• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9 
10 #include "base/synchronization/waitable_event.h"
11 
12 #include <stddef.h>
13 
14 #include <limits>
15 #include <optional>
16 #include <vector>
17 
18 #include "base/check_op.h"
19 #include "base/memory/stack_allocated.h"
20 #include "base/ranges/algorithm.h"
21 #include "base/synchronization/condition_variable.h"
22 #include "base/synchronization/lock.h"
23 #include "base/threading/scoped_blocking_call.h"
24 #include "base/threading/thread_restrictions.h"
25 #include "base/time/time.h"
26 #include "base/time/time_override.h"
27 
28 // -----------------------------------------------------------------------------
29 // A WaitableEvent on POSIX is implemented as a wait-list. Currently we don't
30 // support cross-process events (where one process can signal an event which
31 // others are waiting on). Because of this, we can avoid having one thread per
32 // listener in several cases.
33 //
34 // The WaitableEvent maintains a list of waiters, protected by a lock. Each
35 // waiter is either an async wait, in which case we have a Task and the
36 // MessageLoop to run it on, or a blocking wait, in which case we have the
37 // condition variable to signal.
38 //
39 // Waiting involves grabbing the lock and adding oneself to the wait list. Async
40 // waits can be canceled, which means grabbing the lock and removing oneself
41 // from the list.
42 //
43 // Waiting on multiple events is handled by adding a single, synchronous wait to
44 // the wait-list of many events. An event passes a pointer to itself when
45 // firing a waiter and so we can store that pointer to find out which event
46 // triggered.
47 // -----------------------------------------------------------------------------
48 
49 namespace base {
50 
51 // -----------------------------------------------------------------------------
52 // This is just an abstract base class for waking the two types of waiters
53 // -----------------------------------------------------------------------------
WaitableEvent(ResetPolicy reset_policy,InitialState initial_state)54 WaitableEvent::WaitableEvent(ResetPolicy reset_policy,
55                              InitialState initial_state)
56     : kernel_(new WaitableEventKernel(reset_policy, initial_state)) {}
57 
Reset()58 void WaitableEvent::Reset() {
59   base::AutoLock locked(kernel_->lock_);
60   kernel_->signaled_ = false;
61 }
62 
SignalImpl()63 void WaitableEvent::SignalImpl() {
64   base::AutoLock locked(kernel_->lock_);
65 
66   if (kernel_->signaled_)
67     return;
68 
69   if (kernel_->manual_reset_) {
70     SignalAll();
71     kernel_->signaled_ = true;
72   } else {
73     // In the case of auto reset, if no waiters were woken, we remain
74     // signaled.
75     if (!SignalOne())
76       kernel_->signaled_ = true;
77   }
78 }
79 
IsSignaled() const80 bool WaitableEvent::IsSignaled() const {
81   base::AutoLock locked(kernel_->lock_);
82 
83   const bool result = kernel_->signaled_;
84   if (result && !kernel_->manual_reset_)
85     kernel_->signaled_ = false;
86   return result;
87 }
88 
89 // -----------------------------------------------------------------------------
90 // Synchronous waits
91 
92 // -----------------------------------------------------------------------------
93 // This is a synchronous waiter. The thread is waiting on the given condition
94 // variable and the fired flag in this object.
95 // -----------------------------------------------------------------------------
96 class SyncWaiter : public WaitableEvent::Waiter {
97   STACK_ALLOCATED();
98 
99  public:
SyncWaiter()100   SyncWaiter()
101       : fired_(false), signaling_event_(nullptr), lock_(), cv_(&lock_) {}
102 
Fire(WaitableEvent * signaling_event)103   bool Fire(WaitableEvent* signaling_event) override {
104     base::AutoLock locked(lock_);
105 
106     if (fired_)
107       return false;
108 
109     fired_ = true;
110     signaling_event_ = signaling_event;
111 
112     cv_.Broadcast();
113 
114     // Unlike AsyncWaiter objects, SyncWaiter objects are stack-allocated on
115     // the blocking thread's stack.  There is no |delete this;| in Fire.  The
116     // SyncWaiter object is destroyed when it goes out of scope.
117 
118     return true;
119   }
120 
signaling_event() const121   WaitableEvent* signaling_event() const {
122     return signaling_event_;
123   }
124 
125   // ---------------------------------------------------------------------------
126   // These waiters are always stack allocated and don't delete themselves. Thus
127   // there's no problem and the ABA tag is the same as the object pointer.
128   // ---------------------------------------------------------------------------
Compare(void * tag)129   bool Compare(void* tag) override { return this == tag; }
130 
131   // ---------------------------------------------------------------------------
132   // Called with lock held.
133   // ---------------------------------------------------------------------------
fired() const134   bool fired() const {
135     return fired_;
136   }
137 
138   // ---------------------------------------------------------------------------
139   // During a TimedWait, we need a way to make sure that an auto-reset
140   // WaitableEvent doesn't think that this event has been signaled between
141   // unlocking it and removing it from the wait-list. Called with lock held.
142   // ---------------------------------------------------------------------------
Disable()143   void Disable() {
144     fired_ = true;
145   }
146 
lock()147   base::Lock* lock() {
148     return &lock_;
149   }
150 
cv()151   base::ConditionVariable* cv() {
152     return &cv_;
153   }
154 
155  private:
156   bool fired_;
157   WaitableEvent* signaling_event_ = nullptr;  // The WaitableEvent which woke us
158   base::Lock lock_;
159   base::ConditionVariable cv_;
160 };
161 
TimedWaitImpl(TimeDelta wait_delta)162 bool WaitableEvent::TimedWaitImpl(TimeDelta wait_delta) {
163   kernel_->lock_.Acquire();
164   if (kernel_->signaled_) {
165     if (!kernel_->manual_reset_) {
166       // In this case we were signaled when we had no waiters. Now that
167       // someone has waited upon us, we can automatically reset.
168       kernel_->signaled_ = false;
169     }
170 
171     kernel_->lock_.Release();
172     return true;
173   }
174 
175   SyncWaiter sw;
176   if (only_used_while_idle_) {
177     sw.cv()->declare_only_used_while_idle();
178   }
179   sw.lock()->Acquire();
180 
181   Enqueue(&sw);
182   kernel_->lock_.Release();
183   // We are violating locking order here by holding the SyncWaiter lock but not
184   // the WaitableEvent lock. However, this is safe because we don't lock |lock_|
185   // again before unlocking it.
186 
187   // TimeTicks takes care of overflow but we special case is_max() nonetheless
188   // to avoid invoking TimeTicksNowIgnoringOverride() unnecessarily (same for
189   // the increment step of the for loop if the condition variable returns
190   // early). Ref: https://crbug.com/910524#c7
191   const TimeTicks end_time =
192       wait_delta.is_max() ? TimeTicks::Max()
193                           : subtle::TimeTicksNowIgnoringOverride() + wait_delta;
194   for (TimeDelta remaining = wait_delta; remaining.is_positive() && !sw.fired();
195        remaining = end_time.is_max()
196                        ? TimeDelta::Max()
197                        : end_time - subtle::TimeTicksNowIgnoringOverride()) {
198     if (end_time.is_max())
199       sw.cv()->Wait();
200     else
201       sw.cv()->TimedWait(remaining);
202   }
203 
204   // Get the SyncWaiter signaled state before releasing the lock.
205   const bool return_value = sw.fired();
206 
207   // We can't acquire |lock_| before releasing the SyncWaiter lock (because of
208   // locking order), however, in between the two a signal could be fired and
209   // |sw| would accept it, however we will still return false, so the signal
210   // would be lost on an auto-reset WaitableEvent. Thus we call Disable which
211   // makes sw::Fire return false.
212   sw.Disable();
213   sw.lock()->Release();
214 
215   // This is a bug that has been enshrined in the interface of WaitableEvent
216   // now: |Dequeue| is called even when |sw.fired()| is true, even though it'll
217   // always return false in that case. However, taking the lock ensures that
218   // |Signal| has completed before we return and means that a WaitableEvent can
219   // synchronise its own destruction.
220   kernel_->lock_.Acquire();
221   kernel_->Dequeue(&sw, &sw);
222   kernel_->lock_.Release();
223 
224   return return_value;
225 }
226 
227 // -----------------------------------------------------------------------------
228 // Synchronous waiting on multiple objects.
229 
230 static bool  // StrictWeakOrdering
cmp_fst_addr(const std::pair<WaitableEvent *,unsigned> & a,const std::pair<WaitableEvent *,unsigned> & b)231 cmp_fst_addr(const std::pair<WaitableEvent*, unsigned> &a,
232              const std::pair<WaitableEvent*, unsigned> &b) {
233   return a.first < b.first;
234 }
235 
236 // static
237 // NO_THREAD_SAFETY_ANALYSIS: Complex control flow.
WaitManyImpl(WaitableEvent ** raw_waitables,size_t count)238 size_t WaitableEvent::WaitManyImpl(WaitableEvent** raw_waitables,
239                                    size_t count) NO_THREAD_SAFETY_ANALYSIS {
240   // We need to acquire the locks in a globally consistent order. Thus we sort
241   // the array of waitables by address. We actually sort a pairs so that we can
242   // map back to the original index values later.
243   std::vector<std::pair<WaitableEvent*, size_t> > waitables;
244   waitables.reserve(count);
245   for (size_t i = 0; i < count; ++i)
246     waitables.push_back(std::make_pair(raw_waitables[i], i));
247 
248   DCHECK_EQ(count, waitables.size());
249 
250   ranges::sort(waitables, cmp_fst_addr);
251 
252   // The set of waitables must be distinct. Since we have just sorted by
253   // address, we can check this cheaply by comparing pairs of consecutive
254   // elements.
255   for (size_t i = 0; i < waitables.size() - 1; ++i) {
256     DCHECK(waitables[i].first != waitables[i+1].first);
257   }
258 
259   SyncWaiter sw;
260 
261   const size_t r = EnqueueMany(&waitables[0], count, &sw);
262   if (r < count) {
263     // One of the events is already signaled. The SyncWaiter has not been
264     // enqueued anywhere.
265     return waitables[r].second;
266   }
267 
268   // At this point, we hold the locks on all the WaitableEvents and we have
269   // enqueued our waiter in them all.
270   sw.lock()->Acquire();
271     // Release the WaitableEvent locks in the reverse order
272     for (size_t i = 0; i < count; ++i) {
273       waitables[count - (1 + i)].first->kernel_->lock_.Release();
274     }
275 
276     for (;;) {
277       if (sw.fired())
278         break;
279 
280       sw.cv()->Wait();
281     }
282   sw.lock()->Release();
283 
284   // The address of the WaitableEvent which fired is stored in the SyncWaiter.
285   WaitableEvent *const signaled_event = sw.signaling_event();
286   // This will store the index of the raw_waitables which fired.
287   size_t signaled_index = 0;
288 
289   // Take the locks of each WaitableEvent in turn (except the signaled one) and
290   // remove our SyncWaiter from the wait-list
291   for (size_t i = 0; i < count; ++i) {
292     if (raw_waitables[i] != signaled_event) {
293       raw_waitables[i]->kernel_->lock_.Acquire();
294         // There's no possible ABA issue with the address of the SyncWaiter here
295         // because it lives on the stack. Thus the tag value is just the pointer
296         // value again.
297         raw_waitables[i]->kernel_->Dequeue(&sw, &sw);
298       raw_waitables[i]->kernel_->lock_.Release();
299     } else {
300       // By taking this lock here we ensure that |Signal| has completed by the
301       // time we return, because |Signal| holds this lock. This matches the
302       // behaviour of |Wait| and |TimedWait|.
303       raw_waitables[i]->kernel_->lock_.Acquire();
304       raw_waitables[i]->kernel_->lock_.Release();
305       signaled_index = i;
306     }
307   }
308 
309   return signaled_index;
310 }
311 
312 // -----------------------------------------------------------------------------
313 // If return value == count:
314 //   The locks of the WaitableEvents have been taken in order and the Waiter has
315 //   been enqueued in the wait-list of each. None of the WaitableEvents are
316 //   currently signaled
317 // else:
318 //   None of the WaitableEvent locks are held. The Waiter has not been enqueued
319 //   in any of them and the return value is the index of the WaitableEvent which
320 //   was signaled with the lowest input index from the original WaitMany call.
321 // -----------------------------------------------------------------------------
322 // static
323 // NO_THREAD_SAFETY_ANALYSIS: Complex control flow.
EnqueueMany(std::pair<WaitableEvent *,size_t> * waitables,size_t count,Waiter * waiter)324 size_t WaitableEvent::EnqueueMany(std::pair<WaitableEvent*, size_t>* waitables,
325                                   size_t count,
326                                   Waiter* waiter) NO_THREAD_SAFETY_ANALYSIS {
327   size_t winner = count;
328   size_t winner_index = count;
329   for (size_t i = 0; i < count; ++i) {
330     auto& kernel = waitables[i].first->kernel_;
331     kernel->lock_.Acquire();
332     if (kernel->signaled_ && waitables[i].second < winner) {
333       winner = waitables[i].second;
334       winner_index = i;
335     }
336   }
337 
338   // No events signaled. All locks acquired. Enqueue the Waiter on all of them
339   // and return.
340   if (winner == count) {
341     for (size_t i = 0; i < count; ++i)
342       waitables[i].first->Enqueue(waiter);
343     return count;
344   }
345 
346   // Unlock in reverse order and possibly clear the chosen winner's signal
347   // before returning its index.
348   for (auto* w = waitables + count - 1; w >= waitables; --w) {
349     auto& kernel = w->first->kernel_;
350     if (w->second == winner) {
351       if (!kernel->manual_reset_)
352         kernel->signaled_ = false;
353     }
354     kernel->lock_.Release();
355   }
356 
357   return winner_index;
358 }
359 
360 // -----------------------------------------------------------------------------
361 
362 
363 // -----------------------------------------------------------------------------
364 // Private functions...
365 
WaitableEventKernel(ResetPolicy reset_policy,InitialState initial_state)366 WaitableEvent::WaitableEventKernel::WaitableEventKernel(
367     ResetPolicy reset_policy,
368     InitialState initial_state)
369     : manual_reset_(reset_policy == ResetPolicy::MANUAL),
370       signaled_(initial_state == InitialState::SIGNALED) {}
371 
372 WaitableEvent::WaitableEventKernel::~WaitableEventKernel() = default;
373 
374 // -----------------------------------------------------------------------------
375 // Wake all waiting waiters. Called with lock held.
376 // -----------------------------------------------------------------------------
SignalAll()377 bool WaitableEvent::SignalAll() {
378   bool signaled_at_least_one = false;
379 
380   for (Waiter* i : kernel_->waiters_) {
381     if (i->Fire(this))
382       signaled_at_least_one = true;
383   }
384 
385   kernel_->waiters_.clear();
386   return signaled_at_least_one;
387 }
388 
389 // ---------------------------------------------------------------------------
390 // Try to wake a single waiter. Return true if one was woken. Called with lock
391 // held.
392 // ---------------------------------------------------------------------------
SignalOne()393 bool WaitableEvent::SignalOne() {
394   for (;;) {
395     if (kernel_->waiters_.empty())
396       return false;
397 
398     const bool r = (*kernel_->waiters_.begin())->Fire(this);
399     kernel_->waiters_.pop_front();
400     if (r)
401       return true;
402   }
403 }
404 
405 // -----------------------------------------------------------------------------
406 // Add a waiter to the list of those waiting. Called with lock held.
407 // -----------------------------------------------------------------------------
Enqueue(Waiter * waiter)408 void WaitableEvent::Enqueue(Waiter* waiter) {
409   kernel_->waiters_.push_back(waiter);
410 }
411 
412 // -----------------------------------------------------------------------------
413 // Remove a waiter from the list of those waiting. Return true if the waiter was
414 // actually removed. Called with lock held.
415 // -----------------------------------------------------------------------------
Dequeue(Waiter * waiter,void * tag)416 bool WaitableEvent::WaitableEventKernel::Dequeue(Waiter* waiter, void* tag) {
417   for (auto i = waiters_.begin(); i != waiters_.end(); ++i) {
418     if (*i == waiter && (*i)->Compare(tag)) {
419       waiters_.erase(i);
420       return true;
421     }
422   }
423 
424   return false;
425 }
426 
427 // -----------------------------------------------------------------------------
428 
429 }  // namespace base
430