1 // Copyright 2011 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.
4 
5 #ifndef BASE_FUNCTIONAL_BIND_H_
6 #define BASE_FUNCTIONAL_BIND_H_
7 
8 #include <functional>
9 #include <memory>
10 #include <type_traits>
11 #include <utility>
12 
13 #include "base/compiler_specific.h"
14 #include "base/functional/bind_internal.h"
15 #include "base/memory/raw_ptr.h"
16 #include "build/build_config.h"
17 
18 #if BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc)
19 #include "base/mac/scoped_block.h"
20 #endif
21 
22 // -----------------------------------------------------------------------------
23 // Usage documentation
24 // -----------------------------------------------------------------------------
25 //
26 // Overview:
27 // base::BindOnce() and base::BindRepeating() are helpers for creating
28 // base::OnceCallback and base::RepeatingCallback objects respectively.
29 //
30 // For a runnable object of n-arity, the base::Bind*() family allows partial
31 // application of the first m arguments. The remaining n - m arguments must be
32 // passed when invoking the callback with Run().
33 //
34 //   // The first argument is bound at callback creation; the remaining
35 //   // two must be passed when calling Run() on the callback object.
36 //   base::OnceCallback<long(int, long)> cb = base::BindOnce(
37 //       [](short x, int y, long z) { return x * y * z; }, 42);
38 //
39 // When binding to a method, the receiver object must also be specified at
40 // callback creation time. When Run() is invoked, the method will be invoked on
41 // the specified receiver object.
42 //
43 //   class C : public base::RefCounted<C> { void F(); };
44 //   auto instance = base::MakeRefCounted<C>();
45 //   auto cb = base::BindOnce(&C::F, instance);
46 //   std::move(cb).Run();  // Identical to instance->F()
47 //
48 // See //docs/callback.md for the full documentation.
49 //
50 // -----------------------------------------------------------------------------
51 // Implementation notes
52 // -----------------------------------------------------------------------------
53 //
54 // If you're reading the implementation, before proceeding further, you should
55 // read the top comment of base/functional/bind_internal.h for a definition of
56 // common terms and concepts.
57 
58 namespace base {
59 
60 // Bind as OnceCallback.
61 template <typename Functor, typename... Args>
BindOnce(Functor && functor,Args &&...args)62 inline OnceCallback<internal::MakeUnboundRunType<Functor, Args...>> BindOnce(
63     Functor&& functor,
64     Args&&... args) {
65   static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() ||
66                     (std::is_rvalue_reference<Functor&&>() &&
67                      !std::is_const<std::remove_reference_t<Functor>>()),
68                 "BindOnce requires non-const rvalue for OnceCallback binding."
69                 " I.e.: base::BindOnce(std::move(callback)).");
70   static_assert(
71       std::conjunction<
72           internal::AssertBindArgIsNotBasePassed<std::decay_t<Args>>...>::value,
73       "Use std::move() instead of base::Passed() with base::BindOnce()");
74 
75   return internal::BindImpl<OnceCallback>(std::forward<Functor>(functor),
76                                           std::forward<Args>(args)...);
77 }
78 
79 // Bind as RepeatingCallback.
80 template <typename Functor, typename... Args>
81 inline RepeatingCallback<internal::MakeUnboundRunType<Functor, Args...>>
BindRepeating(Functor && functor,Args &&...args)82 BindRepeating(Functor&& functor, Args&&... args) {
83   static_assert(
84       !internal::IsOnceCallback<std::decay_t<Functor>>(),
85       "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move().");
86 
87   return internal::BindImpl<RepeatingCallback>(std::forward<Functor>(functor),
88                                                std::forward<Args>(args)...);
89 }
90 
91 // Overloads to allow nicer compile errors when attempting to pass the address
92 // an overloaded function to `BindOnce()` or `BindRepeating()`. Otherwise, clang
93 // provides only the error message "no matching function [...] candidate
94 // template ignored: couldn't infer template argument 'Functor'", with no
95 // reference to the fact that `&` is being used on an overloaded function.
96 //
97 // These overloads to provide better error messages will never be selected
98 // unless template type deduction fails because of how overload resolution
99 // works; per [over.ics.rank/2.2]:
100 //
101 //   When comparing the basic forms of implicit conversion sequences (as defined
102 //   in [over.best.ics])
103 //   - a standard conversion sequence is a better conversion sequence than a
104 //     user-defined conversion sequence or an ellipsis conversion sequence, and
105 //   - a user-defined conversion sequence is a better conversion sequence than
106 //     an ellipsis conversion sequence.
107 //
108 // So these overloads will only be selected as a last resort iff template type
109 // deduction fails.
110 //
111 // These overloads also intentionally do not return `void`, as this prevents
112 // clang from emitting spurious errors such as "variable has incomplete type
113 // 'void'" when assigning the result of `BindOnce()`/`BindRepeating()` to a
114 // variable with type `auto` or `decltype(auto)`.
115 struct BindFailedCheckPreviousErrors {};
116 BindFailedCheckPreviousErrors BindOnce(...);
117 BindFailedCheckPreviousErrors BindRepeating(...);
118 
119 // Unretained(), UnsafeDangling() and UnsafeDanglingUntriaged() allow binding a
120 // non-refcounted class, and to disable refcounting on arguments that are
121 // refcounted. The main difference is whether or not the raw pointers will be
122 // checked for dangling references (e.g. a pointer that points to an already
123 // destroyed object) when the callback is run.
124 //
125 // It is _required_ to use one of Unretained(), UnsafeDangling() or
126 // UnsafeDanglingUntriaged() for raw pointer receivers now. For other arguments,
127 // it remains optional. If not specified, default behavior is Unretained().
128 
129 // Unretained() pointers will be checked for dangling pointers when the
130 // callback is run, *if* the callback has not been cancelled.
131 //
132 // Example of Unretained() usage:
133 //
134 //   class Foo {
135 //    public:
136 //     void func() { cout << "Foo:f" << endl; }
137 //   };
138 //
139 //   // In some function somewhere.
140 //   Foo foo;
141 //   OnceClosure foo_callback =
142 //       BindOnce(&Foo::func, Unretained(&foo));
143 //   std::move(foo_callback).Run();  // Prints "Foo:f".
144 //
145 // Without the Unretained() wrapper on |&foo|, the above call would fail
146 // to compile because Foo does not support the AddRef() and Release() methods.
147 //
148 // Unretained() does not allow dangling pointers, e.g.:
149 //   class MyClass {
150 //    public:
151 //     OnError(int error);
152 //    private:
153 //     scoped_refptr<base::TaskRunner> runner_;
154 //     std::unique_ptr<AnotherClass> obj_;
155 //   };
156 //
157 //   void MyClass::OnError(int error) {
158 //     // the pointer (which is also the receiver here) to `AnotherClass`
159 //     // might dangle depending on when the task is invoked.
160 //     runner_->PostTask(FROM_HERE, base::BindOnce(&AnotherClass::OnError,
161 //         base::Unretained(obj_.get()), error));
162 //     // one of the way to solve this issue here would be:
163 //     // runner_->PostTask(FROM_HERE,
164 //     //                   base::BindOnce(&AnotherClass::OnError,
165 //     //                   base::Owned(std::move(obj_)), error));
166 //     delete this;
167 //   }
168 //
169 // the above example is a BAD USAGE of Unretained(), which might result in a
170 // use-after-free, as `AnotherClass::OnError` might be invoked with a dangling
171 // pointer as receiver.
172 template <typename T>
Unretained(T * o)173 inline auto Unretained(T* o) {
174   return internal::UnretainedWrapper<T, unretained_traits::MayNotDangle>(o);
175 }
176 
177 template <typename T, RawPtrTraits Traits>
Unretained(const raw_ptr<T,Traits> & o)178 inline auto Unretained(const raw_ptr<T, Traits>& o) {
179   return internal::UnretainedWrapper<T, unretained_traits::MayNotDangle,
180                                      Traits>(o);
181 }
182 
183 template <typename T, RawPtrTraits Traits>
Unretained(raw_ptr<T,Traits> && o)184 inline auto Unretained(raw_ptr<T, Traits>&& o) {
185   return internal::UnretainedWrapper<T, unretained_traits::MayNotDangle,
186                                      Traits>(std::move(o));
187 }
188 
189 template <typename T, RawPtrTraits Traits>
Unretained(const raw_ref<T,Traits> & o)190 inline auto Unretained(const raw_ref<T, Traits>& o) {
191   return internal::UnretainedRefWrapper<T, unretained_traits::MayNotDangle,
192                                         Traits>(o);
193 }
194 
195 template <typename T, RawPtrTraits Traits>
Unretained(raw_ref<T,Traits> && o)196 inline auto Unretained(raw_ref<T, Traits>&& o) {
197   return internal::UnretainedRefWrapper<T, unretained_traits::MayNotDangle,
198                                         Traits>(std::move(o));
199 }
200 
201 // Similar to `Unretained()`, but allows dangling pointers, e.g.:
202 //
203 //   class MyClass {
204 //     public:
205 //       DoSomething(HandlerClass* handler);
206 //     private:
207 //       void MyClass::DoSomethingInternal(HandlerClass::Id id,
208 //                                         HandlerClass* handler);
209 //
210 //       std::unordered_map<HandlerClass::Id, HandlerClass*> handlers_;
211 //       scoped_refptr<base::SequencedTaskRunner> runner_;
212 //       base::Lock lock_;
213 //   };
214 //   void MyClass::DoSomething(HandlerClass* handler) {
215 //      runner_->PostTask(FROM_HERE,
216 //          base::BindOnce(&MyClass::DoSomethingInternal,
217 //                         base::Unretained(this),
218 //                         handler->id(),
219 //                         base::Unretained(handler)));
220 //   }
221 //   void MyClass::DoSomethingInternal(HandlerClass::Id id,
222 //                                     HandlerClass* handler) {
223 //     base::AutoLock locker(lock_);
224 //     if (handlers_.find(id) == std::end(handlers_)) return;
225 //     // Now we can use `handler`.
226 //   }
227 //
228 // As `DoSomethingInternal` is run on a sequence (and we can imagine
229 // `handlers_` being modified on it as well), we protect the function from
230 // using a dangling `handler` by making sure it is still contained in the
231 // map.
232 //
233 // Strongly prefer `Unretained()`. This is useful in limited situations such as
234 // the one above.
235 //
236 // When using `UnsafeDangling()`, the receiver must be of type MayBeDangling<>.
237 template <typename T>
UnsafeDangling(T * o)238 inline auto UnsafeDangling(T* o) {
239   return internal::UnretainedWrapper<T, unretained_traits::MayDangle>(o);
240 }
241 
242 template <typename T, RawPtrTraits Traits>
UnsafeDangling(const raw_ptr<T,Traits> & o)243 auto UnsafeDangling(const raw_ptr<T, Traits>& o) {
244   return internal::UnretainedWrapper<T, unretained_traits::MayDangle, Traits>(
245       o);
246 }
247 
248 template <typename T, RawPtrTraits Traits>
UnsafeDangling(raw_ptr<T,Traits> && o)249 auto UnsafeDangling(raw_ptr<T, Traits>&& o) {
250   return internal::UnretainedWrapper<T, unretained_traits::MayDangle, Traits>(
251       std::move(o));
252 }
253 
254 template <typename T, RawPtrTraits Traits>
UnsafeDangling(const raw_ref<T,Traits> & o)255 auto UnsafeDangling(const raw_ref<T, Traits>& o) {
256   return internal::UnretainedRefWrapper<T, unretained_traits::MayDangle,
257                                         Traits>(o);
258 }
259 
260 template <typename T, RawPtrTraits Traits>
UnsafeDangling(raw_ref<T,Traits> && o)261 auto UnsafeDangling(raw_ref<T, Traits>&& o) {
262   return internal::UnretainedRefWrapper<T, unretained_traits::MayDangle,
263                                         Traits>(std::move(o));
264 }
265 
266 // Like `UnsafeDangling()`, but used to annotate places that still need to be
267 // triaged and either migrated to `Unretained()` and safer ownership patterns
268 // (preferred) or `UnsafeDangling()` if the correct pattern to use is the one
269 // in the `UnsafeDangling()` example above for example.
270 //
271 // Unlike `UnsafeDangling()`, the receiver doesn't have to be MayBeDangling<>.
272 template <typename T>
UnsafeDanglingUntriaged(T * o)273 inline auto UnsafeDanglingUntriaged(T* o) {
274   return internal::UnretainedWrapper<T, unretained_traits::MayDangleUntriaged>(
275       o);
276 }
277 
278 template <typename T, RawPtrTraits Traits>
UnsafeDanglingUntriaged(const raw_ptr<T,Traits> & o)279 auto UnsafeDanglingUntriaged(const raw_ptr<T, Traits>& o) {
280   return internal::UnretainedWrapper<T, unretained_traits::MayDangleUntriaged,
281                                      Traits>(o);
282 }
283 
284 template <typename T, RawPtrTraits Traits>
UnsafeDanglingUntriaged(raw_ptr<T,Traits> && o)285 auto UnsafeDanglingUntriaged(raw_ptr<T, Traits>&& o) {
286   return internal::UnretainedWrapper<T, unretained_traits::MayDangleUntriaged,
287                                      Traits>(std::move(o));
288 }
289 
290 template <typename T, RawPtrTraits Traits>
UnsafeDanglingUntriaged(const raw_ref<T,Traits> & o)291 auto UnsafeDanglingUntriaged(const raw_ref<T, Traits>& o) {
292   return internal::UnretainedRefWrapper<
293       T, unretained_traits::MayDangleUntriaged, Traits>(o);
294 }
295 
296 template <typename T, RawPtrTraits Traits>
UnsafeDanglingUntriaged(raw_ref<T,Traits> && o)297 auto UnsafeDanglingUntriaged(raw_ref<T, Traits>&& o) {
298   return internal::UnretainedRefWrapper<
299       T, unretained_traits::MayDangleUntriaged, Traits>(std::move(o));
300 }
301 
302 // RetainedRef() accepts a ref counted object and retains a reference to it.
303 // When the callback is called, the object is passed as a raw pointer.
304 //
305 // EXAMPLE OF RetainedRef():
306 //
307 //    void foo(RefCountedBytes* bytes) {}
308 //
309 //    scoped_refptr<RefCountedBytes> bytes = ...;
310 //    OnceClosure callback = BindOnce(&foo, base::RetainedRef(bytes));
311 //    std::move(callback).Run();
312 //
313 // Without RetainedRef, the scoped_refptr would try to implicitly convert to
314 // a raw pointer and fail compilation:
315 //
316 //    OnceClosure callback = BindOnce(&foo, bytes); // ERROR!
317 template <typename T>
RetainedRef(T * o)318 inline internal::RetainedRefWrapper<T> RetainedRef(T* o) {
319   return internal::RetainedRefWrapper<T>(o);
320 }
321 template <typename T>
RetainedRef(scoped_refptr<T> o)322 inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) {
323   return internal::RetainedRefWrapper<T>(std::move(o));
324 }
325 
326 // Owned() transfers ownership of an object to the callback resulting from
327 // bind; the object will be deleted when the callback is deleted.
328 //
329 // EXAMPLE OF Owned():
330 //
331 //   void foo(int* arg) { cout << *arg << endl }
332 //
333 //   int* pn = new int(1);
334 //   RepeatingClosure foo_callback = BindRepeating(&foo, Owned(pn));
335 //
336 //   foo_callback.Run();  // Prints "1"
337 //   foo_callback.Run();  // Prints "1"
338 //   *pn = 2;
339 //   foo_callback.Run();  // Prints "2"
340 //
341 //   foo_callback.Reset();  // |pn| is deleted.  Also will happen when
342 //                          // |foo_callback| goes out of scope.
343 //
344 // Without Owned(), someone would have to know to delete |pn| when the last
345 // reference to the callback is deleted.
346 template <typename T>
Owned(T * o)347 inline internal::OwnedWrapper<T> Owned(T* o) {
348   return internal::OwnedWrapper<T>(o);
349 }
350 
351 template <typename T, typename Deleter>
Owned(std::unique_ptr<T,Deleter> && ptr)352 inline internal::OwnedWrapper<T, Deleter> Owned(
353     std::unique_ptr<T, Deleter>&& ptr) {
354   return internal::OwnedWrapper<T, Deleter>(std::move(ptr));
355 }
356 
357 // OwnedRef() stores an object in the callback resulting from
358 // bind and passes a reference to the object to the bound function.
359 //
360 // EXAMPLE OF OwnedRef():
361 //
362 //   void foo(int& arg) { cout << ++arg << endl }
363 //
364 //   int counter = 0;
365 //   RepeatingClosure foo_callback = BindRepeating(&foo, OwnedRef(counter));
366 //
367 //   foo_callback.Run();  // Prints "1"
368 //   foo_callback.Run();  // Prints "2"
369 //   foo_callback.Run();  // Prints "3"
370 //
371 //   cout << counter;     // Prints "0", OwnedRef creates a copy of counter.
372 //
373 //  Supports OnceCallbacks as well, useful to pass placeholder arguments:
374 //
375 //   void bar(int& ignore, const std::string& s) { cout << s << endl }
376 //
377 //   OnceClosure bar_callback = BindOnce(&bar, OwnedRef(0), "Hello");
378 //
379 //   std::move(bar_callback).Run(); // Prints "Hello"
380 //
381 // Without OwnedRef() it would not be possible to pass a mutable reference to an
382 // object owned by the callback.
383 template <typename T>
OwnedRef(T && t)384 internal::OwnedRefWrapper<std::decay_t<T>> OwnedRef(T&& t) {
385   return internal::OwnedRefWrapper<std::decay_t<T>>(std::forward<T>(t));
386 }
387 
388 // Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr)
389 // through a RepeatingCallback. Logically, this signifies a destructive transfer
390 // of the state of the argument into the target function. Invoking
391 // RepeatingCallback::Run() twice on a callback that was created with a Passed()
392 // argument will CHECK() because the first invocation would have already
393 // transferred ownership to the target function.
394 //
395 // Note that Passed() is not necessary with BindOnce(), as std::move() does the
396 // same thing. Avoid Passed() in favor of std::move() with BindOnce().
397 //
398 // EXAMPLE OF Passed():
399 //
400 //   void TakesOwnership(std::unique_ptr<Foo> arg) { }
401 //   std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>();
402 //   }
403 //
404 //   auto f = std::make_unique<Foo>();
405 //
406 //   // |cb| is given ownership of Foo(). |f| is now NULL.
407 //   // You can use std::move(f) in place of &f, but it's more verbose.
408 //   RepeatingClosure cb = BindRepeating(&TakesOwnership, Passed(&f));
409 //
410 //   // Run was never called so |cb| still owns Foo() and deletes
411 //   // it on Reset().
412 //   cb.Reset();
413 //
414 //   // |cb| is given a new Foo created by CreateFoo().
415 //   cb = BindRepeating(&TakesOwnership, Passed(CreateFoo()));
416 //
417 //   // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
418 //   // no longer owns Foo() and, if reset, would not delete Foo().
419 //   cb.Run();  // Foo() is now transferred to |arg| and deleted.
420 //   cb.Run();  // This CHECK()s since Foo() already been used once.
421 //
422 // We offer 2 syntaxes for calling Passed(). The first takes an rvalue and is
423 // best suited for use with the return value of a function or other temporary
424 // rvalues. The second takes a pointer to the scoper and is just syntactic sugar
425 // to avoid having to write Passed(std::move(scoper)).
426 //
427 // Both versions of Passed() prevent T from being an lvalue reference. The first
428 // via use of enable_if, and the second takes a T* which will not bind to T&.
429 template <typename T,
430           std::enable_if_t<!std::is_lvalue_reference_v<T>>* = nullptr>
Passed(T && scoper)431 inline internal::PassedWrapper<T> Passed(T&& scoper) {
432   return internal::PassedWrapper<T>(std::move(scoper));
433 }
434 template <typename T>
Passed(T * scoper)435 inline internal::PassedWrapper<T> Passed(T* scoper) {
436   return internal::PassedWrapper<T>(std::move(*scoper));
437 }
438 
439 // IgnoreResult() is used to adapt a function or callback with a return type to
440 // one with a void return. This is most useful if you have a function with,
441 // say, a pesky ignorable bool return that you want to use with PostTask or
442 // something else that expect a callback with a void return.
443 //
444 // EXAMPLE OF IgnoreResult():
445 //
446 //   int DoSomething(int arg) { cout << arg << endl; }
447 //
448 //   // Assign to a callback with a void return type.
449 //   OnceCallback<void(int)> cb = BindOnce(IgnoreResult(&DoSomething));
450 //   std::move(cb).Run(1);  // Prints "1".
451 //
452 //   // Prints "2" on |ml|.
453 //   ml->PostTask(FROM_HERE, BindOnce(IgnoreResult(&DoSomething), 2);
454 template <typename T>
IgnoreResult(T data)455 inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
456   return internal::IgnoreResultHelper<T>(std::move(data));
457 }
458 
459 #if BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc)
460 
461 // RetainBlock() is used to adapt an Objective-C block when Automated Reference
462 // Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the
463 // BindOnce and BindRepeating already support blocks then.
464 //
465 // EXAMPLE OF RetainBlock():
466 //
467 //   // Wrap the block and bind it to a callback.
468 //   OnceCallback<void(int)> cb =
469 //       BindOnce(RetainBlock(^(int n) { NSLog(@"%d", n); }));
470 //   std::move(cb).Run(1);  // Logs "1".
471 template <typename R, typename... Args>
472 base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) {
473   return base::mac::ScopedBlock<R (^)(Args...)>(block,
474                                                 base::scoped_policy::RETAIN);
475 }
476 
477 #endif  // BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc)
478 
479 }  // namespace base
480 
481 #endif  // BASE_FUNCTIONAL_BIND_H_
482