1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/functional/bind.h"
13 #include "base/allocator/partition_alloc_features.h"
14 #include "base/allocator/partition_alloc_support.h"
15 #include "base/allocator/partition_allocator/src/partition_alloc/dangling_raw_ptr_checks.h"
16 #include "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_buildflags.h"
17 #include "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_for_testing.h"
18 #include "base/allocator/partition_allocator/src/partition_alloc/partition_root.h"
19 #include "base/functional/callback.h"
20 #include "base/functional/disallow_unretained.h"
21 #include "base/memory/ptr_util.h"
22 #include "base/memory/raw_ptr.h"
23 #include "base/memory/raw_ref.h"
24 #include "base/memory/ref_counted.h"
25 #include "base/memory/weak_ptr.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/test/bind.h"
28 #include "base/test/gtest_util.h"
29 #include "base/test/scoped_feature_list.h"
30 #include "build/build_config.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
35 using ::testing::AnyNumber;
36 using ::testing::ByMove;
37 using ::testing::Mock;
38 using ::testing::Return;
39 using ::testing::StrictMock;
44 class AllowsUnretained {};
46 class BansUnretained {
48 DISALLOW_UNRETAINED();
51 class BansUnretainedInPrivate {
52 DISALLOW_UNRETAINED();
55 class DerivedButBaseBansUnretained : public BansUnretained {};
57 static_assert(internal::TypeSupportsUnretainedV<AllowsUnretained>);
58 static_assert(!internal::TypeSupportsUnretainedV<BansUnretained>);
59 static_assert(!internal::TypeSupportsUnretainedV<BansUnretainedInPrivate>);
60 static_assert(!internal::TypeSupportsUnretainedV<DerivedButBaseBansUnretained>);
65 NoRef(const NoRef&) = delete;
66 // Particularly important in this test to ensure no copies are made.
67 NoRef& operator=(const NoRef&) = delete;
69 MOCK_METHOD0(VoidMethod0, void());
70 MOCK_CONST_METHOD0(VoidConstMethod0, void());
72 MOCK_METHOD0(IntMethod0, int());
73 MOCK_CONST_METHOD0(IntConstMethod0, int());
75 MOCK_METHOD1(VoidMethodWithIntArg, void(int));
76 MOCK_METHOD0(UniquePtrMethod0, std::unique_ptr<int>());
79 class HasRef : public NoRef {
82 HasRef(const HasRef&) = delete;
83 // Particularly important in this test to ensure no copies are made.
84 HasRef& operator=(const HasRef&) = delete;
86 MOCK_CONST_METHOD0(AddRef, void());
87 MOCK_CONST_METHOD0(Release, bool());
88 MOCK_CONST_METHOD0(HasAtLeastOneRef, bool());
91 class HasRefPrivateDtor : public HasRef {
93 ~HasRefPrivateDtor() = default;
96 static const int kParentValue = 1;
97 static const int kChildValue = 2;
101 void AddRef() const {}
102 void Release() const {}
103 bool HasAtLeastOneRef() const { return true; }
104 virtual void VirtualSet() { value = kParentValue; }
105 void NonVirtualSet() { value = kParentValue; }
109 class Child : public Parent {
111 void VirtualSet() override { value = kChildValue; }
112 void NonVirtualSet() { value = kChildValue; }
117 virtual void VirtualSet() { value = kParentValue; }
118 void NonVirtualSet() { value = kParentValue; }
122 class NoRefChild : public NoRefParent {
123 void VirtualSet() override { value = kChildValue; }
124 void NonVirtualSet() { value = kChildValue; }
127 // Used for probing the number of copies and moves that occur if a type must be
128 // coerced during argument forwarding in the Run() methods.
129 struct DerivedCopyMoveCounter {
130 DerivedCopyMoveCounter(int* copies,
132 int* move_constructs,
136 move_constructs_(move_constructs),
137 move_assigns_(move_assigns) {}
138 raw_ptr<int> copies_;
139 raw_ptr<int> assigns_;
140 raw_ptr<int> move_constructs_;
141 raw_ptr<int> move_assigns_;
144 // Used for probing the number of copies and moves in an argument.
145 class CopyMoveCounter {
147 CopyMoveCounter(int* copies,
149 int* move_constructs,
153 move_constructs_(move_constructs),
154 move_assigns_(move_assigns) {}
156 CopyMoveCounter(const CopyMoveCounter& other)
157 : copies_(other.copies_),
158 assigns_(other.assigns_),
159 move_constructs_(other.move_constructs_),
160 move_assigns_(other.move_assigns_) {
164 CopyMoveCounter(CopyMoveCounter&& other)
165 : copies_(other.copies_),
166 assigns_(other.assigns_),
167 move_constructs_(other.move_constructs_),
168 move_assigns_(other.move_assigns_) {
169 (*move_constructs_)++;
172 // Probing for copies from coercion.
173 explicit CopyMoveCounter(const DerivedCopyMoveCounter& other)
174 : copies_(other.copies_),
175 assigns_(other.assigns_),
176 move_constructs_(other.move_constructs_),
177 move_assigns_(other.move_assigns_) {
181 // Probing for moves from coercion.
182 explicit CopyMoveCounter(DerivedCopyMoveCounter&& other)
183 : copies_(other.copies_),
184 assigns_(other.assigns_),
185 move_constructs_(other.move_constructs_),
186 move_assigns_(other.move_assigns_) {
187 (*move_constructs_)++;
190 const CopyMoveCounter& operator=(const CopyMoveCounter& rhs) {
191 copies_ = rhs.copies_;
192 assigns_ = rhs.assigns_;
193 move_constructs_ = rhs.move_constructs_;
194 move_assigns_ = rhs.move_assigns_;
201 const CopyMoveCounter& operator=(CopyMoveCounter&& rhs) {
202 copies_ = rhs.copies_;
203 assigns_ = rhs.assigns_;
204 move_constructs_ = rhs.move_constructs_;
205 move_assigns_ = rhs.move_assigns_;
212 int copies() const { return *copies_; }
215 raw_ptr<int> copies_;
216 raw_ptr<int> assigns_;
217 raw_ptr<int> move_constructs_;
218 raw_ptr<int> move_assigns_;
221 // Used for probing the number of copies in an argument. The instance is a
222 // copyable and non-movable type.
225 CopyCounter(int* copies, int* assigns)
226 : counter_(copies, assigns, nullptr, nullptr) {}
227 CopyCounter(const CopyCounter& other) = default;
228 CopyCounter& operator=(const CopyCounter& other) = default;
230 explicit CopyCounter(const DerivedCopyMoveCounter& other) : counter_(other) {}
232 int copies() const { return counter_.copies(); }
235 CopyMoveCounter counter_;
238 // Used for probing the number of moves in an argument. The instance is a
239 // non-copyable and movable type.
242 MoveCounter(int* move_constructs, int* move_assigns)
243 : counter_(nullptr, nullptr, move_constructs, move_assigns) {}
244 MoveCounter(MoveCounter&& other) : counter_(std::move(other.counter_)) {}
245 MoveCounter& operator=(MoveCounter&& other) {
246 counter_ = std::move(other.counter_);
250 explicit MoveCounter(DerivedCopyMoveCounter&& other)
251 : counter_(std::move(other)) {}
254 CopyMoveCounter counter_;
257 class DeleteCounter {
259 explicit DeleteCounter(int* deletes) : deletes_(deletes) {}
261 ~DeleteCounter() { (*deletes_)++; }
263 void VoidMethod0() {}
266 raw_ptr<int> deletes_;
269 template <typename T>
270 T PassThru(T scoper) {
274 // Some test functions that we can Bind to.
275 template <typename T>
276 T PolymorphicIdentity(T t) {
280 template <typename... Ts>
281 struct VoidPolymorphic {
282 static void Run(Ts... t) {}
285 int Identity(int n) {
289 int ArrayGet(const int array[], int n) {
293 int Sum(int a, int b, int c, int d, int e, int f) {
294 return a + b + c + d + e + f;
297 const char* CStringIdentity(const char* s) {
301 int GetCopies(const CopyMoveCounter& counter) {
302 return counter.copies();
305 int UnwrapNoRefParent(NoRefParent p) {
309 int UnwrapNoRefParentPtr(NoRefParent* p) {
313 int UnwrapNoRefParentConstRef(const NoRefParent& p) {
317 void RefArgSet(int& n) {
321 void PtrArgSet(int* n) {
325 int FunctionWithWeakFirstParam(WeakPtr<NoRef> o, int n) {
329 int FunctionWithScopedRefptrFirstParam(const scoped_refptr<HasRef>& o, int n) {
333 void TakesACallback(const RepeatingClosure& callback) {
337 int Noexcept() noexcept {
341 class NoexceptFunctor {
343 int operator()() noexcept { return 42; }
346 class ConstNoexceptFunctor {
348 int operator()() noexcept { return 42; }
351 class BindTest : public ::testing::Test {
354 const_has_ref_ptr_ = &has_ref_;
355 const_no_ref_ptr_ = &no_ref_;
356 static_func_mock_ptr = &static_func_mock_;
358 BindTest(const BindTest&) = delete;
359 BindTest& operator=(const BindTest&) = delete;
360 ~BindTest() override = default;
362 static void VoidFunc0() { static_func_mock_ptr->VoidMethod0(); }
364 static int IntFunc0() { return static_func_mock_ptr->IntMethod0(); }
365 int NoexceptMethod() noexcept { return 42; }
366 int ConstNoexceptMethod() const noexcept { return 42; }
369 StrictMock<NoRef> no_ref_;
370 StrictMock<HasRef> has_ref_;
371 raw_ptr<const HasRef> const_has_ref_ptr_;
372 raw_ptr<const NoRef> const_no_ref_ptr_;
373 StrictMock<NoRef> static_func_mock_;
375 // Used by the static functions to perform expectations.
376 static StrictMock<NoRef>* static_func_mock_ptr;
379 StrictMock<NoRef>* BindTest::static_func_mock_ptr;
380 StrictMock<NoRef>* g_func_mock_ptr;
383 g_func_mock_ptr->VoidMethod0();
387 return g_func_mock_ptr->IntMethod0();
390 TEST_F(BindTest, BasicTest) {
391 RepeatingCallback<int(int, int, int)> cb = BindRepeating(&Sum, 32, 16, 8);
392 EXPECT_EQ(92, cb.Run(13, 12, 11));
394 RepeatingCallback<int(int, int, int, int, int, int)> c1 = BindRepeating(&Sum);
395 EXPECT_EQ(69, c1.Run(14, 13, 12, 11, 10, 9));
397 RepeatingCallback<int(int, int, int)> c2 = BindRepeating(c1, 32, 16, 8);
398 EXPECT_EQ(86, c2.Run(11, 10, 9));
400 RepeatingCallback<int()> c3 = BindRepeating(c2, 4, 2, 1);
401 EXPECT_EQ(63, c3.Run());
404 // Test that currying the rvalue result of another BindRepeating() works
406 // - rvalue should be usable as argument to BindRepeating().
407 // - multiple runs of resulting RepeatingCallback remain valid.
408 TEST_F(BindTest, CurryingRvalueResultOfBind) {
410 RepeatingClosure cb =
411 BindRepeating(&TakesACallback, BindRepeating(&PtrArgSet, &n));
413 // If we implement BindRepeating() such that the return value has
414 // auto_ptr-like semantics, the second call here will fail because ownership
415 // of the internal BindState<> would have been transferred to a *temporary*
416 // construction of a RepeatingCallback object on the first call.
425 TEST_F(BindTest, RepeatingCallbackBasicTest) {
426 RepeatingCallback<int(int)> c0 = BindRepeating(&Sum, 1, 2, 4, 8, 16);
428 // RepeatingCallback can run via a lvalue-reference.
429 EXPECT_EQ(63, c0.Run(32));
431 // It is valid to call a RepeatingCallback more than once.
432 EXPECT_EQ(54, c0.Run(23));
434 // BindRepeating can handle a RepeatingCallback as the target functor.
435 RepeatingCallback<int()> c1 = BindRepeating(c0, 11);
437 // RepeatingCallback can run via a rvalue-reference.
438 EXPECT_EQ(42, std::move(c1).Run());
440 // BindRepeating can handle a rvalue-reference of RepeatingCallback.
441 EXPECT_EQ(32, BindRepeating(std::move(c0), 1).Run());
444 TEST_F(BindTest, OnceCallbackBasicTest) {
445 OnceCallback<int(int)> c0 = BindOnce(&Sum, 1, 2, 4, 8, 16);
447 // OnceCallback can run via a rvalue-reference.
448 EXPECT_EQ(63, std::move(c0).Run(32));
450 // After running via the rvalue-reference, the value of the OnceCallback
451 // is undefined. The implementation simply clears the instance after the
453 EXPECT_TRUE(c0.is_null());
455 c0 = BindOnce(&Sum, 2, 3, 5, 7, 11);
457 // BindOnce can handle a rvalue-reference of OnceCallback as the target
459 OnceCallback<int()> c1 = BindOnce(std::move(c0), 13);
460 EXPECT_EQ(41, std::move(c1).Run());
462 RepeatingCallback<int(int)> c2 = BindRepeating(&Sum, 2, 3, 5, 7, 11);
463 EXPECT_EQ(41, BindOnce(c2, 13).Run());
466 // IgnoreResult adapter test.
467 // - Function with return value.
468 // - Method with return value.
469 // - Const Method with return.
470 // - Method with return value bound to WeakPtr<>.
471 // - Const Method with return bound to WeakPtr<>.
472 TEST_F(BindTest, IgnoreResultForRepeating) {
473 EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
474 EXPECT_CALL(has_ref_, AddRef()).Times(2);
475 EXPECT_CALL(has_ref_, Release()).Times(2);
476 EXPECT_CALL(has_ref_, HasAtLeastOneRef()).WillRepeatedly(Return(true));
477 EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
478 EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
479 EXPECT_CALL(no_ref_, IntMethod0()).WillOnce(Return(12));
480 EXPECT_CALL(no_ref_, IntConstMethod0()).WillOnce(Return(13));
482 RepeatingClosure normal_func_cb = BindRepeating(IgnoreResult(&IntFunc0));
483 normal_func_cb.Run();
485 RepeatingClosure non_void_method_cb =
486 BindRepeating(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
487 non_void_method_cb.Run();
489 RepeatingClosure non_void_const_method_cb =
490 BindRepeating(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
491 non_void_const_method_cb.Run();
493 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
494 WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
496 RepeatingClosure non_void_weak_method_cb = BindRepeating(
497 IgnoreResult(&NoRef::IntMethod0), weak_factory.GetWeakPtr());
498 non_void_weak_method_cb.Run();
500 RepeatingClosure non_void_weak_const_method_cb = BindRepeating(
501 IgnoreResult(&NoRef::IntConstMethod0), weak_factory.GetWeakPtr());
502 non_void_weak_const_method_cb.Run();
504 weak_factory.InvalidateWeakPtrs();
505 non_void_weak_const_method_cb.Run();
506 non_void_weak_method_cb.Run();
509 TEST_F(BindTest, IgnoreResultForOnce) {
510 EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
511 EXPECT_CALL(has_ref_, AddRef()).Times(2);
512 EXPECT_CALL(has_ref_, Release()).Times(2);
513 EXPECT_CALL(has_ref_, HasAtLeastOneRef()).WillRepeatedly(Return(true));
514 EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
515 EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
517 OnceClosure normal_func_cb = BindOnce(IgnoreResult(&IntFunc0));
518 std::move(normal_func_cb).Run();
520 OnceClosure non_void_method_cb =
521 BindOnce(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
522 std::move(non_void_method_cb).Run();
524 OnceClosure non_void_const_method_cb =
525 BindOnce(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
526 std::move(non_void_const_method_cb).Run();
528 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
529 WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
531 OnceClosure non_void_weak_method_cb =
532 BindOnce(IgnoreResult(&NoRef::IntMethod0), weak_factory.GetWeakPtr());
533 OnceClosure non_void_weak_const_method_cb = BindOnce(
534 IgnoreResult(&NoRef::IntConstMethod0), weak_factory.GetWeakPtr());
536 weak_factory.InvalidateWeakPtrs();
537 std::move(non_void_weak_const_method_cb).Run();
538 std::move(non_void_weak_method_cb).Run();
541 TEST_F(BindTest, IgnoreResultForRepeatingCallback) {
543 RepeatingCallback<int(int)> cb = BindRepeating(
544 [](std::string* s, int i) {
545 *s += "Run" + base::NumberToString(i);
549 RepeatingCallback<void(int)> noreturn = BindRepeating(IgnoreResult(cb));
551 EXPECT_EQ(s, "Run2");
554 TEST_F(BindTest, IgnoreResultForOnceCallback) {
556 OnceCallback<int(int)> cb = BindOnce(
557 [](std::string* s, int i) {
558 *s += "Run" + base::NumberToString(i);
562 OnceCallback<void(int)> noreturn = BindOnce(IgnoreResult(std::move(cb)));
563 std::move(noreturn).Run(2);
564 EXPECT_EQ(s, "Run2");
567 void SetFromRef(int& ref) {
573 TEST_F(BindTest, BindOnceWithNonConstRef) {
576 // Mutates `v` because it's not bound to callback instead it's forwarded by
578 auto cb1 = BindOnce(SetFromRef);
579 std::move(cb1).Run(v);
583 // Mutates `v` through std::reference_wrapper bound to callback.
584 auto cb2 = BindOnce(SetFromRef, std::ref(v));
585 std::move(cb2).Run();
589 // Everything past here following will make a copy of the argument. The copy
590 // will be mutated and leave `v` unmodified.
591 auto cb3 = BindOnce(SetFromRef, base::OwnedRef(v));
592 std::move(cb3).Run();
596 auto cb4 = BindOnce(SetFromRef, base::OwnedRef(ref));
597 std::move(cb4).Run();
601 auto cb5 = BindOnce(SetFromRef, base::OwnedRef(cv));
602 std::move(cb5).Run();
606 auto cb6 = BindOnce(SetFromRef, base::OwnedRef(cref));
607 std::move(cb6).Run();
610 auto cb7 = BindOnce(SetFromRef, base::OwnedRef(1));
611 std::move(cb7).Run();
614 TEST_F(BindTest, BindRepeatingWithNonConstRef) {
617 // Mutates `v` because it's not bound to callback instead it's forwarded by
619 auto cb1 = BindRepeating(SetFromRef);
620 std::move(cb1).Run(v);
624 // Mutates `v` through std::reference_wrapper bound to callback.
625 auto cb2 = BindRepeating(SetFromRef, std::ref(v));
626 std::move(cb2).Run();
630 // Everything past here following will make a copy of the argument. The copy
631 // will be mutated and leave `v` unmodified.
632 auto cb3 = BindRepeating(SetFromRef, base::OwnedRef(v));
633 std::move(cb3).Run();
637 auto cb4 = BindRepeating(SetFromRef, base::OwnedRef(ref));
638 std::move(cb4).Run();
642 auto cb5 = BindRepeating(SetFromRef, base::OwnedRef(cv));
643 std::move(cb5).Run();
647 auto cb6 = BindRepeating(SetFromRef, base::OwnedRef(cref));
648 std::move(cb6).Run();
651 auto cb7 = BindRepeating(SetFromRef, base::OwnedRef(1));
652 std::move(cb7).Run();
655 // Functions that take reference parameters.
656 // - Forced reference parameter type still stores a copy.
657 // - Forced const reference parameter type still stores a copy.
658 TEST_F(BindTest, ReferenceArgumentBindingForRepeating) {
661 const int& const_ref_n = n;
663 RepeatingCallback<int()> ref_copies_cb = BindRepeating(&Identity, ref_n);
664 EXPECT_EQ(n, ref_copies_cb.Run());
666 EXPECT_EQ(n - 1, ref_copies_cb.Run());
668 RepeatingCallback<int()> const_ref_copies_cb =
669 BindRepeating(&Identity, const_ref_n);
670 EXPECT_EQ(n, const_ref_copies_cb.Run());
672 EXPECT_EQ(n - 1, const_ref_copies_cb.Run());
675 TEST_F(BindTest, ReferenceArgumentBindingForOnce) {
678 const int& const_ref_n = n;
680 OnceCallback<int()> ref_copies_cb = BindOnce(&Identity, ref_n);
682 EXPECT_EQ(n - 1, std::move(ref_copies_cb).Run());
684 OnceCallback<int()> const_ref_copies_cb = BindOnce(&Identity, const_ref_n);
686 EXPECT_EQ(n - 1, std::move(const_ref_copies_cb).Run());
689 // Check that we can pass in arrays and have them be stored as a pointer.
690 // - Array of values stores a pointer.
691 // - Array of const values stores a pointer.
692 TEST_F(BindTest, ArrayArgumentBindingForRepeating) {
693 int array[4] = {1, 1, 1, 1};
694 const int(*const_array_ptr)[4] = &array;
696 RepeatingCallback<int()> array_cb = BindRepeating(&ArrayGet, array, 1);
697 EXPECT_EQ(1, array_cb.Run());
699 RepeatingCallback<int()> const_array_cb =
700 BindRepeating(&ArrayGet, *const_array_ptr, 1);
701 EXPECT_EQ(1, const_array_cb.Run());
704 EXPECT_EQ(3, array_cb.Run());
705 EXPECT_EQ(3, const_array_cb.Run());
708 TEST_F(BindTest, ArrayArgumentBindingForOnce) {
709 int array[4] = {1, 1, 1, 1};
710 const int(*const_array_ptr)[4] = &array;
712 OnceCallback<int()> array_cb = BindOnce(&ArrayGet, array, 1);
713 OnceCallback<int()> const_array_cb = BindOnce(&ArrayGet, *const_array_ptr, 1);
716 EXPECT_EQ(3, std::move(array_cb).Run());
717 EXPECT_EQ(3, std::move(const_array_cb).Run());
720 // WeakPtr() support.
721 // - Method bound to WeakPtr<> to non-const object.
722 // - Const method bound to WeakPtr<> to non-const object.
723 // - Const method bound to WeakPtr<> to const object.
724 // - Normal Function with WeakPtr<> as P1 can have return type and is
726 TEST_F(BindTest, WeakPtrForRepeating) {
727 EXPECT_CALL(no_ref_, VoidMethod0());
728 EXPECT_CALL(no_ref_, VoidConstMethod0()).Times(2);
730 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
731 WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
733 RepeatingClosure method_cb =
734 BindRepeating(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
737 RepeatingClosure const_method_cb =
738 BindRepeating(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
739 const_method_cb.Run();
741 RepeatingClosure const_method_const_ptr_cb =
742 BindRepeating(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
743 const_method_const_ptr_cb.Run();
745 RepeatingCallback<int(int)> normal_func_cb =
746 BindRepeating(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
747 EXPECT_EQ(1, normal_func_cb.Run(1));
749 weak_factory.InvalidateWeakPtrs();
750 const_weak_factory.InvalidateWeakPtrs();
753 const_method_cb.Run();
754 const_method_const_ptr_cb.Run();
756 // Still runs even after the pointers are invalidated.
757 EXPECT_EQ(2, normal_func_cb.Run(2));
760 TEST_F(BindTest, WeakPtrForOnce) {
761 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
762 WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
764 OnceClosure method_cb =
765 BindOnce(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
766 OnceClosure const_method_cb =
767 BindOnce(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
768 OnceClosure const_method_const_ptr_cb =
769 BindOnce(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
770 OnceCallback<int(int)> normal_func_cb =
771 BindOnce(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
773 weak_factory.InvalidateWeakPtrs();
774 const_weak_factory.InvalidateWeakPtrs();
776 std::move(method_cb).Run();
777 std::move(const_method_cb).Run();
778 std::move(const_method_const_ptr_cb).Run();
780 // Still runs even after the pointers are invalidated.
781 EXPECT_EQ(2, std::move(normal_func_cb).Run(2));
784 // std::cref() wrapper support.
785 // - Binding w/o std::cref takes a copy.
786 // - Binding a std::cref takes a reference.
787 // - Binding std::cref to a function std::cref does not copy on invoke.
788 TEST_F(BindTest, StdCrefForRepeating) {
791 RepeatingCallback<int()> copy_cb = BindRepeating(&Identity, n);
792 RepeatingCallback<int()> const_ref_cb =
793 BindRepeating(&Identity, std::cref(n));
794 EXPECT_EQ(n, copy_cb.Run());
795 EXPECT_EQ(n, const_ref_cb.Run());
797 EXPECT_EQ(n - 1, copy_cb.Run());
798 EXPECT_EQ(n, const_ref_cb.Run());
802 int move_constructs = 0;
803 int move_assigns = 0;
804 CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
805 RepeatingCallback<int()> all_const_ref_cb =
806 BindRepeating(&GetCopies, std::cref(counter));
807 EXPECT_EQ(0, all_const_ref_cb.Run());
808 EXPECT_EQ(0, copies);
809 EXPECT_EQ(0, assigns);
810 EXPECT_EQ(0, move_constructs);
811 EXPECT_EQ(0, move_assigns);
814 TEST_F(BindTest, StdCrefForOnce) {
817 OnceCallback<int()> copy_cb = BindOnce(&Identity, n);
818 OnceCallback<int()> const_ref_cb = BindOnce(&Identity, std::cref(n));
820 EXPECT_EQ(n - 1, std::move(copy_cb).Run());
821 EXPECT_EQ(n, std::move(const_ref_cb).Run());
825 int move_constructs = 0;
826 int move_assigns = 0;
827 CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
828 OnceCallback<int()> all_const_ref_cb =
829 BindOnce(&GetCopies, std::cref(counter));
830 EXPECT_EQ(0, std::move(all_const_ref_cb).Run());
831 EXPECT_EQ(0, copies);
832 EXPECT_EQ(0, assigns);
833 EXPECT_EQ(0, move_constructs);
834 EXPECT_EQ(0, move_assigns);
837 // Test Owned() support.
838 TEST_F(BindTest, OwnedForRepeatingRawPtr) {
840 DeleteCounter* counter = new DeleteCounter(&deletes);
842 // If we don't capture, delete happens on Callback destruction/reset.
843 // return the same value.
844 RepeatingCallback<DeleteCounter*()> no_capture_cb =
845 BindRepeating(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
846 ASSERT_EQ(counter, no_capture_cb.Run());
847 ASSERT_EQ(counter, no_capture_cb.Run());
848 EXPECT_EQ(0, deletes);
849 no_capture_cb.Reset(); // This should trigger a delete.
850 EXPECT_EQ(1, deletes);
853 counter = new DeleteCounter(&deletes);
854 RepeatingClosure own_object_cb =
855 BindRepeating(&DeleteCounter::VoidMethod0, Owned(counter));
857 EXPECT_EQ(0, deletes);
858 own_object_cb.Reset();
859 EXPECT_EQ(1, deletes);
862 TEST_F(BindTest, OwnedForOnceRawPtr) {
864 DeleteCounter* counter = new DeleteCounter(&deletes);
866 // If we don't capture, delete happens on Callback destruction/reset.
867 // return the same value.
868 OnceCallback<DeleteCounter*()> no_capture_cb =
869 BindOnce(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
870 EXPECT_EQ(0, deletes);
871 no_capture_cb.Reset(); // This should trigger a delete.
872 EXPECT_EQ(1, deletes);
875 counter = new DeleteCounter(&deletes);
876 OnceClosure own_object_cb =
877 BindOnce(&DeleteCounter::VoidMethod0, Owned(counter));
878 EXPECT_EQ(0, deletes);
879 own_object_cb.Reset();
880 EXPECT_EQ(1, deletes);
883 TEST_F(BindTest, OwnedForRepeatingUniquePtr) {
885 auto counter = std::make_unique<DeleteCounter>(&deletes);
886 DeleteCounter* raw_counter = counter.get();
888 // If we don't capture, delete happens on Callback destruction/reset.
889 // return the same value.
890 RepeatingCallback<DeleteCounter*()> no_capture_cb = BindRepeating(
891 &PolymorphicIdentity<DeleteCounter*>, Owned(std::move(counter)));
892 ASSERT_EQ(raw_counter, no_capture_cb.Run());
893 ASSERT_EQ(raw_counter, no_capture_cb.Run());
894 EXPECT_EQ(0, deletes);
895 no_capture_cb.Reset(); // This should trigger a delete.
896 EXPECT_EQ(1, deletes);
899 counter = std::make_unique<DeleteCounter>(&deletes);
900 RepeatingClosure own_object_cb =
901 BindRepeating(&DeleteCounter::VoidMethod0, Owned(std::move(counter)));
903 EXPECT_EQ(0, deletes);
904 own_object_cb.Reset();
905 EXPECT_EQ(1, deletes);
908 TEST_F(BindTest, OwnedForOnceUniquePtr) {
910 auto counter = std::make_unique<DeleteCounter>(&deletes);
912 // If we don't capture, delete happens on Callback destruction/reset.
913 // return the same value.
914 OnceCallback<DeleteCounter*()> no_capture_cb =
915 BindOnce(&PolymorphicIdentity<DeleteCounter*>, Owned(std::move(counter)));
916 EXPECT_EQ(0, deletes);
917 no_capture_cb.Reset(); // This should trigger a delete.
918 EXPECT_EQ(1, deletes);
921 counter = std::make_unique<DeleteCounter>(&deletes);
922 OnceClosure own_object_cb =
923 BindOnce(&DeleteCounter::VoidMethod0, Owned(std::move(counter)));
924 EXPECT_EQ(0, deletes);
925 own_object_cb.Reset();
926 EXPECT_EQ(1, deletes);
930 TEST_F(BindTest, OwnedRefForCounter) {
932 RepeatingCallback<int()> counter_callback =
933 BindRepeating([](int& counter) { return ++counter; }, OwnedRef(counter));
935 EXPECT_EQ(1, counter_callback.Run());
936 EXPECT_EQ(2, counter_callback.Run());
937 EXPECT_EQ(3, counter_callback.Run());
938 EXPECT_EQ(4, counter_callback.Run());
940 EXPECT_EQ(0, counter); // counter should remain unchanged.
943 TEST_F(BindTest, OwnedRefForIgnoringArguments) {
944 OnceCallback<std::string(std::string)> echo_callback =
945 BindOnce([](int& ignore, std::string s) { return s; }, OwnedRef(0));
947 EXPECT_EQ("Hello World", std::move(echo_callback).Run("Hello World"));
950 template <typename T>
951 class BindVariantsTest : public ::testing::Test {};
953 struct RepeatingTestConfig {
954 template <typename Signature>
955 using CallbackType = RepeatingCallback<Signature>;
956 using ClosureType = RepeatingClosure;
958 template <typename F, typename... Args>
959 static CallbackType<internal::MakeUnboundRunType<F, Args...>> Bind(
962 return BindRepeating(std::forward<F>(f), std::forward<Args>(args)...);
966 struct OnceTestConfig {
967 template <typename Signature>
968 using CallbackType = OnceCallback<Signature>;
969 using ClosureType = OnceClosure;
971 template <typename F, typename... Args>
972 static CallbackType<internal::MakeUnboundRunType<F, Args...>> Bind(
975 return BindOnce(std::forward<F>(f), std::forward<Args>(args)...);
979 using BindVariantsTestConfig =
980 ::testing::Types<RepeatingTestConfig, OnceTestConfig>;
981 TYPED_TEST_SUITE(BindVariantsTest, BindVariantsTestConfig);
983 template <typename TypeParam, typename Signature>
984 using CallbackType = typename TypeParam::template CallbackType<Signature>;
986 // Function type support.
987 // - Normal function.
988 // - Normal function bound with non-refcounted first argument.
989 // - Method bound to non-const object.
990 // - Method bound to scoped_refptr.
991 // - Const method bound to non-const object.
992 // - Const method bound to const object.
993 // - Derived classes can be used with pointers to non-virtual base functions.
994 // - Derived classes can be used with pointers to virtual base functions (and
995 // preserve virtual dispatch).
996 TYPED_TEST(BindVariantsTest, FunctionTypeSupport) {
997 using ClosureType = typename TypeParam::ClosureType;
999 StrictMock<HasRef> has_ref;
1000 StrictMock<NoRef> no_ref;
1001 StrictMock<NoRef> static_func_mock;
1002 const HasRef* const_has_ref_ptr = &has_ref;
1003 g_func_mock_ptr = &static_func_mock;
1005 EXPECT_CALL(static_func_mock, VoidMethod0());
1006 EXPECT_CALL(has_ref, AddRef()).Times(4);
1007 EXPECT_CALL(has_ref, Release()).Times(4);
1008 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1009 EXPECT_CALL(has_ref, VoidMethod0()).Times(2);
1010 EXPECT_CALL(has_ref, VoidConstMethod0()).Times(2);
1012 ClosureType normal_cb = TypeParam::Bind(&VoidFunc0);
1013 CallbackType<TypeParam, NoRef*()> normal_non_refcounted_cb =
1014 TypeParam::Bind(&PolymorphicIdentity<NoRef*>, &no_ref);
1015 std::move(normal_cb).Run();
1016 EXPECT_EQ(&no_ref, std::move(normal_non_refcounted_cb).Run());
1018 ClosureType method_cb = TypeParam::Bind(&HasRef::VoidMethod0, &has_ref);
1019 ClosureType method_refptr_cb =
1020 TypeParam::Bind(&HasRef::VoidMethod0, WrapRefCounted(&has_ref));
1021 ClosureType const_method_nonconst_obj_cb =
1022 TypeParam::Bind(&HasRef::VoidConstMethod0, &has_ref);
1023 ClosureType const_method_const_obj_cb =
1024 TypeParam::Bind(&HasRef::VoidConstMethod0, const_has_ref_ptr);
1025 std::move(method_cb).Run();
1026 std::move(method_refptr_cb).Run();
1027 std::move(const_method_nonconst_obj_cb).Run();
1028 std::move(const_method_const_obj_cb).Run();
1032 ClosureType virtual_set_cb = TypeParam::Bind(&Parent::VirtualSet, &child);
1033 std::move(virtual_set_cb).Run();
1034 EXPECT_EQ(kChildValue, child.value);
1037 ClosureType non_virtual_set_cb =
1038 TypeParam::Bind(&Parent::NonVirtualSet, &child);
1039 std::move(non_virtual_set_cb).Run();
1040 EXPECT_EQ(kParentValue, child.value);
1043 // Return value support.
1044 // - Function with return value.
1045 // - Method with return value.
1046 // - Const method with return value.
1047 // - Move-only return value.
1048 TYPED_TEST(BindVariantsTest, ReturnValues) {
1049 StrictMock<NoRef> static_func_mock;
1050 StrictMock<HasRef> has_ref;
1051 g_func_mock_ptr = &static_func_mock;
1052 const HasRef* const_has_ref_ptr = &has_ref;
1054 EXPECT_CALL(static_func_mock, IntMethod0()).WillOnce(Return(1337));
1055 EXPECT_CALL(has_ref, AddRef()).Times(4);
1056 EXPECT_CALL(has_ref, Release()).Times(4);
1057 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1058 EXPECT_CALL(has_ref, IntMethod0()).WillOnce(Return(31337));
1059 EXPECT_CALL(has_ref, IntConstMethod0())
1060 .WillOnce(Return(41337))
1061 .WillOnce(Return(51337));
1062 EXPECT_CALL(has_ref, UniquePtrMethod0())
1063 .WillOnce(Return(ByMove(std::make_unique<int>(42))));
1065 CallbackType<TypeParam, int()> normal_cb = TypeParam::Bind(&IntFunc0);
1066 CallbackType<TypeParam, int()> method_cb =
1067 TypeParam::Bind(&HasRef::IntMethod0, &has_ref);
1068 CallbackType<TypeParam, int()> const_method_nonconst_obj_cb =
1069 TypeParam::Bind(&HasRef::IntConstMethod0, &has_ref);
1070 CallbackType<TypeParam, int()> const_method_const_obj_cb =
1071 TypeParam::Bind(&HasRef::IntConstMethod0, const_has_ref_ptr);
1072 CallbackType<TypeParam, std::unique_ptr<int>()> move_only_rv_cb =
1073 TypeParam::Bind(&HasRef::UniquePtrMethod0, &has_ref);
1074 EXPECT_EQ(1337, std::move(normal_cb).Run());
1075 EXPECT_EQ(31337, std::move(method_cb).Run());
1076 EXPECT_EQ(41337, std::move(const_method_nonconst_obj_cb).Run());
1077 EXPECT_EQ(51337, std::move(const_method_const_obj_cb).Run());
1078 EXPECT_EQ(42, *std::move(move_only_rv_cb).Run());
1081 // Argument binding tests.
1082 // - Argument binding to primitive.
1083 // - Argument binding to primitive pointer.
1084 // - Argument binding to a literal integer.
1085 // - Argument binding to a literal string.
1086 // - Argument binding with template function.
1087 // - Argument binding to an object.
1088 // - Argument binding to pointer to incomplete type.
1089 // - Argument gets type converted.
1090 // - Pointer argument gets converted.
1091 // - Const Reference forces conversion.
1092 TYPED_TEST(BindVariantsTest, ArgumentBinding) {
1095 EXPECT_EQ(n, TypeParam::Bind(&Identity, n).Run());
1096 EXPECT_EQ(&n, TypeParam::Bind(&PolymorphicIdentity<int*>, &n).Run());
1097 EXPECT_EQ(3, TypeParam::Bind(&Identity, 3).Run());
1098 EXPECT_STREQ("hi", TypeParam::Bind(&CStringIdentity, "hi").Run());
1099 EXPECT_EQ(4, TypeParam::Bind(&PolymorphicIdentity<int>, 4).Run());
1103 EXPECT_EQ(5, TypeParam::Bind(&UnwrapNoRefParent, p).Run());
1107 EXPECT_EQ(6, TypeParam::Bind(&UnwrapNoRefParent, c).Run());
1110 EXPECT_EQ(7, TypeParam::Bind(&UnwrapNoRefParentPtr, &c).Run());
1113 EXPECT_EQ(8, TypeParam::Bind(&UnwrapNoRefParentConstRef, c).Run());
1116 // Unbound argument type support tests.
1118 // - Unbound pointer.
1119 // - Unbound reference.
1120 // - Unbound const reference.
1121 // - Unbound unsized array.
1122 // - Unbound sized array.
1123 // - Unbound array-of-arrays.
1124 TYPED_TEST(BindVariantsTest, UnboundArgumentTypeSupport) {
1125 CallbackType<TypeParam, void(int)> unbound_value_cb =
1126 TypeParam::Bind(&VoidPolymorphic<int>::Run);
1127 CallbackType<TypeParam, void(int*)> unbound_pointer_cb =
1128 TypeParam::Bind(&VoidPolymorphic<int*>::Run);
1129 CallbackType<TypeParam, void(int&)> unbound_ref_cb =
1130 TypeParam::Bind(&VoidPolymorphic<int&>::Run);
1131 CallbackType<TypeParam, void(const int&)> unbound_const_ref_cb =
1132 TypeParam::Bind(&VoidPolymorphic<const int&>::Run);
1133 CallbackType<TypeParam, void(int[])> unbound_unsized_array_cb =
1134 TypeParam::Bind(&VoidPolymorphic<int[]>::Run);
1135 CallbackType<TypeParam, void(int[2])> unbound_sized_array_cb =
1136 TypeParam::Bind(&VoidPolymorphic<int[2]>::Run);
1137 CallbackType<TypeParam, void(int[][2])> unbound_array_of_arrays_cb =
1138 TypeParam::Bind(&VoidPolymorphic<int[][2]>::Run);
1139 CallbackType<TypeParam, void(int&)> unbound_ref_with_bound_arg =
1140 TypeParam::Bind(&VoidPolymorphic<int, int&>::Run, 1);
1143 // Function with unbound reference parameter.
1144 // - Original parameter is modified by callback.
1145 TYPED_TEST(BindVariantsTest, UnboundReferenceSupport) {
1147 CallbackType<TypeParam, void(int&)> unbound_ref_cb =
1148 TypeParam::Bind(&RefArgSet);
1149 std::move(unbound_ref_cb).Run(n);
1153 // Unretained() wrapper support.
1154 // - Method bound to Unretained() non-const object.
1155 // - Const method bound to Unretained() non-const object.
1156 // - Const method bound to Unretained() const object.
1157 TYPED_TEST(BindVariantsTest, Unretained) {
1158 StrictMock<NoRef> no_ref;
1159 const NoRef* const_no_ref_ptr = &no_ref;
1161 EXPECT_CALL(no_ref, VoidMethod0());
1162 EXPECT_CALL(no_ref, VoidConstMethod0()).Times(2);
1164 TypeParam::Bind(&NoRef::VoidMethod0, Unretained(&no_ref)).Run();
1165 TypeParam::Bind(&NoRef::VoidConstMethod0, Unretained(&no_ref)).Run();
1166 TypeParam::Bind(&NoRef::VoidConstMethod0, Unretained(const_no_ref_ptr)).Run();
1169 TYPED_TEST(BindVariantsTest, ScopedRefptr) {
1170 StrictMock<HasRef> has_ref;
1171 EXPECT_CALL(has_ref, AddRef()).Times(1);
1172 EXPECT_CALL(has_ref, Release()).Times(1);
1173 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1175 const scoped_refptr<HasRef> refptr(&has_ref);
1176 CallbackType<TypeParam, int()> scoped_refptr_const_ref_cb = TypeParam::Bind(
1177 &FunctionWithScopedRefptrFirstParam, std::cref(refptr), 1);
1178 EXPECT_EQ(1, std::move(scoped_refptr_const_ref_cb).Run());
1181 TYPED_TEST(BindVariantsTest, UniquePtrReceiver) {
1182 std::unique_ptr<StrictMock<NoRef>> no_ref(new StrictMock<NoRef>);
1183 EXPECT_CALL(*no_ref, VoidMethod0()).Times(1);
1184 TypeParam::Bind(&NoRef::VoidMethod0, std::move(no_ref)).Run();
1187 TYPED_TEST(BindVariantsTest, ImplicitRefPtrReceiver) {
1188 StrictMock<HasRef> has_ref;
1189 EXPECT_CALL(has_ref, AddRef()).Times(1);
1190 EXPECT_CALL(has_ref, Release()).Times(1);
1191 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1193 HasRef* ptr = &has_ref;
1194 auto ptr_cb = TypeParam::Bind(&HasRef::HasAtLeastOneRef, ptr);
1195 EXPECT_EQ(1, std::move(ptr_cb).Run());
1198 TYPED_TEST(BindVariantsTest, RawPtrReceiver) {
1199 StrictMock<HasRef> has_ref;
1200 EXPECT_CALL(has_ref, AddRef()).Times(1);
1201 EXPECT_CALL(has_ref, Release()).Times(1);
1202 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1204 raw_ptr<HasRef> rawptr(&has_ref);
1205 auto rawptr_cb = TypeParam::Bind(&HasRef::HasAtLeastOneRef, rawptr);
1206 EXPECT_EQ(1, std::move(rawptr_cb).Run());
1209 TYPED_TEST(BindVariantsTest, UnretainedRawRefReceiver) {
1210 StrictMock<HasRef> has_ref;
1211 EXPECT_CALL(has_ref, AddRef()).Times(0);
1212 EXPECT_CALL(has_ref, Release()).Times(0);
1213 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1215 raw_ref<HasRef> raw_has_ref(has_ref);
1217 TypeParam::Bind(&HasRef::HasAtLeastOneRef, Unretained(raw_has_ref));
1218 EXPECT_EQ(1, std::move(has_ref_cb).Run());
1220 StrictMock<NoRef> no_ref;
1221 EXPECT_CALL(has_ref, IntMethod0()).WillRepeatedly(Return(1));
1223 raw_ref<NoRef> raw_no_ref(has_ref);
1224 auto no_ref_cb = TypeParam::Bind(&NoRef::IntMethod0, Unretained(raw_no_ref));
1225 EXPECT_EQ(1, std::move(no_ref_cb).Run());
1228 // Tests for Passed() wrapper support:
1229 // - Passed() can be constructed from a pointer to scoper.
1230 // - Passed() can be constructed from a scoper rvalue.
1231 // - Using Passed() gives Callback Ownership.
1232 // - Ownership is transferred from Callback to callee on the first Run().
1233 // - Callback supports unbound arguments.
1234 template <typename T>
1235 class BindMoveOnlyTypeTest : public ::testing::Test {};
1237 struct CustomDeleter {
1238 void operator()(DeleteCounter* c) { delete c; }
1241 using MoveOnlyTypesToTest =
1242 ::testing::Types<std::unique_ptr<DeleteCounter>,
1243 std::unique_ptr<DeleteCounter, CustomDeleter>>;
1244 TYPED_TEST_SUITE(BindMoveOnlyTypeTest, MoveOnlyTypesToTest);
1246 TYPED_TEST(BindMoveOnlyTypeTest, PassedToBoundCallback) {
1249 TypeParam ptr(new DeleteCounter(&deletes));
1250 RepeatingCallback<TypeParam()> callback =
1251 BindRepeating(&PassThru<TypeParam>, Passed(&ptr));
1252 EXPECT_FALSE(ptr.get());
1253 EXPECT_EQ(0, deletes);
1255 // If we never invoke the Callback, it retains ownership and deletes.
1257 EXPECT_EQ(1, deletes);
1260 TYPED_TEST(BindMoveOnlyTypeTest, PassedWithRvalue) {
1262 RepeatingCallback<TypeParam()> callback = BindRepeating(
1263 &PassThru<TypeParam>, Passed(TypeParam(new DeleteCounter(&deletes))));
1264 EXPECT_EQ(0, deletes);
1266 // If we never invoke the Callback, it retains ownership and deletes.
1268 EXPECT_EQ(1, deletes);
1271 // Check that ownership can be transferred back out.
1272 TYPED_TEST(BindMoveOnlyTypeTest, ReturnMoveOnlyType) {
1274 DeleteCounter* counter = new DeleteCounter(&deletes);
1275 RepeatingCallback<TypeParam()> callback =
1276 BindRepeating(&PassThru<TypeParam>, Passed(TypeParam(counter)));
1277 TypeParam result = callback.Run();
1278 ASSERT_EQ(counter, result.get());
1279 EXPECT_EQ(0, deletes);
1281 // Resetting does not delete since ownership was transferred.
1283 EXPECT_EQ(0, deletes);
1285 // Ensure that we actually did get ownership.
1287 EXPECT_EQ(1, deletes);
1290 TYPED_TEST(BindMoveOnlyTypeTest, UnboundForwarding) {
1292 TypeParam ptr(new DeleteCounter(&deletes));
1293 // Test unbound argument forwarding.
1294 RepeatingCallback<TypeParam(TypeParam)> cb_unbound =
1295 BindRepeating(&PassThru<TypeParam>);
1296 cb_unbound.Run(std::move(ptr));
1297 EXPECT_EQ(1, deletes);
1300 void VerifyVector(const std::vector<std::unique_ptr<int>>& v) {
1301 ASSERT_EQ(1u, v.size());
1302 EXPECT_EQ(12345, *v[0]);
1305 std::vector<std::unique_ptr<int>> AcceptAndReturnMoveOnlyVector(
1306 std::vector<std::unique_ptr<int>> v) {
1311 // Test that a vector containing move-only types can be used with Callback.
1312 TEST_F(BindTest, BindMoveOnlyVector) {
1313 using MoveOnlyVector = std::vector<std::unique_ptr<int>>;
1316 v.push_back(std::make_unique<int>(12345));
1318 // Early binding should work:
1319 base::RepeatingCallback<MoveOnlyVector()> bound_cb =
1320 base::BindRepeating(&AcceptAndReturnMoveOnlyVector, Passed(&v));
1321 MoveOnlyVector intermediate_result = bound_cb.Run();
1322 VerifyVector(intermediate_result);
1324 // As should passing it as an argument to Run():
1325 base::RepeatingCallback<MoveOnlyVector(MoveOnlyVector)> unbound_cb =
1326 base::BindRepeating(&AcceptAndReturnMoveOnlyVector);
1327 MoveOnlyVector final_result = unbound_cb.Run(std::move(intermediate_result));
1328 VerifyVector(final_result);
1331 // Argument copy-constructor usage for non-reference copy-only parameters.
1332 // - Bound arguments are only copied once.
1333 // - Forwarded arguments are only copied once.
1334 // - Forwarded arguments with coercions are only copied twice (once for the
1335 // coercion, and one for the final dispatch).
1336 TEST_F(BindTest, ArgumentCopies) {
1340 CopyCounter counter(&copies, &assigns);
1341 BindRepeating(&VoidPolymorphic<CopyCounter>::Run, counter);
1342 EXPECT_EQ(1, copies);
1343 EXPECT_EQ(0, assigns);
1347 BindRepeating(&VoidPolymorphic<CopyCounter>::Run,
1348 CopyCounter(&copies, &assigns));
1349 EXPECT_EQ(1, copies);
1350 EXPECT_EQ(0, assigns);
1354 BindRepeating(&VoidPolymorphic<CopyCounter>::Run).Run(counter);
1355 EXPECT_EQ(2, copies);
1356 EXPECT_EQ(0, assigns);
1360 BindRepeating(&VoidPolymorphic<CopyCounter>::Run)
1361 .Run(CopyCounter(&copies, &assigns));
1362 EXPECT_EQ(1, copies);
1363 EXPECT_EQ(0, assigns);
1367 DerivedCopyMoveCounter derived(&copies, &assigns, nullptr, nullptr);
1368 BindRepeating(&VoidPolymorphic<CopyCounter>::Run).Run(CopyCounter(derived));
1369 EXPECT_EQ(2, copies);
1370 EXPECT_EQ(0, assigns);
1374 BindRepeating(&VoidPolymorphic<CopyCounter>::Run)
1376 DerivedCopyMoveCounter(&copies, &assigns, nullptr, nullptr)));
1377 EXPECT_EQ(2, copies);
1378 EXPECT_EQ(0, assigns);
1381 // Argument move-constructor usage for move-only parameters.
1382 // - Bound arguments passed by move are not copied.
1383 TEST_F(BindTest, ArgumentMoves) {
1384 int move_constructs = 0;
1385 int move_assigns = 0;
1387 BindRepeating(&VoidPolymorphic<const MoveCounter&>::Run,
1388 MoveCounter(&move_constructs, &move_assigns));
1389 EXPECT_EQ(1, move_constructs);
1390 EXPECT_EQ(0, move_assigns);
1392 // TODO(tzik): Support binding move-only type into a non-reference parameter
1393 // of a variant of Callback.
1395 move_constructs = 0;
1397 BindRepeating(&VoidPolymorphic<MoveCounter>::Run)
1398 .Run(MoveCounter(&move_constructs, &move_assigns));
1399 EXPECT_EQ(1, move_constructs);
1400 EXPECT_EQ(0, move_assigns);
1402 move_constructs = 0;
1404 BindRepeating(&VoidPolymorphic<MoveCounter>::Run)
1405 .Run(MoveCounter(DerivedCopyMoveCounter(
1406 nullptr, nullptr, &move_constructs, &move_assigns)));
1407 EXPECT_EQ(2, move_constructs);
1408 EXPECT_EQ(0, move_assigns);
1411 // Argument constructor usage for non-reference movable-copyable
1413 // - Bound arguments passed by move are not copied.
1414 // - Forwarded arguments are only copied once.
1415 // - Forwarded arguments with coercions are only copied once and moved once.
1416 TEST_F(BindTest, ArgumentCopiesAndMoves) {
1419 int move_constructs = 0;
1420 int move_assigns = 0;
1422 CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
1423 BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run, counter);
1424 EXPECT_EQ(1, copies);
1425 EXPECT_EQ(0, assigns);
1426 EXPECT_EQ(0, move_constructs);
1427 EXPECT_EQ(0, move_assigns);
1431 move_constructs = 0;
1434 &VoidPolymorphic<CopyMoveCounter>::Run,
1435 CopyMoveCounter(&copies, &assigns, &move_constructs, &move_assigns));
1436 EXPECT_EQ(0, copies);
1437 EXPECT_EQ(0, assigns);
1438 EXPECT_EQ(1, move_constructs);
1439 EXPECT_EQ(0, move_assigns);
1443 move_constructs = 0;
1445 BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run).Run(counter);
1446 EXPECT_EQ(1, copies);
1447 EXPECT_EQ(0, assigns);
1448 EXPECT_EQ(1, move_constructs);
1449 EXPECT_EQ(0, move_assigns);
1453 move_constructs = 0;
1455 BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
1456 .Run(CopyMoveCounter(&copies, &assigns, &move_constructs, &move_assigns));
1457 EXPECT_EQ(0, copies);
1458 EXPECT_EQ(0, assigns);
1459 EXPECT_EQ(1, move_constructs);
1460 EXPECT_EQ(0, move_assigns);
1462 DerivedCopyMoveCounter derived_counter(&copies, &assigns, &move_constructs,
1466 move_constructs = 0;
1468 BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
1469 .Run(CopyMoveCounter(derived_counter));
1470 EXPECT_EQ(1, copies);
1471 EXPECT_EQ(0, assigns);
1472 EXPECT_EQ(1, move_constructs);
1473 EXPECT_EQ(0, move_assigns);
1477 move_constructs = 0;
1479 BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
1480 .Run(CopyMoveCounter(DerivedCopyMoveCounter(
1481 &copies, &assigns, &move_constructs, &move_assigns)));
1482 EXPECT_EQ(0, copies);
1483 EXPECT_EQ(0, assigns);
1484 EXPECT_EQ(2, move_constructs);
1485 EXPECT_EQ(0, move_assigns);
1488 TEST_F(BindTest, CapturelessLambda) {
1489 EXPECT_FALSE(internal::IsCallableObject<void>::value);
1490 EXPECT_FALSE(internal::IsCallableObject<int>::value);
1491 EXPECT_FALSE(internal::IsCallableObject<void (*)()>::value);
1492 EXPECT_FALSE(internal::IsCallableObject<void (NoRef::*)()>::value);
1495 EXPECT_TRUE(internal::IsCallableObject<decltype(f)>::value);
1498 auto g = [i] { (void)i; };
1499 EXPECT_TRUE(internal::IsCallableObject<decltype(g)>::value);
1501 auto h = [](int, double) { return 'k'; };
1502 EXPECT_TRUE((std::is_same_v<char(int, double),
1503 internal::ExtractCallableRunType<decltype(h)>>));
1505 EXPECT_EQ(42, BindRepeating([] { return 42; }).Run());
1506 EXPECT_EQ(42, BindRepeating([](int i) { return i * 7; }, 6).Run());
1509 base::RepeatingCallback<void(int)> cb =
1510 BindRepeating([](int* x, int i) { *x *= i; }, Unretained(&x));
1517 TEST_F(BindTest, EmptyFunctor) {
1518 struct NonEmptyFunctor {
1519 int operator()() const { return x; }
1523 struct EmptyFunctor {
1524 int operator()() { return 42; }
1527 struct EmptyFunctorConst {
1528 int operator()() const { return 42; }
1531 EXPECT_TRUE(internal::IsCallableObject<NonEmptyFunctor>::value);
1532 EXPECT_TRUE(internal::IsCallableObject<EmptyFunctor>::value);
1533 EXPECT_TRUE(internal::IsCallableObject<EmptyFunctorConst>::value);
1534 EXPECT_EQ(42, BindOnce(EmptyFunctor()).Run());
1535 EXPECT_EQ(42, BindOnce(EmptyFunctorConst()).Run());
1536 EXPECT_EQ(42, BindRepeating(EmptyFunctorConst()).Run());
1539 TEST_F(BindTest, CapturingLambdaForTesting) {
1540 // Test copyable lambdas.
1542 EXPECT_EQ(42, BindLambdaForTesting([=](int y) { return x * y; }).Run(7));
1544 BindLambdaForTesting([=](int y) mutable { return x *= y; }).Run(7));
1545 auto f = [x](std::unique_ptr<int> y) { return x * *y; };
1546 EXPECT_EQ(42, BindLambdaForTesting(f).Run(std::make_unique<int>(7)));
1548 // Test move-only lambdas.
1549 auto y = std::make_unique<int>(7);
1550 auto g = [y = std::move(y)](int& x) mutable {
1551 return x * *std::exchange(y, nullptr);
1553 EXPECT_EQ(42, BindLambdaForTesting(std::move(g)).Run(x));
1555 y = std::make_unique<int>(7);
1556 auto h = [x, y = std::move(y)] { return x * *y; };
1557 EXPECT_EQ(42, BindLambdaForTesting(std::move(h)).Run());
1560 TEST_F(BindTest, Cancellation) {
1561 EXPECT_CALL(no_ref_, VoidMethodWithIntArg(_)).Times(2);
1563 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
1564 RepeatingCallback<void(int)> cb =
1565 BindRepeating(&NoRef::VoidMethodWithIntArg, weak_factory.GetWeakPtr());
1566 RepeatingClosure cb2 = BindRepeating(cb, 8);
1567 OnceClosure cb3 = BindOnce(cb, 8);
1569 OnceCallback<void(int)> cb4 =
1570 BindOnce(&NoRef::VoidMethodWithIntArg, weak_factory.GetWeakPtr());
1571 EXPECT_FALSE(cb4.IsCancelled());
1573 OnceClosure cb5 = BindOnce(std::move(cb4), 8);
1575 EXPECT_FALSE(cb.IsCancelled());
1576 EXPECT_FALSE(cb2.IsCancelled());
1577 EXPECT_FALSE(cb3.IsCancelled());
1578 EXPECT_FALSE(cb5.IsCancelled());
1583 weak_factory.InvalidateWeakPtrs();
1585 EXPECT_TRUE(cb.IsCancelled());
1586 EXPECT_TRUE(cb2.IsCancelled());
1587 EXPECT_TRUE(cb3.IsCancelled());
1588 EXPECT_TRUE(cb5.IsCancelled());
1592 std::move(cb3).Run();
1593 std::move(cb5).Run();
1596 TEST_F(BindTest, OnceCallback) {
1597 // Check if Callback variants have declarations of conversions as expected.
1598 // Copy constructor and assignment of RepeatingCallback.
1600 std::is_constructible_v<RepeatingClosure, const RepeatingClosure&>,
1601 "RepeatingClosure should be copyable.");
1602 static_assert(std::is_assignable_v<RepeatingClosure, const RepeatingClosure&>,
1603 "RepeatingClosure should be copy-assignable.");
1605 // Move constructor and assignment of RepeatingCallback.
1606 static_assert(std::is_constructible_v<RepeatingClosure, RepeatingClosure&&>,
1607 "RepeatingClosure should be movable.");
1608 static_assert(std::is_assignable_v<RepeatingClosure, RepeatingClosure&&>,
1609 "RepeatingClosure should be move-assignable");
1611 // Conversions from OnceCallback to RepeatingCallback.
1612 static_assert(!std::is_constructible_v<RepeatingClosure, const OnceClosure&>,
1613 "OnceClosure should not be convertible to RepeatingClosure.");
1614 static_assert(!std::is_assignable_v<RepeatingClosure, const OnceClosure&>,
1615 "OnceClosure should not be convertible to RepeatingClosure.");
1617 // Destructive conversions from OnceCallback to RepeatingCallback.
1618 static_assert(!std::is_constructible_v<RepeatingClosure, OnceClosure&&>,
1619 "OnceClosure should not be convertible to RepeatingClosure.");
1620 static_assert(!std::is_assignable_v<RepeatingClosure, OnceClosure&&>,
1621 "OnceClosure should not be convertible to RepeatingClosure.");
1623 // Copy constructor and assignment of OnceCallback.
1624 static_assert(!std::is_constructible_v<OnceClosure, const OnceClosure&>,
1625 "OnceClosure should not be copyable.");
1626 static_assert(!std::is_assignable_v<OnceClosure, const OnceClosure&>,
1627 "OnceClosure should not be copy-assignable");
1629 // Move constructor and assignment of OnceCallback.
1630 static_assert(std::is_constructible_v<OnceClosure, OnceClosure&&>,
1631 "OnceClosure should be movable.");
1632 static_assert(std::is_assignable_v<OnceClosure, OnceClosure&&>,
1633 "OnceClosure should be move-assignable.");
1635 // Conversions from RepeatingCallback to OnceCallback.
1636 static_assert(std::is_constructible_v<OnceClosure, const RepeatingClosure&>,
1637 "RepeatingClosure should be convertible to OnceClosure.");
1638 static_assert(std::is_assignable_v<OnceClosure, const RepeatingClosure&>,
1639 "RepeatingClosure should be convertible to OnceClosure.");
1641 // Destructive conversions from RepeatingCallback to OnceCallback.
1642 static_assert(std::is_constructible_v<OnceClosure, RepeatingClosure&&>,
1643 "RepeatingClosure should be convertible to OnceClosure.");
1644 static_assert(std::is_assignable_v<OnceClosure, RepeatingClosure&&>,
1645 "RepeatingClosure should be covretible to OnceClosure.");
1647 OnceClosure cb = BindOnce(&VoidPolymorphic<>::Run);
1648 std::move(cb).Run();
1650 // RepeatingCallback should be convertible to OnceCallback.
1651 OnceClosure cb2 = BindRepeating(&VoidPolymorphic<>::Run);
1652 std::move(cb2).Run();
1654 RepeatingClosure cb3 = BindRepeating(&VoidPolymorphic<>::Run);
1656 std::move(cb).Run();
1658 cb = std::move(cb2);
1660 OnceCallback<void(int)> cb4 =
1661 BindOnce(&VoidPolymorphic<std::unique_ptr<int>, int>::Run,
1662 std::make_unique<int>(0));
1663 BindOnce(std::move(cb4), 1).Run();
1666 // Callback construction and assignment tests.
1667 // - Construction from an InvokerStorageHolder should not cause ref/deref.
1668 // - Assignment from other callback should only cause one ref
1670 // TODO(ajwong): Is there actually a way to test this?
1672 #if BUILDFLAG(IS_WIN)
1673 int __fastcall FastCallFunc(int n) {
1677 int __stdcall StdCallFunc(int n) {
1681 // Windows specific calling convention support.
1682 // - Can bind a __fastcall function.
1683 // - Can bind a __stdcall function.
1684 // - Can bind const and non-const __stdcall methods.
1685 TEST_F(BindTest, WindowsCallingConventions) {
1686 auto fastcall_cb = BindRepeating(&FastCallFunc, 1);
1687 EXPECT_EQ(1, fastcall_cb.Run());
1689 auto stdcall_cb = BindRepeating(&StdCallFunc, 2);
1690 EXPECT_EQ(2, stdcall_cb.Run());
1692 class MethodHolder {
1694 int __stdcall Func(int n) { return n; }
1695 int __stdcall ConstFunc(int n) const { return -n; }
1699 auto stdcall_method_cb =
1700 BindRepeating(&MethodHolder::Func, base::Unretained(&obj), 1);
1701 EXPECT_EQ(1, stdcall_method_cb.Run());
1703 const MethodHolder const_obj;
1704 auto stdcall_const_method_cb =
1705 BindRepeating(&MethodHolder::ConstFunc, base::Unretained(&const_obj), 1);
1706 EXPECT_EQ(-1, stdcall_const_method_cb.Run());
1710 // Test unwrapping the various wrapping functions.
1712 TEST_F(BindTest, UnwrapUnretained) {
1714 auto unretained = Unretained(&i);
1715 EXPECT_EQ(&i, internal::Unwrap(unretained));
1716 EXPECT_EQ(&i, internal::Unwrap(std::move(unretained)));
1719 TEST_F(BindTest, UnwrapRetainedRef) {
1720 auto p = MakeRefCounted<RefCountedData<int>>();
1721 auto retained_ref = RetainedRef(p);
1722 EXPECT_EQ(p.get(), internal::Unwrap(retained_ref));
1723 EXPECT_EQ(p.get(), internal::Unwrap(std::move(retained_ref)));
1726 TEST_F(BindTest, UnwrapOwned) {
1729 auto owned = Owned(p);
1730 EXPECT_EQ(p, internal::Unwrap(owned));
1731 EXPECT_EQ(p, internal::Unwrap(std::move(owned)));
1735 auto p = std::make_unique<int>();
1736 int* raw_p = p.get();
1737 auto owned = Owned(std::move(p));
1738 EXPECT_EQ(raw_p, internal::Unwrap(owned));
1739 EXPECT_EQ(raw_p, internal::Unwrap(std::move(owned)));
1743 TEST_F(BindTest, UnwrapPassed) {
1745 auto passed = Passed(WrapUnique(p));
1746 EXPECT_EQ(p, internal::Unwrap(passed).get());
1749 EXPECT_EQ(p, internal::Unwrap(Passed(WrapUnique(p))).get());
1752 TEST_F(BindTest, BindNoexcept) {
1753 EXPECT_EQ(42, base::BindOnce(&Noexcept).Run());
1756 base::BindOnce(&BindTest::NoexceptMethod, base::Unretained(this)).Run());
1758 42, base::BindOnce(&BindTest::ConstNoexceptMethod, base::Unretained(this))
1760 EXPECT_EQ(42, base::BindOnce(NoexceptFunctor()).Run());
1761 EXPECT_EQ(42, base::BindOnce(ConstNoexceptFunctor()).Run());
1764 int PingPong(int* i_ptr) {
1768 TEST_F(BindTest, BindAndCallbacks) {
1770 raw_ptr<int> p = &i;
1772 auto callback = base::BindOnce(PingPong, base::Unretained(p));
1773 int res = std::move(callback).Run();
1774 EXPECT_EQ(123, res);
1777 TEST_F(BindTest, ConvertibleArgs) {
1778 // Create two types S and T, such that you can convert a T to an S, but you
1779 // cannot construct an S from a T.
1783 explicit S(const T&) {}
1786 // NOLINTNEXTLINE(google-explicit-constructor)
1787 operator S() const { return S(*this); }
1789 static_assert(!std::is_constructible_v<S, T>);
1790 static_assert(std::is_convertible_v<T, S>);
1792 // Ensure it's possible to pass a T to a function expecting an S.
1793 void (*foo)(S) = +[](S) {};
1795 auto callback = base::BindOnce(foo, t);
1796 std::move(callback).Run();
1801 // This simulates a race weak pointer that, unlike our `base::WeakPtr<>`,
1802 // may become invalidated between `operator bool()` is tested and `Lock()`
1803 // is called in the implementation of `Unwrap()`.
1804 template <typename T>
1805 struct MockRacyWeakPtr {
1806 explicit MockRacyWeakPtr(T*) {}
1807 T* Lock() const { return nullptr; }
1809 explicit operator bool() const { return true; }
1812 template <typename T>
1813 struct IsWeakReceiver<MockRacyWeakPtr<T>> : std::true_type {};
1815 template <typename T>
1816 struct BindUnwrapTraits<MockRacyWeakPtr<T>> {
1817 static T* Unwrap(const MockRacyWeakPtr<T>& o) { return o.Lock(); }
1820 template <typename T>
1821 struct MaybeValidTraits<MockRacyWeakPtr<T>> {
1822 static bool MaybeValid(const MockRacyWeakPtr<T>& o) { return true; }
1827 // Note this only covers a case of racy weak pointer invalidation. Other
1828 // weak pointer scenarios (such as a valid pointer) are covered
1829 // in BindTest.WeakPtrFor{Once,Repeating}.
1830 TEST_F(BindTest, BindRacyWeakPtrTest) {
1831 MockRacyWeakPtr<NoRef> weak(&no_ref_);
1833 RepeatingClosure cb = base::BindRepeating(&NoRef::VoidMethod0, weak);
1837 // Test null callbacks cause a DCHECK.
1838 TEST(BindDeathTest, NullCallback) {
1839 base::RepeatingCallback<void(int)> null_cb;
1840 ASSERT_TRUE(null_cb.is_null());
1841 EXPECT_CHECK_DEATH(base::BindRepeating(null_cb, 42));
1844 TEST(BindDeathTest, NullFunctionPointer) {
1845 void (*null_function)(int) = nullptr;
1846 EXPECT_DCHECK_DEATH(base::BindRepeating(null_function, 42));
1849 TEST(BindDeathTest, NullCallbackWithoutBoundArgs) {
1850 base::OnceCallback<void(int)> null_cb;
1851 ASSERT_TRUE(null_cb.is_null());
1852 EXPECT_CHECK_DEATH(base::BindOnce(std::move(null_cb)));
1855 TEST(BindDeathTest, BanFirstOwnerOfRefCountedType) {
1856 StrictMock<HasRef> has_ref;
1857 EXPECT_DCHECK_DEATH({
1858 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillOnce(Return(false));
1859 base::BindOnce(&HasRef::VoidMethod0, &has_ref);
1862 EXPECT_DCHECK_DEATH({
1863 raw_ptr<HasRef> rawptr(&has_ref);
1864 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillOnce(Return(false));
1865 base::BindOnce(&HasRef::VoidMethod0, rawptr);
1869 #if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
1871 void HandleOOM(size_t unused_size) {
1872 LOG(FATAL) << "Out of memory";
1875 // Basic set of options to mostly only enable `BackupRefPtr::kEnabled`.
1876 // This avoids the boilerplate of having too much options enabled for simple
1878 static constexpr partition_alloc::PartitionOptions
1879 kOnlyEnableBackupRefPtrOptions = {
1880 .backup_ref_ptr = partition_alloc::PartitionOptions::kEnabled,
1883 class BindUnretainedDanglingInternalFixture : public BindTest {
1885 void SetUp() override {
1886 partition_alloc::PartitionAllocGlobalInit(HandleOOM);
1887 enabled_feature_list_.InitWithFeaturesAndParameters(
1888 {{features::kPartitionAllocUnretainedDanglingPtr, {{"mode", "crash"}}}},
1889 {/* disabled_features */});
1890 allocator::InstallUnretainedDanglingRawPtrChecks();
1893 void TearDown() override {
1894 enabled_feature_list_.Reset();
1895 allocator::InstallUnretainedDanglingRawPtrChecks();
1898 // In unit tests, allocations being tested need to live in a separate PA
1899 // root so the test code doesn't interfere with various counters. Following
1900 // methods are helpers for managing allocations inside the separate allocator
1902 template <typename T,
1903 RawPtrTraits Traits = RawPtrTraits::kEmpty,
1905 raw_ptr<T, Traits> Alloc(Args&&... args) {
1906 void* ptr = allocator_.root()->Alloc(sizeof(T), "");
1907 T* p = new (reinterpret_cast<T*>(ptr)) T(std::forward<Args>(args)...);
1908 return raw_ptr<T, Traits>(p);
1910 template <typename T, RawPtrTraits Traits>
1911 void Free(raw_ptr<T, Traits>& ptr) {
1912 allocator_.root()->Free(ptr.ExtractAsDangling());
1916 test::ScopedFeatureList enabled_feature_list_;
1917 partition_alloc::PartitionAllocatorForTesting allocator_{
1918 kOnlyEnableBackupRefPtrOptions};
1921 class BindUnretainedDanglingTest
1922 : public BindUnretainedDanglingInternalFixture {};
1923 class BindUnretainedDanglingDeathTest
1924 : public BindUnretainedDanglingInternalFixture {};
1926 bool PtrCheckFn(int* p) {
1927 return p != nullptr;
1930 bool RefCheckFn(const int& p) {
1934 bool MayBeDanglingCheckFn(MayBeDangling<int> p) {
1935 return p != nullptr;
1938 bool MayBeDanglingAndDummyTraitCheckFn(
1939 MayBeDangling<int, RawPtrTraits::kDummyForTest> p) {
1940 return p != nullptr;
1943 class ClassWithWeakPtr {
1945 ClassWithWeakPtr() = default;
1946 void RawPtrArg(int* p) { *p = 123; }
1947 void RawRefArg(int& p) { p = 123; }
1948 WeakPtr<ClassWithWeakPtr> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
1951 WeakPtrFactory<ClassWithWeakPtr> weak_factory_{this};
1954 TEST_F(BindUnretainedDanglingTest, UnretainedNoDanglingPtr) {
1955 raw_ptr<int> p = Alloc<int>(3);
1956 auto callback = base::BindOnce(PingPong, base::Unretained(p));
1957 EXPECT_EQ(std::move(callback).Run(), 3);
1961 TEST_F(BindUnretainedDanglingTest, UnsafeDanglingPtr) {
1962 raw_ptr<int> p = Alloc<int>(3);
1963 auto callback = base::BindOnce(MayBeDanglingCheckFn, base::UnsafeDangling(p));
1965 EXPECT_EQ(std::move(callback).Run(), true);
1968 TEST_F(BindUnretainedDanglingTest, UnsafeDanglingPtrWithDummyTrait) {
1969 raw_ptr<int, RawPtrTraits::kDummyForTest> p =
1970 Alloc<int, RawPtrTraits::kDummyForTest>(3);
1971 auto callback = base::BindOnce(MayBeDanglingAndDummyTraitCheckFn,
1972 base::UnsafeDangling(p));
1974 EXPECT_EQ(std::move(callback).Run(), true);
1977 TEST_F(BindUnretainedDanglingTest,
1978 UnsafeDanglingPtrWithDummyAndDanglingTraits) {
1979 raw_ptr<int, RawPtrTraits::kDummyForTest | RawPtrTraits::kMayDangle> p =
1980 Alloc<int, RawPtrTraits::kDummyForTest | RawPtrTraits::kMayDangle>(3);
1981 auto callback = base::BindOnce(MayBeDanglingAndDummyTraitCheckFn,
1982 base::UnsafeDangling(p));
1984 EXPECT_EQ(std::move(callback).Run(), true);
1987 TEST_F(BindUnretainedDanglingTest, UnsafeDanglingPtrNoRawPtrReceiver) {
1988 std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
1991 base::BindOnce(&ClassWithWeakPtr::RawPtrArg,
1992 base::UnsafeDangling(r.get()), base::Unretained(&val));
1993 std::move(callback).Run();
1994 EXPECT_EQ(val, 123);
1997 TEST_F(BindUnretainedDanglingTest, UnsafeDanglingUntriagedPtr) {
1998 raw_ptr<int> p = Alloc<int>(3);
1999 auto callback = base::BindOnce(PtrCheckFn, base::UnsafeDanglingUntriaged(p));
2001 EXPECT_EQ(std::move(callback).Run(), true);
2004 TEST_F(BindUnretainedDanglingTest, UnretainedWeakReceiverValidNoDangling) {
2005 raw_ptr<int> p = Alloc<int>(3);
2006 std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
2007 auto callback = base::BindOnce(&ClassWithWeakPtr::RawPtrArg, r->GetWeakPtr(),
2008 base::Unretained(p));
2009 std::move(callback).Run();
2014 TEST_F(BindUnretainedDanglingTest, UnretainedRefWeakReceiverValidNoDangling) {
2015 raw_ptr<int> p = Alloc<int>(3);
2017 std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
2018 auto callback = base::BindOnce(&ClassWithWeakPtr::RawRefArg, r->GetWeakPtr(),
2020 std::move(callback).Run();
2025 TEST_F(BindUnretainedDanglingTest, UnretainedWeakReceiverInvalidNoDangling) {
2026 raw_ptr<int> p = Alloc<int>(3);
2027 std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
2028 auto callback = base::BindOnce(&ClassWithWeakPtr::RawPtrArg, r->GetWeakPtr(),
2029 base::Unretained(p));
2032 std::move(callback).Run();
2033 // Should reach this point without crashing; there is a dangling pointer, but
2034 // the callback is cancelled because the WeakPtr is already invalidated.
2037 TEST_F(BindUnretainedDanglingTest, UnretainedRefWeakReceiverInvalidNoDangling) {
2038 raw_ptr<int> p = Alloc<int>(3);
2040 std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
2041 auto callback = base::BindOnce(&ClassWithWeakPtr::RawRefArg, r->GetWeakPtr(),
2045 std::move(callback).Run();
2046 // Should reach this point without crashing; there is a dangling pointer, but
2047 // the callback is cancelled because the WeakPtr is already invalidated.
2050 TEST_F(BindUnretainedDanglingTest, UnretainedRefUnsafeDangling) {
2051 raw_ptr<int> p = Alloc<int>(3);
2054 base::BindOnce(RefCheckFn, base::UnsafeDangling(base::raw_ref<int>(ref)));
2056 EXPECT_EQ(std::move(callback).Run(), true);
2057 // Should reach this point without crashing; there is a dangling pointer, but
2058 // the we marked the reference as `UnsafeDangling`.
2061 TEST_F(BindUnretainedDanglingTest, UnretainedRefUnsafeDanglingUntriaged) {
2062 raw_ptr<int> p = Alloc<int>(3);
2064 auto callback = base::BindOnce(
2065 RefCheckFn, base::UnsafeDanglingUntriaged(base::raw_ref<const int>(ref)));
2067 EXPECT_EQ(std::move(callback).Run(), true);
2068 // Should reach this point without crashing; there is a dangling pointer, but
2069 // the we marked the reference as `UnsafeDanglingUntriaged`.
2072 // Death tests misbehave on Android, http://crbug.com/643760.
2073 #if defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID)
2075 int FuncWithRefArgument(int& i_ptr) {
2079 TEST_F(BindUnretainedDanglingDeathTest, UnretainedDanglingPtr) {
2080 raw_ptr<int> p = Alloc<int>(3);
2081 auto callback = base::BindOnce(PingPong, base::Unretained(p));
2083 EXPECT_DEATH(std::move(callback).Run(), "");
2086 TEST_F(BindUnretainedDanglingDeathTest, UnretainedRefDanglingPtr) {
2087 raw_ptr<int> p = Alloc<int>(3);
2089 auto callback = base::BindOnce(FuncWithRefArgument, std::ref(ref));
2091 EXPECT_DEATH(std::move(callback).Run(), "");
2094 TEST_F(BindUnretainedDanglingDeathTest,
2095 UnretainedRefWithManualUnretainedDanglingPtr) {
2096 raw_ptr<int> p = Alloc<int>(3);
2098 auto callback = base::BindOnce(FuncWithRefArgument,
2099 base::Unretained(base::raw_ref<int>(ref)));
2101 EXPECT_DEATH(std::move(callback).Run(), "");
2104 TEST_F(BindUnretainedDanglingDeathTest, UnretainedWeakReceiverDangling) {
2105 raw_ptr<int> p = Alloc<int>(3);
2106 std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
2107 auto callback = base::BindOnce(&ClassWithWeakPtr::RawPtrArg, r->GetWeakPtr(),
2108 base::Unretained(p));
2110 EXPECT_DEATH(std::move(callback).Run(), "");
2113 #endif // defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID)
2115 #endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)