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
3 // found in the LICENSE file.
4
5 #include "ppapi/shared_impl/tracked_callback.h"
6
7 #include "base/bind.h"
8 #include "base/compiler_specific.h"
9 #include "base/logging.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/synchronization/lock.h"
12 #include "ppapi/c/pp_completion_callback.h"
13 #include "ppapi/c/pp_errors.h"
14 #include "ppapi/c/ppb_message_loop.h"
15 #include "ppapi/shared_impl/callback_tracker.h"
16 #include "ppapi/shared_impl/ppapi_globals.h"
17 #include "ppapi/shared_impl/ppb_message_loop_shared.h"
18 #include "ppapi/shared_impl/proxy_lock.h"
19 #include "ppapi/shared_impl/resource.h"
20
21 namespace ppapi {
22
23 namespace {
24
IsMainThread()25 bool IsMainThread() {
26 return PpapiGlobals::Get()
27 ->GetMainThreadMessageLoop()
28 ->BelongsToCurrentThread();
29 }
30
RunCompletionTask(TrackedCallback::CompletionTask completion_task,int32_t result)31 int32_t RunCompletionTask(TrackedCallback::CompletionTask completion_task,
32 int32_t result) {
33 int32_t task_result = completion_task.Run(result);
34 if (result != PP_ERROR_ABORTED)
35 result = task_result;
36 return result;
37 }
38
39 } // namespace
40
41 // TrackedCallback -------------------------------------------------------------
42
43 // Note: don't keep a Resource* since it may go out of scope before us.
TrackedCallback(Resource * resource,const PP_CompletionCallback & callback)44 TrackedCallback::TrackedCallback(Resource* resource,
45 const PP_CompletionCallback& callback)
46 : is_scheduled_(false),
47 resource_id_(resource ? resource->pp_resource() : 0),
48 completed_(false),
49 aborted_(false),
50 callback_(callback),
51 target_loop_(PpapiGlobals::Get()->GetCurrentMessageLoop()),
52 result_for_blocked_callback_(PP_OK) {
53 // 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.
55 // The Enter class should handle checking this for us.
56
57 // TODO(dmichael): Add tracking at the instance level, for callbacks that only
58 // have an instance (e.g. for MouseLock).
59 if (resource) {
60 tracker_ = PpapiGlobals::Get()->GetCallbackTrackerForInstance(
61 resource->pp_instance());
62 tracker_->Add(make_scoped_refptr(this));
63 }
64
65 base::Lock* proxy_lock = ProxyLock::Get();
66 if (proxy_lock) {
67 // If the proxy_lock is valid, we're running out-of-process, and locking
68 // is enabled.
69 if (is_blocking()) {
70 // This is a blocking completion callback, so we will need a condition
71 // variable for blocking & signalling the calling thread.
72 operation_completed_condvar_.reset(
73 new base::ConditionVariable(proxy_lock));
74 } else {
75 // 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,
77 // EnterResource::SetResult will check to make sure the callback is valid
78 // and take appropriate action.
79 }
80 }
81 }
82
~TrackedCallback()83 TrackedCallback::~TrackedCallback() {}
84
Abort()85 void TrackedCallback::Abort() { Run(PP_ERROR_ABORTED); }
86
PostAbort()87 void TrackedCallback::PostAbort() { PostRun(PP_ERROR_ABORTED); }
88
Run(int32_t result)89 void TrackedCallback::Run(int32_t result) {
90 // 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
92 // 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
94 // callback will go away when all referring Closures go away.
95 if (completed())
96 return;
97 if (result == PP_ERROR_ABORTED)
98 aborted_ = true;
99
100 // 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
102 // trumps a result that was scheduled before, so we should make sure to pass
103 // PP_ERROR_ABORTED.
104 if (aborted())
105 result = PP_ERROR_ABORTED;
106
107 if (is_blocking()) {
108 // If the condition variable is invalid, there are two possibilities. One,
109 // we're running in-process, in which case the call should have come in on
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 // If there's a target_loop_, and we're not on the right thread, we need to
128 // post to target_loop_.
129 if (target_loop_.get() &&
130 target_loop_.get() != PpapiGlobals::Get()->GetCurrentMessageLoop()) {
131 PostRun(result);
132 return;
133 }
134
135 // Copy callback fields now, since |MarkAsCompleted()| may delete us.
136 PP_CompletionCallback callback = callback_;
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
143 if (!completion_task.is_null())
144 result = RunCompletionTask(completion_task, result);
145
146 // TODO(dmichael): Associate a message loop with the callback; if it's not
147 // the same as the current thread's loop, then post it to the right loop.
148 CallWhileUnlocked(PP_RunCompletionCallback, &callback, result);
149 }
150 }
151
PostRun(int32_t result)152 void TrackedCallback::PostRun(int32_t result) {
153 if (completed()) {
154 NOTREACHED();
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_) {
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 }
182
set_completion_task(const CompletionTask & completion_task)183 void TrackedCallback::set_completion_task(
184 const CompletionTask& completion_task) {
185 DCHECK(completion_task_.is_null());
186 completion_task_ = completion_task;
187 }
188
189 // static
IsPending(const scoped_refptr<TrackedCallback> & callback)190 bool TrackedCallback::IsPending(
191 const scoped_refptr<TrackedCallback>& callback) {
192 if (!callback.get())
193 return false;
194 if (callback->aborted())
195 return false;
196 return !callback->completed();
197 }
198
199 // static
IsScheduledToRun(const scoped_refptr<TrackedCallback> & callback)200 bool TrackedCallback::IsScheduledToRun(
201 const scoped_refptr<TrackedCallback>& callback) {
202 return IsPending(callback) && callback->is_scheduled_;
203 }
204
BlockUntilComplete()205 int32_t TrackedCallback::BlockUntilComplete() {
206 // Note, we are already holding the proxy lock in all these methods, including
207 // this one (see ppapi/thunk/enter.cc for where it gets acquired).
208
209 // It doesn't make sense to wait on a non-blocking callback. Furthermore,
210 // BlockUntilComplete should never be called for in-process plugins, where
211 // blocking callbacks are not supported.
212 CHECK(operation_completed_condvar_.get());
213 if (!is_blocking() || !operation_completed_condvar_.get()) {
214 NOTREACHED();
215 return PP_ERROR_FAILED;
216 }
217
218 while (!completed())
219 operation_completed_condvar_->Wait();
220
221 if (!completion_task_.is_null()) {
222 result_for_blocked_callback_ =
223 RunCompletionTask(completion_task_, result_for_blocked_callback_);
224 completion_task_.Reset();
225 }
226 return result_for_blocked_callback_;
227 }
228
MarkAsCompleted()229 void TrackedCallback::MarkAsCompleted() {
230 DCHECK(!completed());
231
232 // We will be removed; maintain a reference to ensure we won't be deleted
233 // until we're done.
234 scoped_refptr<TrackedCallback> thiz = this;
235 completed_ = true;
236 // We may not have a valid resource, in which case we're not in the tracker.
237 if (resource_id_)
238 tracker_->Remove(thiz);
239 tracker_ = NULL;
240 }
241
242 } // namespace ppapi
243