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.
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 bool SyncMessageFilter::Send(Message
* message
) {
26 base::AutoLock
auto_lock(lock_
);
33 if (!message
->is_sync()) {
35 FROM_HERE
, base::Bind(&SyncMessageFilter::SendOnIOThread
, this, message
));
39 base::WaitableEvent
done_event(true, false);
40 PendingSyncMsg
pending_message(
41 SyncMessage::GetMessageId(*message
),
42 reinterpret_cast<SyncMessage
*>(message
)->GetReplyDeserializer(),
46 base::AutoLock
auto_lock(lock_
);
47 // Can't use this class on the main thread or else it can lead to deadlocks.
48 // Also by definition, can't use this on IO thread since we're blocking it.
49 DCHECK(MessageLoopProxy::current() != listener_loop_
);
50 DCHECK(MessageLoopProxy::current() != io_loop_
);
51 pending_sync_messages_
.insert(&pending_message
);
55 FROM_HERE
, base::Bind(&SyncMessageFilter::SendOnIOThread
, this, message
));
57 base::WaitableEvent
* events
[2] = { shutdown_event_
, &done_event
};
58 base::WaitableEvent::WaitMany(events
, 2);
61 base::AutoLock
auto_lock(lock_
);
62 delete pending_message
.deserializer
;
63 pending_sync_messages_
.erase(&pending_message
);
66 return pending_message
.send_result
;
69 void SyncMessageFilter::OnFilterAdded(Channel
* channel
) {
71 base::AutoLock
auto_lock(lock_
);
72 io_loop_
= MessageLoopProxy::current();
75 void SyncMessageFilter::OnChannelError() {
80 void SyncMessageFilter::OnChannelClosing() {
85 bool SyncMessageFilter::OnMessageReceived(const Message
& message
) {
86 base::AutoLock
auto_lock(lock_
);
87 for (PendingSyncMessages::iterator iter
= pending_sync_messages_
.begin();
88 iter
!= pending_sync_messages_
.end(); ++iter
) {
89 if (SyncMessage::IsMessageReplyTo(message
, (*iter
)->id
)) {
90 if (!message
.is_reply_error()) {
91 (*iter
)->send_result
=
92 (*iter
)->deserializer
->SerializeOutputParameters(message
);
94 (*iter
)->done_event
->Signal();
102 SyncMessageFilter::~SyncMessageFilter() {
105 void SyncMessageFilter::SendOnIOThread(Message
* message
) {
107 channel_
->Send(message
);
111 if (message
->is_sync()) {
112 // We don't know which thread sent it, but it doesn't matter, just signal
120 void SyncMessageFilter::SignalAllEvents() {
121 base::AutoLock
auto_lock(lock_
);
122 for (PendingSyncMessages::iterator iter
= pending_sync_messages_
.begin();
123 iter
!= pending_sync_messages_
.end(); ++iter
) {
124 (*iter
)->done_event
->Signal();