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