1 // Copyright (c) 2011 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 "ipc/ipc_sync_message_filter.h"
8 #include "base/location.h"
9 #include "base/logging.h"
10 #include "base/message_loop_proxy.h"
11 #include "base/synchronization/waitable_event.h"
12 #include "ipc/ipc_sync_message.h"
14 using base::MessageLoopProxy
;
18 SyncMessageFilter::SyncMessageFilter(base::WaitableEvent
* shutdown_event
)
20 listener_loop_(MessageLoopProxy::current()),
21 shutdown_event_(shutdown_event
) {
24 SyncMessageFilter::~SyncMessageFilter() {
27 bool SyncMessageFilter::Send(Message
* message
) {
29 base::AutoLock
auto_lock(lock_
);
36 if (!message
->is_sync()) {
38 FROM_HERE
, base::Bind(&SyncMessageFilter::SendOnIOThread
, this, message
));
42 base::WaitableEvent
done_event(true, false);
43 PendingSyncMsg
pending_message(
44 SyncMessage::GetMessageId(*message
),
45 reinterpret_cast<SyncMessage
*>(message
)->GetReplyDeserializer(),
49 base::AutoLock
auto_lock(lock_
);
50 // Can't use this class on the main thread or else it can lead to deadlocks.
51 // Also by definition, can't use this on IO thread since we're blocking it.
52 DCHECK(MessageLoopProxy::current() != listener_loop_
);
53 DCHECK(MessageLoopProxy::current() != io_loop_
);
54 pending_sync_messages_
.insert(&pending_message
);
58 FROM_HERE
, base::Bind(&SyncMessageFilter::SendOnIOThread
, this, message
));
60 base::WaitableEvent
* events
[2] = { shutdown_event_
, &done_event
};
61 base::WaitableEvent::WaitMany(events
, 2);
64 base::AutoLock
auto_lock(lock_
);
65 delete pending_message
.deserializer
;
66 pending_sync_messages_
.erase(&pending_message
);
69 return pending_message
.send_result
;
72 void SyncMessageFilter::SendOnIOThread(Message
* message
) {
74 channel_
->Send(message
);
78 if (message
->is_sync()) {
79 // We don't know which thread sent it, but it doesn't matter, just signal
87 void SyncMessageFilter::SignalAllEvents() {
88 base::AutoLock
auto_lock(lock_
);
89 for (PendingSyncMessages::iterator iter
= pending_sync_messages_
.begin();
90 iter
!= pending_sync_messages_
.end(); ++iter
) {
91 (*iter
)->done_event
->Signal();
95 void SyncMessageFilter::OnFilterAdded(Channel
* channel
) {
97 base::AutoLock
auto_lock(lock_
);
98 io_loop_
= MessageLoopProxy::current();
101 void SyncMessageFilter::OnChannelError() {
106 void SyncMessageFilter::OnChannelClosing() {
111 bool SyncMessageFilter::OnMessageReceived(const Message
& message
) {
112 base::AutoLock
auto_lock(lock_
);
113 for (PendingSyncMessages::iterator iter
= pending_sync_messages_
.begin();
114 iter
!= pending_sync_messages_
.end(); ++iter
) {
115 if (SyncMessage::IsMessageReplyTo(message
, (*iter
)->id
)) {
116 if (!message
.is_reply_error()) {
117 (*iter
)->send_result
=
118 (*iter
)->deserializer
->SerializeOutputParameters(message
);
120 (*iter
)->done_event
->Signal();