Wed, 31 Dec 2014 06:09:35 +0100
Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.
1 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
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/waitable_event_watcher.h"
7 #include "base/condition_variable.h"
8 #include "base/lock.h"
9 #include "base/message_loop.h"
10 #include "base/waitable_event.h"
12 #include "mozilla/Attributes.h"
14 namespace base {
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 MessageLoop, and a Task to be posted to it.
21 // The MessageLoop ends up running the task, which calls the delegate.
22 //
23 // Since the wait can be canceled, we have a thread-safe Flag object which is
24 // set when the wait has been canceled. At each stage in the above, we check the
25 // flag before going onto the next stage. Since the wait may only be canceled in
26 // the MessageLoop which runs the Task, we are assured that the delegate cannot
27 // be called after canceling...
29 // -----------------------------------------------------------------------------
30 // A thread-safe, reference-counted, write-once flag.
31 // -----------------------------------------------------------------------------
32 class Flag : public RefCountedThreadSafe<Flag> {
33 public:
34 Flag() { flag_ = false; }
36 void Set() {
37 AutoLock locked(lock_);
38 flag_ = true;
39 }
41 bool value() const {
42 AutoLock locked(lock_);
43 return flag_;
44 }
46 private:
47 mutable Lock lock_;
48 bool flag_;
49 };
51 // -----------------------------------------------------------------------------
52 // This is an asynchronous waiter which posts a task to a MessageLoop when
53 // fired. An AsyncWaiter may only be in a single wait-list.
54 // -----------------------------------------------------------------------------
55 class AsyncWaiter MOZ_FINAL : public WaitableEvent::Waiter {
56 public:
57 AsyncWaiter(MessageLoop* message_loop, Task* task, Flag* flag)
58 : message_loop_(message_loop),
59 cb_task_(task),
60 flag_(flag) { }
62 bool Fire(WaitableEvent* event) {
63 if (flag_->value()) {
64 // If the callback has been canceled, we don't enqueue the task, we just
65 // delete it instead.
66 delete cb_task_;
67 } else {
68 message_loop_->PostTask(FROM_HERE, cb_task_);
69 }
71 // We are removed from the wait-list by the WaitableEvent itself. It only
72 // remains to delete ourselves.
73 delete this;
75 // We can always return true because an AsyncWaiter is never in two
76 // different wait-lists at the same time.
77 return true;
78 }
80 // See StopWatching for discussion
81 bool Compare(void* tag) {
82 return tag == flag_.get();
83 }
85 private:
86 MessageLoop *const message_loop_;
87 Task *const cb_task_;
88 scoped_refptr<Flag> flag_;
89 };
91 // -----------------------------------------------------------------------------
92 // For async waits we need to make a callback in a MessageLoop thread. We do
93 // this by posting this task, which calls the delegate and keeps track of when
94 // the event is canceled.
95 // -----------------------------------------------------------------------------
96 class AsyncCallbackTask : public Task {
97 public:
98 AsyncCallbackTask(Flag* flag, WaitableEventWatcher::Delegate* delegate,
99 WaitableEvent* event)
100 : flag_(flag),
101 delegate_(delegate),
102 event_(event) {
103 }
105 void Run() {
106 // Runs in MessageLoop thread.
107 if (!flag_->value()) {
108 // This is to let the WaitableEventWatcher know that the event has occured
109 // because it needs to be able to return NULL from GetWatchedObject
110 flag_->Set();
111 delegate_->OnWaitableEventSignaled(event_);
112 }
114 // We are deleted by the MessageLoop
115 }
117 private:
118 scoped_refptr<Flag> flag_;
119 WaitableEventWatcher::Delegate *const delegate_;
120 WaitableEvent *const event_;
121 };
123 WaitableEventWatcher::WaitableEventWatcher()
124 : event_(NULL),
125 message_loop_(NULL),
126 cancel_flag_(NULL),
127 callback_task_(NULL) {
128 }
130 WaitableEventWatcher::~WaitableEventWatcher() {
131 StopWatching();
132 }
134 // -----------------------------------------------------------------------------
135 // The Handle is how the user cancels a wait. After deleting the Handle we
136 // insure that the delegate cannot be called.
137 // -----------------------------------------------------------------------------
138 bool WaitableEventWatcher::StartWatching
139 (WaitableEvent* event, WaitableEventWatcher::Delegate* delegate) {
140 MessageLoop *const current_ml = MessageLoop::current();
141 DCHECK(current_ml) << "Cannot create WaitableEventWatcher without a "
142 "current MessageLoop";
144 // A user may call StartWatching from within the callback function. In this
145 // case, we won't know that we have finished watching, expect that the Flag
146 // will have been set in AsyncCallbackTask::Run()
147 if (cancel_flag_.get() && cancel_flag_->value()) {
148 if (message_loop_) {
149 message_loop_->RemoveDestructionObserver(this);
150 message_loop_ = NULL;
151 }
153 cancel_flag_ = NULL;
154 }
156 DCHECK(!cancel_flag_.get()) << "StartWatching called while still watching";
158 cancel_flag_ = new Flag;
159 callback_task_ = new AsyncCallbackTask(cancel_flag_, delegate, event);
160 WaitableEvent::WaitableEventKernel* kernel = event->kernel_.get();
162 AutoLock locked(kernel->lock_);
164 if (kernel->signaled_) {
165 if (!kernel->manual_reset_)
166 kernel->signaled_ = false;
168 // No hairpinning - we can't call the delegate directly here. We have to
169 // enqueue a task on the MessageLoop as normal.
170 current_ml->PostTask(FROM_HERE, callback_task_);
171 return true;
172 }
174 message_loop_ = current_ml;
175 current_ml->AddDestructionObserver(this);
177 event_ = event;
178 kernel_ = kernel;
179 waiter_ = new AsyncWaiter(current_ml, callback_task_, cancel_flag_);
180 event->Enqueue(waiter_);
182 return true;
183 }
185 void WaitableEventWatcher::StopWatching() {
186 if (message_loop_) {
187 message_loop_->RemoveDestructionObserver(this);
188 message_loop_ = NULL;
189 }
191 if (!cancel_flag_.get()) // if not currently watching...
192 return;
194 if (cancel_flag_->value()) {
195 // In this case, the event has fired, but we haven't figured that out yet.
196 // The WaitableEvent may have been deleted too.
197 cancel_flag_ = NULL;
198 return;
199 }
201 if (!kernel_.get()) {
202 // We have no kernel. This means that we never enqueued a Waiter on an
203 // event because the event was already signaled when StartWatching was
204 // called.
205 //
206 // In this case, a task was enqueued on the MessageLoop and will run.
207 // We set the flag in case the task hasn't yet run. The flag will stop the
208 // delegate getting called. If the task has run then we have the last
209 // reference to the flag and it will be deleted immedately after.
210 cancel_flag_->Set();
211 cancel_flag_ = NULL;
212 return;
213 }
215 AutoLock locked(kernel_->lock_);
216 // We have a lock on the kernel. No one else can signal the event while we
217 // have it.
219 // We have a possible ABA issue here. If Dequeue was to compare only the
220 // pointer values then it's possible that the AsyncWaiter could have been
221 // fired, freed and the memory reused for a different Waiter which was
222 // enqueued in the same wait-list. We would think that that waiter was our
223 // AsyncWaiter and remove it.
224 //
225 // To stop this, Dequeue also takes a tag argument which is passed to the
226 // virtual Compare function before the two are considered a match. So we need
227 // a tag which is good for the lifetime of this handle: the Flag. Since we
228 // have a reference to the Flag, its memory cannot be reused while this object
229 // still exists. So if we find a waiter with the correct pointer value, and
230 // which shares a Flag pointer, we have a real match.
231 if (kernel_->Dequeue(waiter_, cancel_flag_.get())) {
232 // Case 2: the waiter hasn't been signaled yet; it was still on the wait
233 // list. We've removed it, thus we can delete it and the task (which cannot
234 // have been enqueued with the MessageLoop because the waiter was never
235 // signaled)
236 delete waiter_;
237 delete callback_task_;
238 cancel_flag_ = NULL;
239 return;
240 }
242 // Case 3: the waiter isn't on the wait-list, thus it was signaled. It may
243 // not have run yet, so we set the flag to tell it not to bother enqueuing the
244 // task on the MessageLoop, but to delete it instead. The Waiter deletes
245 // itself once run.
246 cancel_flag_->Set();
247 cancel_flag_ = NULL;
249 // If the waiter has already run then the task has been enqueued. If the Task
250 // hasn't yet run, the flag will stop the delegate from getting called. (This
251 // is thread safe because one may only delete a Handle from the MessageLoop
252 // thread.)
253 //
254 // If the delegate has already been called then we have nothing to do. The
255 // task has been deleted by the MessageLoop.
256 }
258 WaitableEvent* WaitableEventWatcher::GetWatchedEvent() {
259 if (!cancel_flag_.get())
260 return NULL;
262 if (cancel_flag_->value())
263 return NULL;
265 return event_;
266 }
268 // -----------------------------------------------------------------------------
269 // This is called when the MessageLoop which the callback will be run it is
270 // deleted. We need to cancel the callback as if we had been deleted, but we
271 // will still be deleted at some point in the future.
272 // -----------------------------------------------------------------------------
273 void WaitableEventWatcher::WillDestroyCurrentMessageLoop() {
274 StopWatching();
275 }
277 } // namespace base