blob: 81f8dc1ce792068993b1230eda22619b7c6651d1 [file] [log] [blame]
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001// 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.
4
5#include "ipc/ipc_sync_channel.h"
6
7#include "base/lazy_instance.h"
8#include "base/logging.h"
9#include "base/thread_local.h"
10#include "base/message_loop.h"
11#include "base/waitable_event.h"
12#include "base/waitable_event_watcher.h"
13#include "ipc/ipc_sync_message.h"
14
15using base::TimeDelta;
16using base::TimeTicks;
17using base::WaitableEvent;
18
19namespace IPC {
20// When we're blocked in a Send(), we need to process incoming synchronous
21// messages right away because it could be blocking our reply (either
22// directly from the same object we're calling, or indirectly through one or
23// more other channels). That means that in SyncContext's OnMessageReceived,
24// we need to process sync message right away if we're blocked. However a
25// simple check isn't sufficient, because the listener thread can be in the
26// process of calling Send.
27// To work around this, when SyncChannel filters a sync message, it sets
28// an event that the listener thread waits on during its Send() call. This
29// allows us to dispatch incoming sync messages when blocked. The race
30// condition is handled because if Send is in the process of being called, it
31// will check the event. In case the listener thread isn't sending a message,
32// we queue a task on the listener thread to dispatch the received messages.
33// The messages are stored in this queue object that's shared among all
34// SyncChannel objects on the same thread (since one object can receive a
35// sync message while another one is blocked).
36
37class SyncChannel::ReceivedSyncMsgQueue :
38 public base::RefCountedThreadSafe<ReceivedSyncMsgQueue> {
39 public:
40 // Returns the ReceivedSyncMsgQueue instance for this thread, creating one
41 // if necessary. Call RemoveContext on the same thread when done.
42 static ReceivedSyncMsgQueue* AddContext() {
43 // We want one ReceivedSyncMsgQueue per listener thread (i.e. since multiple
44 // SyncChannel objects can block the same thread).
45 ReceivedSyncMsgQueue* rv = lazy_tls_ptr_.Pointer()->Get();
46 if (!rv) {
47 rv = new ReceivedSyncMsgQueue();
48 ReceivedSyncMsgQueue::lazy_tls_ptr_.Pointer()->Set(rv);
49 }
50 rv->listener_count_++;
51 return rv;
52 }
53
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090054 // Called on IPC thread when a synchronous message or reply arrives.
55 void QueueMessage(const Message& msg, SyncChannel::SyncContext* context) {
56 bool was_task_pending;
57 {
58 AutoLock auto_lock(message_lock_);
59
60 was_task_pending = task_pending_;
61 task_pending_ = true;
62
63 // We set the event in case the listener thread is blocked (or is about
64 // to). In case it's not, the PostTask dispatches the messages.
65 message_queue_.push_back(QueuedMessage(new Message(msg), context));
66 }
67
68 dispatch_event_.Signal();
69 if (!was_task_pending) {
70 listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
71 this, &ReceivedSyncMsgQueue::DispatchMessagesTask));
72 }
73 }
74
75 void QueueReply(const Message &msg, SyncChannel::SyncContext* context) {
76 received_replies_.push_back(QueuedMessage(new Message(msg), context));
77 }
78
79 // Called on the listener's thread to process any queues synchronous
80 // messages.
81 void DispatchMessagesTask() {
82 {
83 AutoLock auto_lock(message_lock_);
84 task_pending_ = false;
85 }
86 DispatchMessages();
87 }
88
89 void DispatchMessages() {
90 while (true) {
91 Message* message;
92 scoped_refptr<SyncChannel::SyncContext> context;
93 {
94 AutoLock auto_lock(message_lock_);
95 if (message_queue_.empty())
96 break;
97
98 message = message_queue_.front().message;
99 context = message_queue_.front().context;
100 message_queue_.pop_front();
101 }
102
103 context->OnDispatchMessage(*message);
104 delete message;
105 }
106 }
107
108 // SyncChannel calls this in its destructor.
109 void RemoveContext(SyncContext* context) {
110 AutoLock auto_lock(message_lock_);
111
112 SyncMessageQueue::iterator iter = message_queue_.begin();
113 while (iter != message_queue_.end()) {
114 if (iter->context == context) {
115 delete iter->message;
116 iter = message_queue_.erase(iter);
117 } else {
118 iter++;
119 }
120 }
121
122 if (--listener_count_ == 0) {
123 DCHECK(lazy_tls_ptr_.Pointer()->Get());
124 lazy_tls_ptr_.Pointer()->Set(NULL);
125 }
126 }
127
128 WaitableEvent* dispatch_event() { return &dispatch_event_; }
129 MessageLoop* listener_message_loop() { return listener_message_loop_; }
130
131 // Holds a pointer to the per-thread ReceivedSyncMsgQueue object.
132 static base::LazyInstance<base::ThreadLocalPointer<ReceivedSyncMsgQueue> >
133 lazy_tls_ptr_;
134
135 // Called on the ipc thread to check if we can unblock any current Send()
136 // calls based on a queued reply.
137 void DispatchReplies() {
138 for (size_t i = 0; i < received_replies_.size(); ++i) {
139 Message* message = received_replies_[i].message;
140 if (received_replies_[i].context->TryToUnblockListener(message)) {
141 delete message;
142 received_replies_.erase(received_replies_.begin() + i);
143 return;
144 }
145 }
146 }
147
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900148 base::WaitableEventWatcher* top_send_done_watcher() {
149 return top_send_done_watcher_;
150 }
151
152 void set_top_send_done_watcher(base::WaitableEventWatcher* watcher) {
153 top_send_done_watcher_ = watcher;
154 }
155
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900156 private:
jam@chromium.orgb1f47b22009-11-06 06:53:08 +0900157 friend class base::RefCountedThreadSafe<ReceivedSyncMsgQueue>;
158
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900159 // See the comment in SyncChannel::SyncChannel for why this event is created
160 // as manual reset.
161 ReceivedSyncMsgQueue() :
162 dispatch_event_(true, false),
163 listener_message_loop_(MessageLoop::current()),
164 task_pending_(false),
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900165 listener_count_(0),
166 top_send_done_watcher_(NULL) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900167 }
168
jam@chromium.orgb1f47b22009-11-06 06:53:08 +0900169 ~ReceivedSyncMsgQueue() {}
170
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900171 // Holds information about a queued synchronous message or reply.
172 struct QueuedMessage {
173 QueuedMessage(Message* m, SyncContext* c) : message(m), context(c) { }
174 Message* message;
175 scoped_refptr<SyncChannel::SyncContext> context;
176 };
177
178 typedef std::deque<QueuedMessage> SyncMessageQueue;
179 SyncMessageQueue message_queue_;
180
181 std::vector<QueuedMessage> received_replies_;
182
183 // Set when we got a synchronous message that we must respond to as the
184 // sender needs its reply before it can reply to our original synchronous
185 // message.
186 WaitableEvent dispatch_event_;
187 MessageLoop* listener_message_loop_;
188 Lock message_lock_;
189 bool task_pending_;
190 int listener_count_;
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900191
192 // The current send done event watcher for this thread. Used to maintain
193 // a local global stack of send done watchers to ensure that nested sync
194 // message loops complete correctly.
195 base::WaitableEventWatcher* top_send_done_watcher_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900196};
197
198base::LazyInstance<base::ThreadLocalPointer<SyncChannel::ReceivedSyncMsgQueue> >
199 SyncChannel::ReceivedSyncMsgQueue::lazy_tls_ptr_(base::LINKER_INITIALIZED);
200
201SyncChannel::SyncContext::SyncContext(
202 Channel::Listener* listener,
203 MessageFilter* filter,
204 MessageLoop* ipc_thread,
205 WaitableEvent* shutdown_event)
206 : ChannelProxy::Context(listener, filter, ipc_thread),
207 received_sync_msgs_(ReceivedSyncMsgQueue::AddContext()),
208 shutdown_event_(shutdown_event) {
209}
210
211SyncChannel::SyncContext::~SyncContext() {
212 while (!deserializers_.empty())
213 Pop();
214}
215
216// Adds information about an outgoing sync message to the context so that
217// we know how to deserialize the reply. Returns a handle that's set when
218// the reply has arrived.
219void SyncChannel::SyncContext::Push(SyncMessage* sync_msg) {
220 // The event is created as manual reset because in between Signal and
221 // OnObjectSignalled, another Send can happen which would stop the watcher
222 // from being called. The event would get watched later, when the nested
223 // Send completes, so the event will need to remain set.
224 PendingSyncMsg pending(SyncMessage::GetMessageId(*sync_msg),
225 sync_msg->GetReplyDeserializer(),
226 new WaitableEvent(true, false));
227 AutoLock auto_lock(deserializers_lock_);
228 deserializers_.push_back(pending);
229}
230
231bool SyncChannel::SyncContext::Pop() {
232 bool result;
233 {
234 AutoLock auto_lock(deserializers_lock_);
235 PendingSyncMsg msg = deserializers_.back();
236 delete msg.deserializer;
237 delete msg.done_event;
238 msg.done_event = NULL;
239 deserializers_.pop_back();
240 result = msg.send_result;
241 }
242
243 // We got a reply to a synchronous Send() call that's blocking the listener
244 // thread. However, further down the call stack there could be another
245 // blocking Send() call, whose reply we received after we made this last
246 // Send() call. So check if we have any queued replies available that
247 // can now unblock the listener thread.
248 ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
249 received_sync_msgs_.get(), &ReceivedSyncMsgQueue::DispatchReplies));
250
251 return result;
252}
253
254WaitableEvent* SyncChannel::SyncContext::GetSendDoneEvent() {
255 AutoLock auto_lock(deserializers_lock_);
256 return deserializers_.back().done_event;
257}
258
259WaitableEvent* SyncChannel::SyncContext::GetDispatchEvent() {
260 return received_sync_msgs_->dispatch_event();
261}
262
263void SyncChannel::SyncContext::DispatchMessages() {
264 received_sync_msgs_->DispatchMessages();
265}
266
267bool SyncChannel::SyncContext::TryToUnblockListener(const Message* msg) {
268 AutoLock auto_lock(deserializers_lock_);
269 if (deserializers_.empty() ||
270 !SyncMessage::IsMessageReplyTo(*msg, deserializers_.back().id)) {
271 return false;
272 }
273
274 if (!msg->is_reply_error()) {
275 deserializers_.back().send_result = deserializers_.back().deserializer->
276 SerializeOutputParameters(*msg);
277 }
278 deserializers_.back().done_event->Signal();
279
280 return true;
281}
282
283void SyncChannel::SyncContext::Clear() {
284 CancelPendingSends();
285 received_sync_msgs_->RemoveContext(this);
286
287 Context::Clear();
288}
289
290void SyncChannel::SyncContext::OnMessageReceived(const Message& msg) {
291 // Give the filters a chance at processing this message.
292 if (TryFilters(msg))
293 return;
294
295 if (TryToUnblockListener(&msg))
296 return;
297
298 if (msg.should_unblock()) {
299 received_sync_msgs_->QueueMessage(msg, this);
300 return;
301 }
302
303 if (msg.is_reply()) {
304 received_sync_msgs_->QueueReply(msg, this);
305 return;
306 }
307
308 return Context::OnMessageReceivedNoFilter(msg);
309}
310
311void SyncChannel::SyncContext::OnChannelError() {
312 CancelPendingSends();
313 shutdown_watcher_.StopWatching();
314 Context::OnChannelError();
315}
316
317void SyncChannel::SyncContext::OnChannelOpened() {
318 shutdown_watcher_.StartWatching(shutdown_event_, this);
319 Context::OnChannelOpened();
320}
321
322void SyncChannel::SyncContext::OnChannelClosed() {
323 shutdown_watcher_.StopWatching();
324 Context::OnChannelClosed();
325}
326
327void SyncChannel::SyncContext::OnSendTimeout(int message_id) {
328 AutoLock auto_lock(deserializers_lock_);
329 PendingSyncMessageQueue::iterator iter;
330 for (iter = deserializers_.begin(); iter != deserializers_.end(); iter++) {
331 if (iter->id == message_id) {
332 iter->done_event->Signal();
333 break;
334 }
335 }
336}
337
338void SyncChannel::SyncContext::CancelPendingSends() {
339 AutoLock auto_lock(deserializers_lock_);
340 PendingSyncMessageQueue::iterator iter;
341 for (iter = deserializers_.begin(); iter != deserializers_.end(); iter++)
342 iter->done_event->Signal();
343}
344
345void SyncChannel::SyncContext::OnWaitableEventSignaled(WaitableEvent* event) {
346 DCHECK(event == shutdown_event_);
347 // Process shut down before we can get a reply to a synchronous message.
348 // Cancel pending Send calls, which will end up setting the send done event.
349 CancelPendingSends();
350}
351
352
353SyncChannel::SyncChannel(
354 const std::string& channel_id, Channel::Mode mode,
355 Channel::Listener* listener, MessageFilter* filter,
356 MessageLoop* ipc_message_loop, bool create_pipe_now,
357 WaitableEvent* shutdown_event)
358 : ChannelProxy(
359 channel_id, mode, ipc_message_loop,
360 new SyncContext(listener, filter, ipc_message_loop, shutdown_event),
361 create_pipe_now),
362 sync_messages_with_no_timeout_allowed_(true) {
363 // Ideally we only want to watch this object when running a nested message
364 // loop. However, we don't know when it exits if there's another nested
365 // message loop running under it or not, so we wouldn't know whether to
366 // stop or keep watching. So we always watch it, and create the event as
367 // manual reset since the object watcher might otherwise reset the event
368 // when we're doing a WaitMany.
369 dispatch_watcher_.StartWatching(sync_context()->GetDispatchEvent(), this);
370}
371
372SyncChannel::~SyncChannel() {
373}
374
375bool SyncChannel::Send(Message* message) {
376 return SendWithTimeout(message, base::kNoTimeout);
377}
378
379bool SyncChannel::SendWithTimeout(Message* message, int timeout_ms) {
380 if (!message->is_sync()) {
381 ChannelProxy::Send(message);
382 return true;
383 }
384
385 // *this* might get deleted in WaitForReply.
386 scoped_refptr<SyncContext> context(sync_context());
387 if (context->shutdown_event()->IsSignaled()) {
388 delete message;
389 return false;
390 }
391
392 DCHECK(sync_messages_with_no_timeout_allowed_ ||
393 timeout_ms != base::kNoTimeout);
394 SyncMessage* sync_msg = static_cast<SyncMessage*>(message);
395 context->Push(sync_msg);
396 int message_id = SyncMessage::GetMessageId(*sync_msg);
397 WaitableEvent* pump_messages_event = sync_msg->pump_messages_event();
398
399 ChannelProxy::Send(message);
400
401 if (timeout_ms != base::kNoTimeout) {
402 // We use the sync message id so that when a message times out, we don't
403 // confuse it with another send that is either above/below this Send in
404 // the call stack.
405 context->ipc_message_loop()->PostDelayedTask(FROM_HERE,
406 NewRunnableMethod(context.get(),
407 &SyncContext::OnSendTimeout, message_id), timeout_ms);
408 }
409
410 // Wait for reply, or for any other incoming synchronous messages.
411 WaitForReply(pump_messages_event);
412
413 return context->Pop();
414}
415
416void SyncChannel::WaitForReply(WaitableEvent* pump_messages_event) {
417 while (true) {
418 WaitableEvent* objects[] = {
419 sync_context()->GetDispatchEvent(),
420 sync_context()->GetSendDoneEvent(),
421 pump_messages_event
422 };
423
424 unsigned count = pump_messages_event ? 3: 2;
gregoryd@google.com5be8f342009-11-21 02:30:44 +0900425 size_t result = WaitableEvent::WaitMany(objects, count);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900426 if (result == 0 /* dispatch event */) {
427 // We're waiting for a reply, but we received a blocking synchronous
428 // call. We must process it or otherwise a deadlock might occur.
429 sync_context()->GetDispatchEvent()->Reset();
430 sync_context()->DispatchMessages();
431 continue;
432 }
433
434 if (result == 2 /* pump_messages_event */)
435 WaitForReplyWithNestedMessageLoop(); // Start a nested message loop.
436
437 break;
438 }
439}
440
441void SyncChannel::WaitForReplyWithNestedMessageLoop() {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900442 base::WaitableEventWatcher send_done_watcher;
443
444 ReceivedSyncMsgQueue* sync_msg_queue = sync_context()->received_sync_msgs();
445 DCHECK(sync_msg_queue != NULL);
446
447 base::WaitableEventWatcher* old_send_done_event_watcher =
448 sync_msg_queue->top_send_done_watcher();
449
450 base::WaitableEventWatcher::Delegate* old_delegate = NULL;
451 base::WaitableEvent* old_event = NULL;
452
453 // Maintain a local global stack of send done delegates to ensure that
454 // nested sync calls complete in the correct sequence, i.e. the
455 // outermost call completes first, etc.
456 if (old_send_done_event_watcher) {
457 old_delegate = old_send_done_event_watcher->delegate();
458 old_event = old_send_done_event_watcher->GetWatchedEvent();
459 old_send_done_event_watcher->StopWatching();
460 }
461
462 sync_msg_queue->set_top_send_done_watcher(&send_done_watcher);
463
464 send_done_watcher.StartWatching(sync_context()->GetSendDoneEvent(), this);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900465 bool old_state = MessageLoop::current()->NestableTasksAllowed();
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900466
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900467 MessageLoop::current()->SetNestableTasksAllowed(true);
468 MessageLoop::current()->Run();
469 MessageLoop::current()->SetNestableTasksAllowed(old_state);
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900470
471 sync_msg_queue->set_top_send_done_watcher(old_send_done_event_watcher);
ananta@chromium.org2777cb02009-10-15 04:58:13 +0900472 if (old_send_done_event_watcher && old_event) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900473 old_send_done_event_watcher->StartWatching(old_event, old_delegate);
474 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900475}
476
477void SyncChannel::OnWaitableEventSignaled(WaitableEvent* event) {
478 WaitableEvent* dispatch_event = sync_context()->GetDispatchEvent();
479 if (event == dispatch_event) {
480 // The call to DispatchMessages might delete this object, so reregister
481 // the object watcher first.
482 dispatch_event->Reset();
483 dispatch_watcher_.StartWatching(dispatch_event, this);
484 sync_context()->DispatchMessages();
485 } else {
486 // We got the reply, timed out or the process shutdown.
487 DCHECK(event == sync_context()->GetSendDoneEvent());
488 MessageLoop::current()->Quit();
489 }
490}
491
492} // namespace IPC