xref: /aosp_15_r20/external/cronet/base/synchronization/waitable_event_watcher_posix.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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.
4 
5 #include "base/synchronization/waitable_event_watcher.h"
6 
7 #include <utility>
8 
9 #include "base/check.h"
10 #include "base/functional/bind.h"
11 #include "base/synchronization/lock.h"
12 #include "base/synchronization/waitable_event.h"
13 
14 namespace base {
15 
16 // -----------------------------------------------------------------------------
17 // WaitableEventWatcher (async waits).
18 //
19 // The basic design is that we add an AsyncWaiter to the wait-list of the event.
20 // That AsyncWaiter has a pointer to SequencedTaskRunner, and a Task to be
21 // posted to it. The task ends up calling the callback when it runs on the
22 // sequence.
23 //
24 // Since the wait can be canceled, we have a thread-safe Flag object which is
25 // set when the wait has been canceled. At each stage in the above, we check the
26 // flag before going onto the next stage. Since the wait may only be canceled in
27 // the sequence which runs the Task, we are assured that the callback cannot be
28 // called after canceling...
29 
30 // -----------------------------------------------------------------------------
31 // A thread-safe, reference-counted, write-once flag.
32 // -----------------------------------------------------------------------------
33 class Flag : public RefCountedThreadSafe<Flag> {
34  public:
Flag()35   Flag() { flag_ = false; }
36 
37   Flag(const Flag&) = delete;
38   Flag& operator=(const Flag&) = delete;
39 
Set()40   void Set() {
41     AutoLock locked(lock_);
42     flag_ = true;
43   }
44 
value() const45   bool value() const {
46     AutoLock locked(lock_);
47     return flag_;
48   }
49 
50  private:
51   friend class RefCountedThreadSafe<Flag>;
52   ~Flag() = default;
53 
54   mutable Lock lock_;
55   bool flag_;
56 };
57 
58 // -----------------------------------------------------------------------------
59 // This is an asynchronous waiter which posts a task to a SequencedTaskRunner
60 // when fired. An AsyncWaiter may only be in a single wait-list.
61 // -----------------------------------------------------------------------------
62 class AsyncWaiter : public WaitableEvent::Waiter {
63  public:
AsyncWaiter(scoped_refptr<SequencedTaskRunner> task_runner,base::OnceClosure callback,Flag * flag)64   AsyncWaiter(scoped_refptr<SequencedTaskRunner> task_runner,
65               base::OnceClosure callback,
66               Flag* flag)
67       : task_runner_(std::move(task_runner)),
68         callback_(std::move(callback)),
69         flag_(flag) {}
70 
Fire(WaitableEvent * event)71   bool Fire(WaitableEvent* event) override {
72     // Post the callback if we haven't been cancelled.
73     if (!flag_->value())
74       task_runner_->PostTask(FROM_HERE, std::move(callback_));
75 
76     // We are removed from the wait-list by the WaitableEvent itself. It only
77     // remains to delete ourselves.
78     delete this;
79 
80     // We can always return true because an AsyncWaiter is never in two
81     // different wait-lists at the same time.
82     return true;
83   }
84 
85   // See StopWatching for discussion
Compare(void * tag)86   bool Compare(void* tag) override { return tag == flag_.get(); }
87 
88  private:
89   const scoped_refptr<SequencedTaskRunner> task_runner_;
90   base::OnceClosure callback_;
91   const scoped_refptr<Flag> flag_;
92 };
93 
94 // -----------------------------------------------------------------------------
95 // For async waits we need to run a callback on a sequence. We do this by
96 // posting an AsyncCallbackHelper task, which calls the callback and keeps track
97 // of when the event is canceled.
98 // -----------------------------------------------------------------------------
AsyncCallbackHelper(Flag * flag,WaitableEventWatcher::EventCallback callback,WaitableEvent * event)99 void AsyncCallbackHelper(Flag* flag,
100                          WaitableEventWatcher::EventCallback callback,
101                          WaitableEvent* event) {
102   // Runs on the sequence that called StartWatching().
103   if (!flag->value()) {
104     // This is to let the WaitableEventWatcher know that the event has occured.
105     flag->Set();
106     std::move(callback).Run(event);
107   }
108 }
109 
WaitableEventWatcher()110 WaitableEventWatcher::WaitableEventWatcher() {
111   DETACH_FROM_SEQUENCE(sequence_checker_);
112 }
113 
~WaitableEventWatcher()114 WaitableEventWatcher::~WaitableEventWatcher() {
115   // The destructor may be called from a different sequence than StartWatching()
116   // when there is no active watch. To avoid triggering a DCHECK in
117   // StopWatching(), do not call it when there is no active watch.
118   if (cancel_flag_ && !cancel_flag_->value())
119     StopWatching();
120 }
121 
122 // -----------------------------------------------------------------------------
123 // The Handle is how the user cancels a wait. After deleting the Handle we
124 // insure that the delegate cannot be called.
125 // -----------------------------------------------------------------------------
StartWatching(WaitableEvent * event,EventCallback callback,scoped_refptr<SequencedTaskRunner> task_runner)126 bool WaitableEventWatcher::StartWatching(
127     WaitableEvent* event,
128     EventCallback callback,
129     scoped_refptr<SequencedTaskRunner> task_runner) {
130   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
131 
132   // A user may call StartWatching from within the callback function. In this
133   // case, we won't know that we have finished watching, expect that the Flag
134   // will have been set in AsyncCallbackHelper().
135   if (cancel_flag_.get() && cancel_flag_->value())
136     cancel_flag_ = nullptr;
137 
138   DCHECK(!cancel_flag_) << "StartWatching called while still watching";
139 
140   cancel_flag_ = new Flag;
141   // UnsafeDanglingUntriaged triggered by test:
142   // WaitableEventWatcherDeletionTest.SignalAndDelete
143   // TODO(https://crbug.com/1380714): Remove `UnsafeDanglingUntriaged`
144   OnceClosure internal_callback =
145       base::BindOnce(&AsyncCallbackHelper, base::RetainedRef(cancel_flag_),
146                      std::move(callback), base::UnsafeDanglingUntriaged(event));
147   WaitableEvent::WaitableEventKernel* kernel = event->kernel_.get();
148 
149   AutoLock locked(kernel->lock_);
150 
151   if (kernel->signaled_) {
152     if (!kernel->manual_reset_)
153       kernel->signaled_ = false;
154 
155     // No hairpinning - we can't call the delegate directly here. We have to
156     // post a task to |task_runner| as usual.
157     task_runner->PostTask(FROM_HERE, std::move(internal_callback));
158     return true;
159   }
160 
161   kernel_ = kernel;
162   waiter_ = new AsyncWaiter(std::move(task_runner),
163                             std::move(internal_callback), cancel_flag_.get());
164   event->Enqueue(waiter_);
165 
166   return true;
167 }
168 
StopWatching()169 void WaitableEventWatcher::StopWatching() {
170   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
171 
172   if (!cancel_flag_.get())  // if not currently watching...
173     return;
174 
175   if (cancel_flag_->value()) {
176     // In this case, the event has fired, but we haven't figured that out yet.
177     // The WaitableEvent may have been deleted too.
178     cancel_flag_ = nullptr;
179     return;
180   }
181 
182   if (!kernel_.get()) {
183     // We have no kernel. This means that we never enqueued a Waiter on an
184     // event because the event was already signaled when StartWatching was
185     // called.
186     //
187     // In this case, a task was enqueued on the MessageLoop and will run.
188     // We set the flag in case the task hasn't yet run. The flag will stop the
189     // delegate getting called. If the task has run then we have the last
190     // reference to the flag and it will be deleted immediately after.
191     cancel_flag_->Set();
192     cancel_flag_ = nullptr;
193     return;
194   }
195 
196   AutoLock locked(kernel_->lock_);
197   // We have a lock on the kernel. No one else can signal the event while we
198   // have it.
199 
200   // We have a possible ABA issue here. If Dequeue was to compare only the
201   // pointer values then it's possible that the AsyncWaiter could have been
202   // fired, freed and the memory reused for a different Waiter which was
203   // enqueued in the same wait-list. We would think that that waiter was our
204   // AsyncWaiter and remove it.
205   //
206   // To stop this, Dequeue also takes a tag argument which is passed to the
207   // virtual Compare function before the two are considered a match. So we need
208   // a tag which is good for the lifetime of this handle: the Flag. Since we
209   // have a reference to the Flag, its memory cannot be reused while this object
210   // still exists. So if we find a waiter with the correct pointer value, and
211   // which shares a Flag pointer, we have a real match.
212   if (kernel_->Dequeue(waiter_, cancel_flag_.get())) {
213     // Case 2: the waiter hasn't been signaled yet; it was still on the wait
214     // list. We've removed it, thus we can delete it and the task (which cannot
215     // have been enqueued with the MessageLoop because the waiter was never
216     // signaled)
217     delete waiter_;
218     cancel_flag_ = nullptr;
219     return;
220   }
221 
222   // Case 3: the waiter isn't on the wait-list, thus it was signaled. It may not
223   // have run yet, so we set the flag to tell it not to bother enqueuing the
224   // task on the SequencedTaskRunner, but to delete it instead. The Waiter
225   // deletes itself once run.
226   cancel_flag_->Set();
227   cancel_flag_ = nullptr;
228 
229   // If the waiter has already run then the task has been enqueued. If the Task
230   // hasn't yet run, the flag will stop the delegate from getting called. (This
231   // is thread safe because one may only delete a Handle from the sequence that
232   // called StartWatching()).
233   //
234   // If the delegate has already been called then we have nothing to do. The
235   // task has been deleted by the MessageLoop.
236 }
237 
238 }  // namespace base
239