Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(122)

Side by Side Diff: ppapi/shared_impl/tracked_callback.cc

Issue 923263003: PPAPI: Make TrackedCallback more threadsafe (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "ppapi/shared_impl/tracked_callback.h" 5 #include "ppapi/shared_impl/tracked_callback.h"
6 6
7 #include "base/bind.h" 7 #include "base/bind.h"
8 #include "base/compiler_specific.h" 8 #include "base/compiler_specific.h"
9 #include "base/logging.h" 9 #include "base/logging.h"
10 #include "base/message_loop/message_loop.h" 10 #include "base/message_loop/message_loop.h"
(...skipping 12 matching lines...) Expand all
23 namespace { 23 namespace {
24 24
25 bool IsMainThread() { 25 bool IsMainThread() {
26 return PpapiGlobals::Get() 26 return PpapiGlobals::Get()
27 ->GetMainThreadMessageLoop() 27 ->GetMainThreadMessageLoop()
28 ->BelongsToCurrentThread(); 28 ->BelongsToCurrentThread();
29 } 29 }
30 30
31 int32_t RunCompletionTask(TrackedCallback::CompletionTask completion_task, 31 int32_t RunCompletionTask(TrackedCallback::CompletionTask completion_task,
32 int32_t result) { 32 int32_t result) {
33 ProxyLock::AssertAcquired();
33 int32_t task_result = completion_task.Run(result); 34 int32_t task_result = completion_task.Run(result);
34 if (result != PP_ERROR_ABORTED) 35 if (result != PP_ERROR_ABORTED)
35 result = task_result; 36 result = task_result;
36 return result; 37 return result;
37 } 38 }
38 39
40 void AcquireProxyLockAndRun(const base::Closure& closure) {
41 ProxyAutoLock acquire;
42 closure.Run();
43 }
44
45
39 } // namespace 46 } // namespace
40 47
41 // TrackedCallback ------------------------------------------------------------- 48 // TrackedCallback -------------------------------------------------------------
42 49
43 // Note: don't keep a Resource* since it may go out of scope before us. 50 // Note: don't keep a Resource* since it may go out of scope before us.
44 TrackedCallback::TrackedCallback(Resource* resource, 51 TrackedCallback::TrackedCallback(Resource* resource,
45 const PP_CompletionCallback& callback) 52 const PP_CompletionCallback& callback)
46 : is_scheduled_(false), 53 : is_scheduled_(false),
47 resource_id_(resource ? resource->pp_resource() : 0), 54 resource_id_(resource ? resource->pp_resource() : 0),
48 completed_(false), 55 completed_(false),
49 aborted_(false), 56 aborted_(false),
50 callback_(callback), 57 callback_(callback),
51 target_loop_(PpapiGlobals::Get()->GetCurrentMessageLoop()), 58 target_loop_(PpapiGlobals::Get()->GetCurrentMessageLoop()),
52 result_for_blocked_callback_(PP_OK) { 59 result_for_blocked_callback_(PP_OK) {
53 // Note that target_loop_ may be NULL at this point, if the plugin has not 60 // Note that target_loop_ may be NULL at this point, if the plugin has not
54 // attached a loop to this thread, or if this is an in-process plugin. 61 // attached a loop to this thread, or if this is an in-process plugin.
55 // The Enter class should handle checking this for us. 62 // The Enter class should handle checking this for us.
56 63
57 // TODO(dmichael): Add tracking at the instance level, for callbacks that only 64 // TODO(dmichael): Add tracking at the instance level, for callbacks that only
58 // have an instance (e.g. for MouseLock). 65 // have an instance (e.g. for MouseLock).
59 if (resource) { 66 if (resource) {
60 tracker_ = PpapiGlobals::Get()->GetCallbackTrackerForInstance( 67 tracker_ = PpapiGlobals::Get()->GetCallbackTrackerForInstance(
61 resource->pp_instance()); 68 resource->pp_instance());
62 tracker_->Add(make_scoped_refptr(this)); 69 tracker_->Add(make_scoped_refptr(this));
63 } 70 }
64 71
65 base::Lock* proxy_lock = ProxyLock::Get(); 72 base::Lock* proxy_lock = ProxyLock::Get();
66 if (proxy_lock) { 73 if (proxy_lock) {
74 ProxyLock::AssertAcquired();
67 // If the proxy_lock is valid, we're running out-of-process, and locking 75 // If the proxy_lock is valid, we're running out-of-process, and locking
68 // is enabled. 76 // is enabled.
69 if (is_blocking()) { 77 if (is_blocking()) {
70 // This is a blocking completion callback, so we will need a condition 78 // This is a blocking completion callback, so we will need a condition
71 // variable for blocking & signalling the calling thread. 79 // variable for blocking & signalling the calling thread.
72 operation_completed_condvar_.reset( 80 operation_completed_condvar_.reset(
73 new base::ConditionVariable(proxy_lock)); 81 new base::ConditionVariable(proxy_lock));
74 } else { 82 } else {
75 // It's a non-blocking callback, so we should have a MessageLoopResource 83 // It's a non-blocking callback, so we should have a MessageLoopResource
76 // to dispatch to. Note that we don't error check here, though. Later, 84 // to dispatch to. Note that we don't error check here, though. Later,
77 // EnterResource::SetResult will check to make sure the callback is valid 85 // EnterResource::SetResult will check to make sure the callback is valid
78 // and take appropriate action. 86 // and take appropriate action.
79 } 87 }
80 } 88 }
81 } 89 }
82 90
83 TrackedCallback::~TrackedCallback() {} 91 TrackedCallback::~TrackedCallback() {}
84 92
85 void TrackedCallback::Abort() { Run(PP_ERROR_ABORTED); } 93 void TrackedCallback::Abort() {
94 Run(PP_ERROR_ABORTED);
95 }
86 96
87 void TrackedCallback::PostAbort() { PostRun(PP_ERROR_ABORTED); } 97 void TrackedCallback::PostAbort() {
98 PostRun(PP_ERROR_ABORTED);
99 }
88 100
89 void TrackedCallback::Run(int32_t result) { 101 void TrackedCallback::Run(int32_t result) {
102 // Retain ourselves, since SignalBlockingCallback and MarkAsCompleted might
103 // otherwise cause |this| to be deleted. Do this before acquiring lock_ so
104 // that |this| is definitely valid at the time we release |lock_|.
105 scoped_refptr<TrackedCallback> thiz(this);
106 base::AutoLock acquire(lock_);
90 // Only allow the callback to be run once. Note that this also covers the case 107 // Only allow the callback to be run once. Note that this also covers the case
91 // where the callback was previously Aborted because its associated Resource 108 // where the callback was previously Aborted because its associated Resource
92 // went away. The callback may live on for a while because of a reference from 109 // went away. The callback may live on for a while because of a reference from
93 // a Closure. But when the Closure runs, Run() quietly does nothing, and the 110 // a Closure. But when the Closure runs, Run() quietly does nothing, and the
94 // callback will go away when all referring Closures go away. 111 // callback will go away when all referring Closures go away.
95 if (completed()) 112 if (completed_)
96 return; 113 return;
97 if (result == PP_ERROR_ABORTED) 114 if (result == PP_ERROR_ABORTED)
bbudge 2015/02/25 23:51:31 Would a DCHECK(!aborted_) be useful here?
dmichael (off chromium) 2015/02/27 22:04:40 No :( aborted_ can be set in PostRunWithLock. The
bbudge 2015/03/05 01:29:34 OK, makes sense.
98 aborted_ = true; 115 aborted_ = true;
99 116
100 // Note that this call of Run() may have been scheduled prior to Abort() or 117 // Note that this call of Run() may have been scheduled prior to Abort() or
101 // PostAbort() being called. If we have been told to Abort, that always 118 // PostAbort() being called. If we have been told to Abort, that always
102 // trumps a result that was scheduled before, so we should make sure to pass 119 // trumps a result that was scheduled before, so we should make sure to pass
103 // PP_ERROR_ABORTED. 120 // PP_ERROR_ABORTED.
104 if (aborted()) 121 if (aborted_)
105 result = PP_ERROR_ABORTED; 122 result = PP_ERROR_ABORTED;
106 123
107 if (is_blocking()) { 124 if (is_blocking()) {
108 // If the condition variable is invalid, there are two possibilities. One, 125 // This is a blocking callback; signal the condvar to wake up the thread.
109 // we're running in-process, in which case the call should have come in on 126 SignalBlockingCallback(result);
110 // the main thread and we should have returned PP_ERROR_BLOCKS_MAIN_THREAD
111 // well before this. Otherwise, this callback was not created as a
112 // blocking callback. Either way, there's some internal error.
113 if (!operation_completed_condvar_.get()) {
114 NOTREACHED();
115 return;
116 }
117 result_for_blocked_callback_ = result;
118 // Retain ourselves, since MarkAsCompleted will remove us from the
119 // tracker. Then MarkAsCompleted before waking up the blocked thread,
120 // which could potentially re-enter.
121 scoped_refptr<TrackedCallback> thiz(this);
122 MarkAsCompleted();
123 // Wake up the blocked thread. See BlockUntilComplete for where the thread
124 // Wait()s.
125 operation_completed_condvar_->Signal();
126 } else { 127 } else {
127 // If there's a target_loop_, and we're not on the right thread, we need to 128 // If there's a target_loop_, and we're not on the right thread, we need to
128 // post to target_loop_. 129 // post to target_loop_.
129 if (target_loop_.get() && 130 if (target_loop_.get() &&
130 target_loop_.get() != PpapiGlobals::Get()->GetCurrentMessageLoop()) { 131 target_loop_.get() != PpapiGlobals::Get()->GetCurrentMessageLoop()) {
131 PostRun(result); 132 PostRunImpl(result);
132 return; 133 return;
133 } 134 }
135 // Do this before running the callback in case of reentrancy from running
136 // the completion callback.
137 MarkAsCompletedWithLock();
134 138
135 // Copy callback fields now, since |MarkAsCompleted()| may delete us. 139 if (!completion_task_.is_null())
136 PP_CompletionCallback callback = callback_; 140 result = RunCompletionTask(completion_task_, result);
137 CompletionTask completion_task = completion_task_;
138 completion_task_.Reset();
139 // Do this before running the callback in case of reentrancy from running
140 // the completion task.
141 MarkAsCompleted();
142 141
143 if (!completion_task.is_null()) 142 {
144 result = RunCompletionTask(completion_task, result); 143 base::AutoUnlock release(lock_);
145 144 // Call the callback without lock_ and without the ProxyLock.
146 // TODO(dmichael): Associate a message loop with the callback; if it's not 145 CallWhileUnlocked(PP_RunCompletionCallback, &callback_, result);
147 // the same as the current thread's loop, then post it to the right loop. 146 }
148 CallWhileUnlocked(PP_RunCompletionCallback, &callback, result);
149 } 147 }
150 } 148 }
151 149
152 void TrackedCallback::PostRun(int32_t result) { 150 void TrackedCallback::PostRun(int32_t result) {
153 if (completed()) { 151 base::AutoLock acquire(lock_);
154 NOTREACHED(); 152 PostRunImpl(result);
155 return;
156 }
157 if (result == PP_ERROR_ABORTED)
158 aborted_ = true;
159 // We might abort when there's already a scheduled callback, but callers
160 // should never try to PostRun more than once otherwise.
161 DCHECK(result == PP_ERROR_ABORTED || !is_scheduled_);
162
163 if (is_blocking()) {
164 // We might not have a MessageLoop to post to, so we must call Run()
165 // directly.
166 Run(result);
167 } else {
168 base::Closure callback_closure(
169 RunWhileLocked(base::Bind(&TrackedCallback::Run, this, result)));
170 if (target_loop_.get()) {
171 target_loop_->PostClosure(FROM_HERE, callback_closure, 0);
172 } else {
173 // We must be running in-process and on the main thread (the Enter
174 // classes protect against having a null target_loop_ otherwise).
175 DCHECK(IsMainThread());
176 DCHECK(PpapiGlobals::Get()->IsHostGlobals());
177 base::MessageLoop::current()->PostTask(FROM_HERE, callback_closure);
178 }
179 }
180 is_scheduled_ = true;
181 } 153 }
182 154
183 void TrackedCallback::set_completion_task( 155 void TrackedCallback::set_completion_task(
184 const CompletionTask& completion_task) { 156 const CompletionTask& completion_task) {
157 base::AutoLock acquire(lock_);
185 DCHECK(completion_task_.is_null()); 158 DCHECK(completion_task_.is_null());
186 completion_task_ = completion_task; 159 completion_task_ = completion_task;
187 } 160 }
188 161
189 // static 162 // static
190 bool TrackedCallback::IsPending( 163 bool TrackedCallback::IsPending(
191 const scoped_refptr<TrackedCallback>& callback) { 164 const scoped_refptr<TrackedCallback>& callback) {
192 if (!callback.get()) 165 if (!callback.get())
bbudge 2015/02/25 23:51:31 While you're here, could we eliminate all the .get
dmichael (off chromium) 2015/02/27 22:04:40 Done, thanks
193 return false; 166 return false;
194 if (callback->aborted()) 167 base::AutoLock acquire(callback->lock_);
168 if (callback->aborted_)
195 return false; 169 return false;
196 return !callback->completed(); 170 return !callback->completed_;
197 } 171 }
198 172
199 // static 173 // static
200 bool TrackedCallback::IsScheduledToRun( 174 bool TrackedCallback::IsScheduledToRun(
201 const scoped_refptr<TrackedCallback>& callback) { 175 const scoped_refptr<TrackedCallback>& callback) {
202 return IsPending(callback) && callback->is_scheduled_; 176 if (!callback.get())
177 return false;
178 base::AutoLock acquire(callback->lock_);
179 if (callback->aborted_)
180 return false;
181 return !callback->completed_ && callback->is_scheduled_;
203 } 182 }
204 183
205 int32_t TrackedCallback::BlockUntilComplete() { 184 int32_t TrackedCallback::BlockUntilComplete() {
206 // Note, we are already holding the proxy lock in all these methods, including 185 // Note, we are already holding the proxy lock in this method and many others
207 // this one (see ppapi/thunk/enter.cc for where it gets acquired). 186 // (see ppapi/thunk/enter.cc for where it gets acquired).
187 ProxyLock::AssertAcquired();
188 base::AutoLock acquire(lock_);
208 189
209 // It doesn't make sense to wait on a non-blocking callback. Furthermore, 190 // It doesn't make sense to wait on a non-blocking callback. Furthermore,
210 // BlockUntilComplete should never be called for in-process plugins, where 191 // BlockUntilComplete should never be called for in-process plugins, where
211 // blocking callbacks are not supported. 192 // blocking callbacks are not supported.
212 CHECK(operation_completed_condvar_.get()); 193 CHECK(is_blocking() && operation_completed_condvar_.get());
213 if (!is_blocking() || !operation_completed_condvar_.get()) { 194
214 NOTREACHED(); 195 while (!completed_) {
215 return PP_ERROR_FAILED; 196 // Protect us from being deleted to ensure operation_completd_condvar_ is
bbudge 2015/02/25 23:51:31 sp/completd
197 // available to wait on when we drop our lock.
198 scoped_refptr<TrackedCallback> thiz(this);
199 // Unlock our lock temporarily; any thread that tries to signal us will need
200 // the lock.
201 lock_.Release();
202 operation_completed_condvar_->Wait();
203 // Note that the condvar has re-acquired the ProxyLock for us, and we will
bbudge 2015/02/25 23:51:31 I had to think about this a bit before understandi
dmichael (off chromium) 2015/02/27 22:04:40 I tried rephrasing it; let me know if it's still c
204 // re-acquire lock_ immediately after, preserving lock order.
205 ProxyLock::AssertAcquired();
206 lock_.Acquire();
216 } 207 }
217 208
218 while (!completed())
219 operation_completed_condvar_->Wait();
220
221 if (!completion_task_.is_null()) { 209 if (!completion_task_.is_null()) {
222 result_for_blocked_callback_ = 210 result_for_blocked_callback_ =
223 RunCompletionTask(completion_task_, result_for_blocked_callback_); 211 RunCompletionTask(completion_task_, result_for_blocked_callback_);
224 completion_task_.Reset(); 212 completion_task_.Reset();
225 } 213 }
226 return result_for_blocked_callback_; 214 return result_for_blocked_callback_;
227 } 215 }
228 216
229 void TrackedCallback::MarkAsCompleted() { 217 void TrackedCallback::MarkAsCompleted() {
230 DCHECK(!completed()); 218 base::AutoLock acquire(lock_);
219 MarkAsCompletedWithLock();
220 }
221
222 void TrackedCallback::MarkAsCompletedWithLock() {
223 lock_.AssertAcquired();
224 DCHECK(!completed_);
231 225
232 // We will be removed; maintain a reference to ensure we won't be deleted 226 // We will be removed; maintain a reference to ensure we won't be deleted
233 // until we're done. 227 // until we're done.
234 scoped_refptr<TrackedCallback> thiz = this; 228 scoped_refptr<TrackedCallback> thiz = this;
235 completed_ = true; 229 completed_ = true;
236 // We may not have a valid resource, in which case we're not in the tracker. 230 // We may not have a valid resource, in which case we're not in the tracker.
237 if (resource_id_) 231 if (resource_id_)
238 tracker_->Remove(thiz); 232 tracker_->Remove(thiz);
239 tracker_ = NULL; 233 tracker_ = NULL;
234 target_loop_ = NULL;
235 }
236
237 void TrackedCallback::PostRunImpl(int32_t result) {
238 lock_.AssertAcquired();
239 if (completed_) {
240 NOTREACHED();
241 return;
242 }
243 if (result == PP_ERROR_ABORTED)
244 aborted_ = true;
bbudge 2015/02/25 23:51:31 DCHECK(!aborted_) ?
dmichael (off chromium) 2015/02/27 22:04:40 Some APIs will call PostAbort (e.g. if there's a "
245 // We might abort when there's already a scheduled callback, but callers
246 // should never try to PostRun more than once otherwise.
247 DCHECK(result == PP_ERROR_ABORTED || !is_scheduled_);
248
249 if (is_blocking()) {
250 // We might not have a MessageLoop to post to, so we must Signal
251 // directly.
252 SignalBlockingCallback(result);
253 } else {
254 // Note we can't use "RunWhileLocked" from proxy_lock.h, because it requires
255 // that the ProxyLock is held (to protect Resource and Var ref-counting).
256 // Here, we must not acquire the ProxyLock, because we may be on the IO
257 // thread. But we're not passing any parameters that would require
258 // the ProxyLock (such as Var or Resource).
259 base::Closure callback_closure(
260 base::Bind(&ppapi::AcquireProxyLockAndRun,
261 base::Bind(&TrackedCallback::Run, this, result)));
262 if (target_loop_.get()) {
263 target_loop_->PostClosure(FROM_HERE, callback_closure, 0);
264 } else {
265 // We must be running in-process and on the main thread (the Enter
266 // classes protect against having a null target_loop_ otherwise).
267 DCHECK(IsMainThread());
268 DCHECK(PpapiGlobals::Get()->IsHostGlobals());
269 base::MessageLoop::current()->PostTask(FROM_HERE, callback_closure);
270 }
271 }
272 is_scheduled_ = true;
273 }
274
275 void TrackedCallback::SignalBlockingCallback(int32_t result) {
276 lock_.AssertAcquired();
277 DCHECK(is_blocking());
278 if (!operation_completed_condvar_.get()) {
279 // If the condition variable is invalid, there are two possibilities. One,
280 // we're running in-process, in which case the call should have come in on
281 // the main thread and we should have returned PP_ERROR_BLOCKS_MAIN_THREAD
282 // well before this. Otherwise, this callback was not created as a
283 // blocking callback. Either way, there's some internal error.
284 NOTREACHED();
285 return;
286 }
287 result_for_blocked_callback_ = result;
288 // Retain ourselves, since MarkAsCompleted will remove us from the
289 // tracker. Then MarkAsCompleted before waking up the blocked thread,
290 // which could potentially re-enter.
291 scoped_refptr<TrackedCallback> thiz(this);
292 MarkAsCompletedWithLock();
293 // Wake up the blocked thread. See BlockUntilComplete for where the thread
294 // Wait()s.
295 operation_completed_condvar_->Signal();
240 } 296 }
241 297
242 } // namespace ppapi 298 } // namespace ppapi
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698