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_channel.h"
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/process/process_handle.h"
16 #include "base/run_loop.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/strings/string_util.h"
19 #include "base/synchronization/waitable_event.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/threading/platform_thread.h"
22 #include "base/threading/thread.h"
23 #include "ipc/ipc_listener.h"
24 #include "ipc/ipc_message.h"
25 #include "ipc/ipc_sender.h"
26 #include "ipc/ipc_sync_message_filter.h"
27 #include "ipc/ipc_sync_message_unittest.h"
28 #include "testing/gtest/include/gtest/gtest.h"
30 using base::WaitableEvent
;
35 // Base class for a "process" with listener and IPC threads.
36 class Worker
: public Listener
, public Sender
{
38 // Will create a channel without a name.
39 Worker(Channel::Mode mode
, const std::string
& thread_name
)
40 : done_(new WaitableEvent(false, false)),
41 channel_created_(new WaitableEvent(false, false)),
43 ipc_thread_((thread_name
+ "_ipc").c_str()),
44 listener_thread_((thread_name
+ "_listener").c_str()),
45 overrided_thread_(NULL
),
46 shutdown_event_(true, false),
50 // Will create a named channel and use this name for the threads' name.
51 Worker(const std::string
& channel_name
, Channel::Mode mode
)
52 : done_(new WaitableEvent(false, false)),
53 channel_created_(new WaitableEvent(false, false)),
54 channel_name_(channel_name
),
56 ipc_thread_((channel_name
+ "_ipc").c_str()),
57 listener_thread_((channel_name
+ "_listener").c_str()),
58 overrided_thread_(NULL
),
59 shutdown_event_(true, false),
64 // Shutdown() must be called before destruction.
69 bool Send(Message
* msg
) override
{ return channel_
->Send(msg
); }
70 void WaitForChannelCreation() { channel_created_
->Wait(); }
72 DCHECK(base::MessageLoop::current() == ListenerThread()->message_loop());
76 StartThread(&listener_thread_
, base::MessageLoop::TYPE_DEFAULT
);
77 ListenerThread()->task_runner()->PostTask(
78 FROM_HERE
, base::Bind(&Worker::OnStart
, this));
81 // The IPC thread needs to outlive SyncChannel. We can't do this in
82 // ~Worker(), since that'll reset the vtable pointer (to Worker's), which
83 // may result in a race conditions. See http://crbug.com/25841.
84 WaitableEvent
listener_done(false, false), ipc_done(false, false);
85 ListenerThread()->task_runner()->PostTask(
86 FROM_HERE
, base::Bind(&Worker::OnListenerThreadShutdown1
, this,
87 &listener_done
, &ipc_done
));
91 listener_thread_
.Stop();
94 void OverrideThread(base::Thread
* overrided_thread
) {
95 DCHECK(overrided_thread_
== NULL
);
96 overrided_thread_
= overrided_thread
;
98 bool SendAnswerToLife(bool pump
, bool succeed
) {
100 SyncMessage
* msg
= new SyncChannelTestMsg_AnswerToLife(&answer
);
102 msg
->EnableMessagePumping();
103 bool result
= Send(msg
);
104 DCHECK_EQ(result
, succeed
);
105 DCHECK_EQ(answer
, (succeed
? 42 : 0));
108 bool SendDouble(bool pump
, bool succeed
) {
110 SyncMessage
* msg
= new SyncChannelTestMsg_Double(5, &answer
);
112 msg
->EnableMessagePumping();
113 bool result
= Send(msg
);
114 DCHECK_EQ(result
, succeed
);
115 DCHECK_EQ(answer
, (succeed
? 10 : 0));
118 const std::string
& channel_name() { return channel_name_
; }
119 Channel::Mode
mode() { return mode_
; }
120 WaitableEvent
* done_event() { return done_
.get(); }
121 WaitableEvent
* shutdown_event() { return &shutdown_event_
; }
122 void ResetChannel() { channel_
.reset(); }
123 // Derived classes need to call this when they've completed their part of
125 void Done() { done_
->Signal(); }
128 SyncChannel
* channel() { return channel_
.get(); }
129 // Functions for derived classes to implement if they wish.
130 virtual void Run() { }
131 virtual void OnAnswer(int* answer
) { NOTREACHED(); }
132 virtual void OnAnswerDelay(Message
* reply_msg
) {
133 // The message handler map below can only take one entry for
134 // SyncChannelTestMsg_AnswerToLife, so since some classes want
135 // the normal version while other want the delayed reply, we
136 // call the normal version if the derived class didn't override
140 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg
, answer
);
143 virtual void OnDouble(int in
, int* out
) { NOTREACHED(); }
144 virtual void OnDoubleDelay(int in
, Message
* reply_msg
) {
146 OnDouble(in
, &result
);
147 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg
, result
);
151 virtual void OnNestedTestMsg(Message
* reply_msg
) {
155 virtual SyncChannel
* CreateChannel() {
156 scoped_ptr
<SyncChannel
> channel
= SyncChannel::Create(
157 channel_name_
, mode_
, this, ipc_thread_
.task_runner().get(), true,
158 &shutdown_event_
, nullptr);
159 return channel
.release();
162 base::Thread
* ListenerThread() {
163 return overrided_thread_
? overrided_thread_
: &listener_thread_
;
166 const base::Thread
& ipc_thread() const { return ipc_thread_
; }
169 // Called on the listener thread to create the sync channel.
171 // Link ipc_thread_, listener_thread_ and channel_ altogether.
172 StartThread(&ipc_thread_
, base::MessageLoop::TYPE_IO
);
173 channel_
.reset(CreateChannel());
174 channel_created_
->Signal();
178 void OnListenerThreadShutdown1(WaitableEvent
* listener_event
,
179 WaitableEvent
* ipc_event
) {
180 // SyncChannel needs to be destructed on the thread that it was created on.
183 base::RunLoop().RunUntilIdle();
185 ipc_thread_
.message_loop()->PostTask(
186 FROM_HERE
, base::Bind(&Worker::OnIPCThreadShutdown
, this,
187 listener_event
, ipc_event
));
190 void OnIPCThreadShutdown(WaitableEvent
* listener_event
,
191 WaitableEvent
* ipc_event
) {
192 base::RunLoop().RunUntilIdle();
195 listener_thread_
.task_runner()->PostTask(
197 base::Bind(&Worker::OnListenerThreadShutdown2
, this, listener_event
));
200 void OnListenerThreadShutdown2(WaitableEvent
* listener_event
) {
201 base::RunLoop().RunUntilIdle();
202 listener_event
->Signal();
205 bool OnMessageReceived(const Message
& message
) override
{
206 IPC_BEGIN_MESSAGE_MAP(Worker
, message
)
207 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_Double
, OnDoubleDelay
)
208 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_AnswerToLife
,
210 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelNestedTestMsg_String
,
212 IPC_END_MESSAGE_MAP()
216 void StartThread(base::Thread
* thread
, base::MessageLoop::Type type
) {
217 base::Thread::Options options
;
218 options
.message_loop_type
= type
;
219 thread
->StartWithOptions(options
);
222 scoped_ptr
<WaitableEvent
> done_
;
223 scoped_ptr
<WaitableEvent
> channel_created_
;
224 std::string channel_name_
;
226 scoped_ptr
<SyncChannel
> channel_
;
227 base::Thread ipc_thread_
;
228 base::Thread listener_thread_
;
229 base::Thread
* overrided_thread_
;
231 base::WaitableEvent shutdown_event_
;
235 DISALLOW_COPY_AND_ASSIGN(Worker
);
239 // Starts the test with the given workers. This function deletes the workers
241 void RunTest(std::vector
<Worker
*> workers
) {
242 // First we create the workers that are channel servers, or else the other
243 // workers' channel initialization might fail because the pipe isn't created..
244 for (size_t i
= 0; i
< workers
.size(); ++i
) {
245 if (workers
[i
]->mode() & Channel::MODE_SERVER_FLAG
) {
247 workers
[i
]->WaitForChannelCreation();
251 // now create the clients
252 for (size_t i
= 0; i
< workers
.size(); ++i
) {
253 if (workers
[i
]->mode() & Channel::MODE_CLIENT_FLAG
)
257 // wait for all the workers to finish
258 for (size_t i
= 0; i
< workers
.size(); ++i
)
259 workers
[i
]->done_event()->Wait();
261 for (size_t i
= 0; i
< workers
.size(); ++i
) {
262 workers
[i
]->Shutdown();
267 class IPCSyncChannelTest
: public testing::Test
{
269 base::MessageLoop message_loop_
;
272 //------------------------------------------------------------------------------
274 class SimpleServer
: public Worker
{
276 explicit SimpleServer(bool pump_during_send
)
277 : Worker(Channel::MODE_SERVER
, "simpler_server"),
278 pump_during_send_(pump_during_send
) { }
279 void Run() override
{
280 SendAnswerToLife(pump_during_send_
, true);
284 bool pump_during_send_
;
287 class SimpleClient
: public Worker
{
289 SimpleClient() : Worker(Channel::MODE_CLIENT
, "simple_client") { }
291 void OnAnswer(int* answer
) override
{
297 void Simple(bool pump_during_send
) {
298 std::vector
<Worker
*> workers
;
299 workers
.push_back(new SimpleServer(pump_during_send
));
300 workers
.push_back(new SimpleClient());
304 // Tests basic synchronous call
305 TEST_F(IPCSyncChannelTest
, Simple
) {
310 //------------------------------------------------------------------------------
312 // Worker classes which override how the sync channel is created to use the
313 // two-step initialization (calling the lightweight constructor and then
314 // ChannelProxy::Init separately) process.
315 class TwoStepServer
: public Worker
{
317 explicit TwoStepServer(bool create_pipe_now
)
318 : Worker(Channel::MODE_SERVER
, "simpler_server"),
319 create_pipe_now_(create_pipe_now
) { }
321 void Run() override
{
322 SendAnswerToLife(false, true);
326 SyncChannel
* CreateChannel() override
{
327 SyncChannel
* channel
=
328 SyncChannel::Create(channel_name(), mode(), this,
329 ipc_thread().task_runner().get(), create_pipe_now_
,
330 shutdown_event(), nullptr).release();
334 bool create_pipe_now_
;
337 class TwoStepClient
: public Worker
{
339 TwoStepClient(bool create_pipe_now
)
340 : Worker(Channel::MODE_CLIENT
, "simple_client"),
341 create_pipe_now_(create_pipe_now
) { }
343 void OnAnswer(int* answer
) override
{
348 SyncChannel
* CreateChannel() override
{
349 SyncChannel
* channel
=
350 SyncChannel::Create(channel_name(), mode(), this,
351 ipc_thread().task_runner().get(), create_pipe_now_
,
352 shutdown_event(), nullptr).release();
356 bool create_pipe_now_
;
359 void TwoStep(bool create_server_pipe_now
, bool create_client_pipe_now
) {
360 std::vector
<Worker
*> workers
;
361 workers
.push_back(new TwoStepServer(create_server_pipe_now
));
362 workers
.push_back(new TwoStepClient(create_client_pipe_now
));
366 // Tests basic two-step initialization, where you call the lightweight
367 // constructor then Init.
368 TEST_F(IPCSyncChannelTest
, TwoStepInitialization
) {
369 TwoStep(false, false);
370 TwoStep(false, true);
371 TwoStep(true, false);
375 //------------------------------------------------------------------------------
377 class DelayClient
: public Worker
{
379 DelayClient() : Worker(Channel::MODE_CLIENT
, "delay_client") { }
381 void OnAnswerDelay(Message
* reply_msg
) override
{
382 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg
, 42);
388 void DelayReply(bool pump_during_send
) {
389 std::vector
<Worker
*> workers
;
390 workers
.push_back(new SimpleServer(pump_during_send
));
391 workers
.push_back(new DelayClient());
395 // Tests that asynchronous replies work
396 TEST_F(IPCSyncChannelTest
, DelayReply
) {
401 //------------------------------------------------------------------------------
403 class NoHangServer
: public Worker
{
405 NoHangServer(WaitableEvent
* got_first_reply
, bool pump_during_send
)
406 : Worker(Channel::MODE_SERVER
, "no_hang_server"),
407 got_first_reply_(got_first_reply
),
408 pump_during_send_(pump_during_send
) { }
409 void Run() override
{
410 SendAnswerToLife(pump_during_send_
, true);
411 got_first_reply_
->Signal();
413 SendAnswerToLife(pump_during_send_
, false);
417 WaitableEvent
* got_first_reply_
;
418 bool pump_during_send_
;
421 class NoHangClient
: public Worker
{
423 explicit NoHangClient(WaitableEvent
* got_first_reply
)
424 : Worker(Channel::MODE_CLIENT
, "no_hang_client"),
425 got_first_reply_(got_first_reply
) { }
427 void OnAnswerDelay(Message
* reply_msg
) override
{
428 // Use the DELAY_REPLY macro so that we can force the reply to be sent
429 // before this function returns (when the channel will be reset).
430 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg
, 42);
432 got_first_reply_
->Wait();
437 WaitableEvent
* got_first_reply_
;
440 void NoHang(bool pump_during_send
) {
441 WaitableEvent
got_first_reply(false, false);
442 std::vector
<Worker
*> workers
;
443 workers
.push_back(new NoHangServer(&got_first_reply
, pump_during_send
));
444 workers
.push_back(new NoHangClient(&got_first_reply
));
448 // Tests that caller doesn't hang if receiver dies
449 TEST_F(IPCSyncChannelTest
, NoHang
) {
454 //------------------------------------------------------------------------------
456 class UnblockServer
: public Worker
{
458 UnblockServer(bool pump_during_send
, bool delete_during_send
)
459 : Worker(Channel::MODE_SERVER
, "unblock_server"),
460 pump_during_send_(pump_during_send
),
461 delete_during_send_(delete_during_send
) { }
462 void Run() override
{
463 if (delete_during_send_
) {
464 // Use custom code since race conditions mean the answer may or may not be
467 SyncMessage
* msg
= new SyncChannelTestMsg_AnswerToLife(&answer
);
468 if (pump_during_send_
)
469 msg
->EnableMessagePumping();
472 SendAnswerToLife(pump_during_send_
, true);
477 void OnDoubleDelay(int in
, Message
* reply_msg
) override
{
478 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg
, in
* 2);
480 if (delete_during_send_
)
484 bool pump_during_send_
;
485 bool delete_during_send_
;
488 class UnblockClient
: public Worker
{
490 explicit UnblockClient(bool pump_during_send
)
491 : Worker(Channel::MODE_CLIENT
, "unblock_client"),
492 pump_during_send_(pump_during_send
) { }
494 void OnAnswer(int* answer
) override
{
495 SendDouble(pump_during_send_
, true);
500 bool pump_during_send_
;
503 void Unblock(bool server_pump
, bool client_pump
, bool delete_during_send
) {
504 std::vector
<Worker
*> workers
;
505 workers
.push_back(new UnblockServer(server_pump
, delete_during_send
));
506 workers
.push_back(new UnblockClient(client_pump
));
510 // Tests that the caller unblocks to answer a sync message from the receiver.
511 TEST_F(IPCSyncChannelTest
, Unblock
) {
512 Unblock(false, false, false);
513 Unblock(false, true, false);
514 Unblock(true, false, false);
515 Unblock(true, true, false);
518 //------------------------------------------------------------------------------
520 // Tests that the the SyncChannel object can be deleted during a Send.
521 TEST_F(IPCSyncChannelTest
, ChannelDeleteDuringSend
) {
522 Unblock(false, false, true);
523 Unblock(false, true, true);
524 Unblock(true, false, true);
525 Unblock(true, true, true);
528 //------------------------------------------------------------------------------
530 class RecursiveServer
: public Worker
{
532 RecursiveServer(bool expected_send_result
, bool pump_first
, bool pump_second
)
533 : Worker(Channel::MODE_SERVER
, "recursive_server"),
534 expected_send_result_(expected_send_result
),
535 pump_first_(pump_first
), pump_second_(pump_second
) {}
536 void Run() override
{
537 SendDouble(pump_first_
, expected_send_result_
);
541 void OnDouble(int in
, int* out
) override
{
543 SendAnswerToLife(pump_second_
, expected_send_result_
);
546 bool expected_send_result_
, pump_first_
, pump_second_
;
549 class RecursiveClient
: public Worker
{
551 RecursiveClient(bool pump_during_send
, bool close_channel
)
552 : Worker(Channel::MODE_CLIENT
, "recursive_client"),
553 pump_during_send_(pump_during_send
), close_channel_(close_channel
) {}
555 void OnDoubleDelay(int in
, Message
* reply_msg
) override
{
556 SendDouble(pump_during_send_
, !close_channel_
);
557 if (close_channel_
) {
560 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg
, in
* 2);
566 void OnAnswerDelay(Message
* reply_msg
) override
{
567 if (close_channel_
) {
571 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg
, 42);
576 bool pump_during_send_
, close_channel_
;
580 bool server_pump_first
, bool server_pump_second
, bool client_pump
) {
581 std::vector
<Worker
*> workers
;
583 new RecursiveServer(true, server_pump_first
, server_pump_second
));
584 workers
.push_back(new RecursiveClient(client_pump
, false));
588 // Tests a server calling Send while another Send is pending.
589 TEST_F(IPCSyncChannelTest
, Recursive
) {
590 Recursive(false, false, false);
591 Recursive(false, false, true);
592 Recursive(false, true, false);
593 Recursive(false, true, true);
594 Recursive(true, false, false);
595 Recursive(true, false, true);
596 Recursive(true, true, false);
597 Recursive(true, true, true);
600 //------------------------------------------------------------------------------
602 void RecursiveNoHang(
603 bool server_pump_first
, bool server_pump_second
, bool client_pump
) {
604 std::vector
<Worker
*> workers
;
606 new RecursiveServer(false, server_pump_first
, server_pump_second
));
607 workers
.push_back(new RecursiveClient(client_pump
, true));
611 // Tests that if a caller makes a sync call during an existing sync call and
612 // the receiver dies, neither of the Send() calls hang.
613 TEST_F(IPCSyncChannelTest
, RecursiveNoHang
) {
614 RecursiveNoHang(false, false, false);
615 RecursiveNoHang(false, false, true);
616 RecursiveNoHang(false, true, false);
617 RecursiveNoHang(false, true, true);
618 RecursiveNoHang(true, false, false);
619 RecursiveNoHang(true, false, true);
620 RecursiveNoHang(true, true, false);
621 RecursiveNoHang(true, true, true);
624 //------------------------------------------------------------------------------
626 class MultipleServer1
: public Worker
{
628 explicit MultipleServer1(bool pump_during_send
)
629 : Worker("test_channel1", Channel::MODE_SERVER
),
630 pump_during_send_(pump_during_send
) { }
632 void Run() override
{
633 SendDouble(pump_during_send_
, true);
637 bool pump_during_send_
;
640 class MultipleClient1
: public Worker
{
642 MultipleClient1(WaitableEvent
* client1_msg_received
,
643 WaitableEvent
* client1_can_reply
) :
644 Worker("test_channel1", Channel::MODE_CLIENT
),
645 client1_msg_received_(client1_msg_received
),
646 client1_can_reply_(client1_can_reply
) { }
648 void OnDouble(int in
, int* out
) override
{
649 client1_msg_received_
->Signal();
651 client1_can_reply_
->Wait();
656 WaitableEvent
*client1_msg_received_
, *client1_can_reply_
;
659 class MultipleServer2
: public Worker
{
661 MultipleServer2() : Worker("test_channel2", Channel::MODE_SERVER
) { }
663 void OnAnswer(int* result
) override
{
669 class MultipleClient2
: public Worker
{
672 WaitableEvent
* client1_msg_received
, WaitableEvent
* client1_can_reply
,
673 bool pump_during_send
)
674 : Worker("test_channel2", Channel::MODE_CLIENT
),
675 client1_msg_received_(client1_msg_received
),
676 client1_can_reply_(client1_can_reply
),
677 pump_during_send_(pump_during_send
) { }
679 void Run() override
{
680 client1_msg_received_
->Wait();
681 SendAnswerToLife(pump_during_send_
, true);
682 client1_can_reply_
->Signal();
687 WaitableEvent
*client1_msg_received_
, *client1_can_reply_
;
688 bool pump_during_send_
;
691 void Multiple(bool server_pump
, bool client_pump
) {
692 std::vector
<Worker
*> workers
;
694 // A shared worker thread so that server1 and server2 run on one thread.
695 base::Thread
worker_thread("Multiple");
696 ASSERT_TRUE(worker_thread
.Start());
698 // Server1 sends a sync msg to client1, which blocks the reply until
699 // server2 (which runs on the same worker thread as server1) responds
700 // to a sync msg from client2.
701 WaitableEvent
client1_msg_received(false, false);
702 WaitableEvent
client1_can_reply(false, false);
706 worker
= new MultipleServer2();
707 worker
->OverrideThread(&worker_thread
);
708 workers
.push_back(worker
);
710 worker
= new MultipleClient2(
711 &client1_msg_received
, &client1_can_reply
, client_pump
);
712 workers
.push_back(worker
);
714 worker
= new MultipleServer1(server_pump
);
715 worker
->OverrideThread(&worker_thread
);
716 workers
.push_back(worker
);
718 worker
= new MultipleClient1(
719 &client1_msg_received
, &client1_can_reply
);
720 workers
.push_back(worker
);
725 // Tests that multiple SyncObjects on the same listener thread can unblock each
727 TEST_F(IPCSyncChannelTest
, Multiple
) {
728 Multiple(false, false);
729 Multiple(false, true);
730 Multiple(true, false);
731 Multiple(true, true);
734 //------------------------------------------------------------------------------
736 // This class provides server side functionality to test the case where
737 // multiple sync channels are in use on the same thread on the client and
738 // nested calls are issued.
739 class QueuedReplyServer
: public Worker
{
741 QueuedReplyServer(base::Thread
* listener_thread
,
742 const std::string
& channel_name
,
743 const std::string
& reply_text
)
744 : Worker(channel_name
, Channel::MODE_SERVER
),
745 reply_text_(reply_text
) {
746 Worker::OverrideThread(listener_thread
);
749 void OnNestedTestMsg(Message
* reply_msg
) override
{
750 VLOG(1) << __FUNCTION__
<< " Sending reply: " << reply_text_
;
751 SyncChannelNestedTestMsg_String::WriteReplyParams(reply_msg
, reply_text_
);
757 std::string reply_text_
;
760 // The QueuedReplyClient class provides functionality to test the case where
761 // multiple sync channels are in use on the same thread and they make nested
762 // sync calls, i.e. while the first channel waits for a response it makes a
763 // sync call on another channel.
764 // The callstack should unwind correctly, i.e. the outermost call should
765 // complete first, and so on.
766 class QueuedReplyClient
: public Worker
{
768 QueuedReplyClient(base::Thread
* listener_thread
,
769 const std::string
& channel_name
,
770 const std::string
& expected_text
,
771 bool pump_during_send
)
772 : Worker(channel_name
, Channel::MODE_CLIENT
),
773 pump_during_send_(pump_during_send
),
774 expected_text_(expected_text
) {
775 Worker::OverrideThread(listener_thread
);
778 void Run() override
{
779 std::string response
;
780 SyncMessage
* msg
= new SyncChannelNestedTestMsg_String(&response
);
781 if (pump_during_send_
)
782 msg
->EnableMessagePumping();
783 bool result
= Send(msg
);
785 DCHECK_EQ(response
, expected_text_
);
787 VLOG(1) << __FUNCTION__
<< " Received reply: " << response
;
792 bool pump_during_send_
;
793 std::string expected_text_
;
796 void QueuedReply(bool client_pump
) {
797 std::vector
<Worker
*> workers
;
799 // A shared worker thread for servers
800 base::Thread
server_worker_thread("QueuedReply_ServerListener");
801 ASSERT_TRUE(server_worker_thread
.Start());
803 base::Thread
client_worker_thread("QueuedReply_ClientListener");
804 ASSERT_TRUE(client_worker_thread
.Start());
808 worker
= new QueuedReplyServer(&server_worker_thread
,
809 "QueuedReply_Server1",
810 "Got first message");
811 workers
.push_back(worker
);
813 worker
= new QueuedReplyServer(&server_worker_thread
,
814 "QueuedReply_Server2",
815 "Got second message");
816 workers
.push_back(worker
);
818 worker
= new QueuedReplyClient(&client_worker_thread
,
819 "QueuedReply_Server1",
822 workers
.push_back(worker
);
824 worker
= new QueuedReplyClient(&client_worker_thread
,
825 "QueuedReply_Server2",
826 "Got second message",
828 workers
.push_back(worker
);
833 // While a blocking send is in progress, the listener thread might answer other
834 // synchronous messages. This tests that if during the response to another
835 // message the reply to the original messages comes, it is queued up correctly
836 // and the original Send is unblocked later.
837 // We also test that the send call stacks unwind correctly when the channel
838 // pumps messages while waiting for a response.
839 TEST_F(IPCSyncChannelTest
, QueuedReply
) {
844 //------------------------------------------------------------------------------
846 class ChattyClient
: public Worker
{
849 Worker(Channel::MODE_CLIENT
, "chatty_client") { }
851 void OnAnswer(int* answer
) override
{
852 // The PostMessage limit is 10k. Send 20% more than that.
853 const int kMessageLimit
= 10000;
854 const int kMessagesToSend
= kMessageLimit
* 120 / 100;
855 for (int i
= 0; i
< kMessagesToSend
; ++i
) {
856 if (!SendDouble(false, true))
864 void ChattyServer(bool pump_during_send
) {
865 std::vector
<Worker
*> workers
;
866 workers
.push_back(new UnblockServer(pump_during_send
, false));
867 workers
.push_back(new ChattyClient());
871 // Tests http://b/1093251 - that sending lots of sync messages while
872 // the receiver is waiting for a sync reply does not overflow the PostMessage
874 TEST_F(IPCSyncChannelTest
, ChattyServer
) {
879 //------------------------------------------------------------------------------
881 void NestedCallback(Worker
* server
) {
882 // Sleep a bit so that we wake up after the reply has been received.
883 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(250));
884 server
->SendAnswerToLife(true, true);
887 bool timeout_occurred
= false;
889 void TimeoutCallback() {
890 timeout_occurred
= true;
893 class DoneEventRaceServer
: public Worker
{
895 DoneEventRaceServer()
896 : Worker(Channel::MODE_SERVER
, "done_event_race_server") { }
898 void Run() override
{
899 base::ThreadTaskRunnerHandle::Get()->PostTask(
900 FROM_HERE
, base::Bind(&NestedCallback
, this));
901 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
902 FROM_HERE
, base::Bind(&TimeoutCallback
),
903 base::TimeDelta::FromSeconds(9));
904 // Even though we have a timeout on the Send, it will succeed since for this
905 // bug, the reply message comes back and is deserialized, however the done
906 // event wasn't set. So we indirectly use the timeout task to notice if a
908 SendAnswerToLife(true, true);
909 DCHECK(!timeout_occurred
);
914 // Tests http://b/1474092 - that if after the done_event is set but before
915 // OnObjectSignaled is called another message is sent out, then after its
916 // reply comes back OnObjectSignaled will be called for the first message.
917 TEST_F(IPCSyncChannelTest
, DoneEventRace
) {
918 std::vector
<Worker
*> workers
;
919 workers
.push_back(new DoneEventRaceServer());
920 workers
.push_back(new SimpleClient());
924 //------------------------------------------------------------------------------
926 class TestSyncMessageFilter
: public SyncMessageFilter
{
928 TestSyncMessageFilter(
929 base::WaitableEvent
* shutdown_event
,
931 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
)
932 : SyncMessageFilter(shutdown_event
),
934 task_runner_(task_runner
) {}
936 void OnFilterAdded(Sender
* sender
) override
{
937 SyncMessageFilter::OnFilterAdded(sender
);
938 task_runner_
->PostTask(
940 base::Bind(&TestSyncMessageFilter::SendMessageOnHelperThread
, this));
943 void SendMessageOnHelperThread() {
945 bool result
= Send(new SyncChannelTestMsg_AnswerToLife(&answer
));
947 DCHECK_EQ(answer
, 42);
953 ~TestSyncMessageFilter() override
{}
956 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
959 class SyncMessageFilterServer
: public Worker
{
961 SyncMessageFilterServer()
962 : Worker(Channel::MODE_SERVER
, "sync_message_filter_server"),
963 thread_("helper_thread") {
964 base::Thread::Options options
;
965 options
.message_loop_type
= base::MessageLoop::TYPE_DEFAULT
;
966 thread_
.StartWithOptions(options
);
967 filter_
= new TestSyncMessageFilter(shutdown_event(), this,
968 thread_
.task_runner());
971 void Run() override
{
972 channel()->AddFilter(filter_
.get());
975 base::Thread thread_
;
976 scoped_refptr
<TestSyncMessageFilter
> filter_
;
979 // This class provides functionality to test the case that a Send on the sync
980 // channel does not crash after the channel has been closed.
981 class ServerSendAfterClose
: public Worker
{
983 ServerSendAfterClose()
984 : Worker(Channel::MODE_SERVER
, "simpler_server"),
989 ListenerThread()->task_runner()->PostTask(
990 FROM_HERE
, base::Bind(base::IgnoreResult(&ServerSendAfterClose::Send
),
991 this, new SyncChannelTestMsg_NoArgs
));
995 bool send_result() const {
1000 void Run() override
{
1005 bool Send(Message
* msg
) override
{
1006 send_result_
= Worker::Send(msg
);
1008 return send_result_
;
1014 // Tests basic synchronous call
1015 TEST_F(IPCSyncChannelTest
, SyncMessageFilter
) {
1016 std::vector
<Worker
*> workers
;
1017 workers
.push_back(new SyncMessageFilterServer());
1018 workers
.push_back(new SimpleClient());
1022 // Test the case when the channel is closed and a Send is attempted after that.
1023 TEST_F(IPCSyncChannelTest
, SendAfterClose
) {
1024 ServerSendAfterClose server
;
1027 server
.done_event()->Wait();
1028 server
.done_event()->Reset();
1031 server
.done_event()->Wait();
1033 EXPECT_FALSE(server
.send_result());
1038 //------------------------------------------------------------------------------
1040 class RestrictedDispatchServer
: public Worker
{
1042 RestrictedDispatchServer(WaitableEvent
* sent_ping_event
,
1043 WaitableEvent
* wait_event
)
1044 : Worker("restricted_channel", Channel::MODE_SERVER
),
1045 sent_ping_event_(sent_ping_event
),
1046 wait_event_(wait_event
) { }
1048 void OnDoPing(int ping
) {
1049 // Send an asynchronous message that unblocks the caller.
1050 Message
* msg
= new SyncChannelTestMsg_Ping(ping
);
1051 msg
->set_unblock(true);
1053 // Signal the event after the message has been sent on the channel, on the
1055 ipc_thread().task_runner()->PostTask(
1056 FROM_HERE
, base::Bind(&RestrictedDispatchServer::OnPingSent
, this));
1059 void OnPingTTL(int ping
, int* out
) {
1061 wait_event_
->Wait();
1064 base::Thread
* ListenerThread() { return Worker::ListenerThread(); }
1067 bool OnMessageReceived(const Message
& message
) override
{
1068 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchServer
, message
)
1069 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs
, OnNoArgs
)
1070 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_PingTTL
, OnPingTTL
)
1071 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Done
, Done
)
1072 IPC_END_MESSAGE_MAP()
1077 sent_ping_event_
->Signal();
1081 WaitableEvent
* sent_ping_event_
;
1082 WaitableEvent
* wait_event_
;
1085 class NonRestrictedDispatchServer
: public Worker
{
1087 NonRestrictedDispatchServer(WaitableEvent
* signal_event
)
1088 : Worker("non_restricted_channel", Channel::MODE_SERVER
),
1089 signal_event_(signal_event
) {}
1091 base::Thread
* ListenerThread() { return Worker::ListenerThread(); }
1093 void OnDoPingTTL(int ping
) {
1095 Send(new SyncChannelTestMsg_PingTTL(ping
, &value
));
1096 signal_event_
->Signal();
1100 bool OnMessageReceived(const Message
& message
) override
{
1101 IPC_BEGIN_MESSAGE_MAP(NonRestrictedDispatchServer
, message
)
1102 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs
, OnNoArgs
)
1103 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Done
, Done
)
1104 IPC_END_MESSAGE_MAP()
1109 WaitableEvent
* signal_event_
;
1112 class RestrictedDispatchClient
: public Worker
{
1114 RestrictedDispatchClient(WaitableEvent
* sent_ping_event
,
1115 RestrictedDispatchServer
* server
,
1116 NonRestrictedDispatchServer
* server2
,
1118 : Worker("restricted_channel", Channel::MODE_CLIENT
),
1123 sent_ping_event_(sent_ping_event
) {}
1125 void Run() override
{
1126 // Incoming messages from our channel should only be dispatched when we
1127 // send a message on that same channel.
1128 channel()->SetRestrictDispatchChannelGroup(1);
1130 server_
->ListenerThread()->task_runner()->PostTask(
1131 FROM_HERE
, base::Bind(&RestrictedDispatchServer::OnDoPing
, server_
, 1));
1132 sent_ping_event_
->Wait();
1133 Send(new SyncChannelTestMsg_NoArgs
);
1137 LOG(ERROR
) << "Send failed to dispatch incoming message on same channel";
1139 non_restricted_channel_
= SyncChannel::Create(
1140 "non_restricted_channel", IPC::Channel::MODE_CLIENT
, this,
1141 ipc_thread().task_runner().get(), true, shutdown_event(), nullptr);
1143 server_
->ListenerThread()->task_runner()->PostTask(
1144 FROM_HERE
, base::Bind(&RestrictedDispatchServer::OnDoPing
, server_
, 2));
1145 sent_ping_event_
->Wait();
1146 // Check that the incoming message is *not* dispatched when sending on the
1147 // non restricted channel.
1148 // TODO(piman): there is a possibility of a false positive race condition
1149 // here, if the message that was posted on the server-side end of the pipe
1150 // is not visible yet on the client side, but I don't know how to solve this
1151 // without hooking into the internals of SyncChannel. I haven't seen it in
1152 // practice (i.e. not setting SetRestrictDispatchToSameChannel does cause
1153 // the following to fail).
1154 non_restricted_channel_
->Send(new SyncChannelTestMsg_NoArgs
);
1158 LOG(ERROR
) << "Send dispatched message from restricted channel";
1160 Send(new SyncChannelTestMsg_NoArgs
);
1164 LOG(ERROR
) << "Send failed to dispatch incoming message on same channel";
1166 // Check that the incoming message on the non-restricted channel is
1167 // dispatched when sending on the restricted channel.
1168 server2_
->ListenerThread()->task_runner()->PostTask(
1170 base::Bind(&NonRestrictedDispatchServer::OnDoPingTTL
, server2_
, 3));
1172 Send(new SyncChannelTestMsg_PingTTL(4, &value
));
1173 if (ping_
== 3 && value
== 4)
1176 LOG(ERROR
) << "Send failed to dispatch message from unrestricted channel";
1178 non_restricted_channel_
->Send(new SyncChannelTestMsg_Done
);
1179 non_restricted_channel_
.reset();
1180 Send(new SyncChannelTestMsg_Done
);
1185 bool OnMessageReceived(const Message
& message
) override
{
1186 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchClient
, message
)
1187 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Ping
, OnPing
)
1188 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_PingTTL
, OnPingTTL
)
1189 IPC_END_MESSAGE_MAP()
1193 void OnPing(int ping
) {
1197 void OnPingTTL(int ping
, IPC::Message
* reply
) {
1199 // This message comes from the NonRestrictedDispatchServer, we have to send
1200 // the reply back manually.
1201 SyncChannelTestMsg_PingTTL::WriteReplyParams(reply
, ping
);
1202 non_restricted_channel_
->Send(reply
);
1206 RestrictedDispatchServer
* server_
;
1207 NonRestrictedDispatchServer
* server2_
;
1209 WaitableEvent
* sent_ping_event_
;
1210 scoped_ptr
<SyncChannel
> non_restricted_channel_
;
1213 TEST_F(IPCSyncChannelTest
, RestrictedDispatch
) {
1214 WaitableEvent
sent_ping_event(false, false);
1215 WaitableEvent
wait_event(false, false);
1216 RestrictedDispatchServer
* server
=
1217 new RestrictedDispatchServer(&sent_ping_event
, &wait_event
);
1218 NonRestrictedDispatchServer
* server2
=
1219 new NonRestrictedDispatchServer(&wait_event
);
1222 std::vector
<Worker
*> workers
;
1223 workers
.push_back(server
);
1224 workers
.push_back(server2
);
1225 workers
.push_back(new RestrictedDispatchClient(
1226 &sent_ping_event
, server
, server2
, &success
));
1228 EXPECT_EQ(4, success
);
1231 //------------------------------------------------------------------------------
1233 // This test case inspired by crbug.com/108491
1234 // We create two servers that use the same ListenerThread but have
1235 // SetRestrictDispatchToSameChannel set to true.
1236 // We create clients, then use some specific WaitableEvent wait/signalling to
1237 // ensure that messages get dispatched in a way that causes a deadlock due to
1238 // a nested dispatch and an eligible message in a higher-level dispatch's
1239 // delayed_queue. Specifically, we start with client1 about so send an
1240 // unblocking message to server1, while the shared listener thread for the
1241 // servers server1 and server2 is about to send a non-unblocking message to
1242 // client1. At the same time, client2 will be about to send an unblocking
1243 // message to server2. Server1 will handle the client1->server1 message by
1244 // telling server2 to send a non-unblocking message to client2.
1245 // What should happen is that the send to server2 should find the pending,
1246 // same-context client2->server2 message to dispatch, causing client2 to
1247 // unblock then handle the server2->client2 message, so that the shared
1248 // servers' listener thread can then respond to the client1->server1 message.
1249 // Then client1 can handle the non-unblocking server1->client1 message.
1250 // The old code would end up in a state where the server2->client2 message is
1251 // sent, but the client2->server2 message (which is eligible for dispatch, and
1252 // which is what client2 is waiting for) is stashed in a local delayed_queue
1253 // that has server1's channel context, causing a deadlock.
1254 // WaitableEvents in the events array are used to:
1255 // event 0: indicate to client1 that server listener is in OnDoServerTask
1256 // event 1: indicate to client1 that client2 listener is in OnDoClient2Task
1257 // event 2: indicate to server1 that client2 listener is in OnDoClient2Task
1258 // event 3: indicate to client2 that server listener is in OnDoServerTask
1260 class RestrictedDispatchDeadlockServer
: public Worker
{
1262 RestrictedDispatchDeadlockServer(int server_num
,
1263 WaitableEvent
* server_ready_event
,
1264 WaitableEvent
** events
,
1265 RestrictedDispatchDeadlockServer
* peer
)
1266 : Worker(server_num
== 1 ? "channel1" : "channel2", Channel::MODE_SERVER
),
1267 server_num_(server_num
),
1268 server_ready_event_(server_ready_event
),
1272 void OnDoServerTask() {
1273 events_
[3]->Signal();
1275 events_
[0]->Signal();
1276 SendMessageToClient();
1279 void Run() override
{
1280 channel()->SetRestrictDispatchChannelGroup(1);
1281 server_ready_event_
->Signal();
1284 base::Thread
* ListenerThread() { return Worker::ListenerThread(); }
1287 bool OnMessageReceived(const Message
& message
) override
{
1288 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchDeadlockServer
, message
)
1289 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs
, OnNoArgs
)
1290 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Done
, Done
)
1291 IPC_END_MESSAGE_MAP()
1296 if (server_num_
== 1) {
1297 DCHECK(peer_
!= NULL
);
1298 peer_
->SendMessageToClient();
1302 void SendMessageToClient() {
1303 Message
* msg
= new SyncChannelTestMsg_NoArgs
;
1304 msg
->set_unblock(false);
1305 DCHECK(!msg
->should_unblock());
1310 WaitableEvent
* server_ready_event_
;
1311 WaitableEvent
** events_
;
1312 RestrictedDispatchDeadlockServer
* peer_
;
1315 class RestrictedDispatchDeadlockClient2
: public Worker
{
1317 RestrictedDispatchDeadlockClient2(RestrictedDispatchDeadlockServer
* server
,
1318 WaitableEvent
* server_ready_event
,
1319 WaitableEvent
** events
)
1320 : Worker("channel2", Channel::MODE_CLIENT
),
1321 server_ready_event_(server_ready_event
),
1323 received_msg_(false),
1324 received_noarg_reply_(false),
1325 done_issued_(false) {}
1327 void Run() override
{
1328 server_ready_event_
->Wait();
1331 void OnDoClient2Task() {
1333 events_
[1]->Signal();
1334 events_
[2]->Signal();
1335 DCHECK(received_msg_
== false);
1337 Message
* message
= new SyncChannelTestMsg_NoArgs
;
1338 message
->set_unblock(true);
1340 received_noarg_reply_
= true;
1343 base::Thread
* ListenerThread() { return Worker::ListenerThread(); }
1345 bool OnMessageReceived(const Message
& message
) override
{
1346 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchDeadlockClient2
, message
)
1347 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs
, OnNoArgs
)
1348 IPC_END_MESSAGE_MAP()
1353 received_msg_
= true;
1357 void PossiblyDone() {
1358 if (received_noarg_reply_
&& received_msg_
) {
1359 DCHECK(done_issued_
== false);
1360 done_issued_
= true;
1361 Send(new SyncChannelTestMsg_Done
);
1366 WaitableEvent
* server_ready_event_
;
1367 WaitableEvent
** events_
;
1369 bool received_noarg_reply_
;
1373 class RestrictedDispatchDeadlockClient1
: public Worker
{
1375 RestrictedDispatchDeadlockClient1(RestrictedDispatchDeadlockServer
* server
,
1376 RestrictedDispatchDeadlockClient2
* peer
,
1377 WaitableEvent
* server_ready_event
,
1378 WaitableEvent
** events
)
1379 : Worker("channel1", Channel::MODE_CLIENT
),
1382 server_ready_event_(server_ready_event
),
1384 received_msg_(false),
1385 received_noarg_reply_(false),
1386 done_issued_(false) {}
1388 void Run() override
{
1389 server_ready_event_
->Wait();
1390 server_
->ListenerThread()->task_runner()->PostTask(
1392 base::Bind(&RestrictedDispatchDeadlockServer::OnDoServerTask
, server_
));
1393 peer_
->ListenerThread()->task_runner()->PostTask(
1395 base::Bind(&RestrictedDispatchDeadlockClient2::OnDoClient2Task
, peer_
));
1398 DCHECK(received_msg_
== false);
1400 Message
* message
= new SyncChannelTestMsg_NoArgs
;
1401 message
->set_unblock(true);
1403 received_noarg_reply_
= true;
1408 bool OnMessageReceived(const Message
& message
) override
{
1409 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchDeadlockClient1
, message
)
1410 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs
, OnNoArgs
)
1411 IPC_END_MESSAGE_MAP()
1416 received_msg_
= true;
1420 void PossiblyDone() {
1421 if (received_noarg_reply_
&& received_msg_
) {
1422 DCHECK(done_issued_
== false);
1423 done_issued_
= true;
1424 Send(new SyncChannelTestMsg_Done
);
1429 RestrictedDispatchDeadlockServer
* server_
;
1430 RestrictedDispatchDeadlockClient2
* peer_
;
1431 WaitableEvent
* server_ready_event_
;
1432 WaitableEvent
** events_
;
1434 bool received_noarg_reply_
;
1438 TEST_F(IPCSyncChannelTest
, RestrictedDispatchDeadlock
) {
1439 std::vector
<Worker
*> workers
;
1441 // A shared worker thread so that server1 and server2 run on one thread.
1442 base::Thread
worker_thread("RestrictedDispatchDeadlock");
1443 ASSERT_TRUE(worker_thread
.Start());
1445 WaitableEvent
server1_ready(false, false);
1446 WaitableEvent
server2_ready(false, false);
1448 WaitableEvent
event0(false, false);
1449 WaitableEvent
event1(false, false);
1450 WaitableEvent
event2(false, false);
1451 WaitableEvent
event3(false, false);
1452 WaitableEvent
* events
[4] = {&event0
, &event1
, &event2
, &event3
};
1454 RestrictedDispatchDeadlockServer
* server1
;
1455 RestrictedDispatchDeadlockServer
* server2
;
1456 RestrictedDispatchDeadlockClient1
* client1
;
1457 RestrictedDispatchDeadlockClient2
* client2
;
1459 server2
= new RestrictedDispatchDeadlockServer(2, &server2_ready
, events
,
1461 server2
->OverrideThread(&worker_thread
);
1462 workers
.push_back(server2
);
1464 client2
= new RestrictedDispatchDeadlockClient2(server2
, &server2_ready
,
1466 workers
.push_back(client2
);
1468 server1
= new RestrictedDispatchDeadlockServer(1, &server1_ready
, events
,
1470 server1
->OverrideThread(&worker_thread
);
1471 workers
.push_back(server1
);
1473 client1
= new RestrictedDispatchDeadlockClient1(server1
, client2
,
1474 &server1_ready
, events
);
1475 workers
.push_back(client1
);
1480 //------------------------------------------------------------------------------
1482 // This test case inspired by crbug.com/120530
1483 // We create 4 workers that pipe to each other W1->W2->W3->W4->W1 then we send a
1484 // message that recurses through 3, 4 or 5 steps to make sure, say, W1 can
1485 // re-enter when called from W4 while it's sending a message to W2.
1486 // The first worker drives the whole test so it must be treated specially.
1488 class RestrictedDispatchPipeWorker
: public Worker
{
1490 RestrictedDispatchPipeWorker(
1491 const std::string
&channel1
,
1492 WaitableEvent
* event1
,
1493 const std::string
&channel2
,
1494 WaitableEvent
* event2
,
1497 : Worker(channel1
, Channel::MODE_SERVER
),
1500 other_channel_name_(channel2
),
1505 void OnPingTTL(int ping
, int* ret
) {
1509 other_channel_
->Send(new SyncChannelTestMsg_PingTTL(ping
- 1, ret
));
1516 other_channel_
->Send(new SyncChannelTestMsg_Done
);
1517 other_channel_
.reset();
1521 void Run() override
{
1522 channel()->SetRestrictDispatchChannelGroup(group_
);
1526 other_channel_
= SyncChannel::Create(
1527 other_channel_name_
, IPC::Channel::MODE_CLIENT
, this,
1528 ipc_thread().task_runner().get(), true, shutdown_event(), nullptr);
1529 other_channel_
->SetRestrictDispatchChannelGroup(group_
);
1536 OnPingTTL(3, &value
);
1537 *success_
+= (value
== 3);
1538 OnPingTTL(4, &value
);
1539 *success_
+= (value
== 4);
1540 OnPingTTL(5, &value
);
1541 *success_
+= (value
== 5);
1542 other_channel_
->Send(new SyncChannelTestMsg_Done
);
1543 other_channel_
.reset();
1547 bool is_first() { return !!success_
; }
1550 bool OnMessageReceived(const Message
& message
) override
{
1551 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchPipeWorker
, message
)
1552 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_PingTTL
, OnPingTTL
)
1553 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Done
, OnDone
)
1554 IPC_END_MESSAGE_MAP()
1558 scoped_ptr
<SyncChannel
> other_channel_
;
1559 WaitableEvent
* event1_
;
1560 WaitableEvent
* event2_
;
1561 std::string other_channel_name_
;
1566 TEST_F(IPCSyncChannelTest
, RestrictedDispatch4WayDeadlock
) {
1568 std::vector
<Worker
*> workers
;
1569 WaitableEvent
event0(true, false);
1570 WaitableEvent
event1(true, false);
1571 WaitableEvent
event2(true, false);
1572 WaitableEvent
event3(true, false);
1573 workers
.push_back(new RestrictedDispatchPipeWorker(
1574 "channel0", &event0
, "channel1", &event1
, 1, &success
));
1575 workers
.push_back(new RestrictedDispatchPipeWorker(
1576 "channel1", &event1
, "channel2", &event2
, 2, NULL
));
1577 workers
.push_back(new RestrictedDispatchPipeWorker(
1578 "channel2", &event2
, "channel3", &event3
, 3, NULL
));
1579 workers
.push_back(new RestrictedDispatchPipeWorker(
1580 "channel3", &event3
, "channel0", &event0
, 4, NULL
));
1582 EXPECT_EQ(3, success
);
1585 //------------------------------------------------------------------------------
1587 // This test case inspired by crbug.com/122443
1588 // We want to make sure a reply message with the unblock flag set correctly
1589 // behaves as a reply, not a regular message.
1590 // We have 3 workers. Server1 will send a message to Server2 (which will block),
1591 // during which it will dispatch a message comming from Client, at which point
1592 // it will send another message to Server2. While sending that second message it
1593 // will receive a reply from Server1 with the unblock flag.
1595 class ReentrantReplyServer1
: public Worker
{
1597 ReentrantReplyServer1(WaitableEvent
* server_ready
)
1598 : Worker("reentrant_reply1", Channel::MODE_SERVER
),
1599 server_ready_(server_ready
) { }
1601 void Run() override
{
1602 server2_channel_
= SyncChannel::Create(
1603 "reentrant_reply2", IPC::Channel::MODE_CLIENT
, this,
1604 ipc_thread().task_runner().get(), true, shutdown_event(), nullptr);
1605 server_ready_
->Signal();
1606 Message
* msg
= new SyncChannelTestMsg_Reentrant1();
1607 server2_channel_
->Send(msg
);
1608 server2_channel_
.reset();
1613 bool OnMessageReceived(const Message
& message
) override
{
1614 IPC_BEGIN_MESSAGE_MAP(ReentrantReplyServer1
, message
)
1615 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Reentrant2
, OnReentrant2
)
1616 IPC_REPLY_HANDLER(OnReply
)
1617 IPC_END_MESSAGE_MAP()
1621 void OnReentrant2() {
1622 Message
* msg
= new SyncChannelTestMsg_Reentrant3();
1623 server2_channel_
->Send(msg
);
1626 void OnReply(const Message
& message
) {
1627 // If we get here, the Send() will never receive the reply (thus would
1628 // hang), so abort instead.
1629 LOG(FATAL
) << "Reply message was dispatched";
1632 WaitableEvent
* server_ready_
;
1633 scoped_ptr
<SyncChannel
> server2_channel_
;
1636 class ReentrantReplyServer2
: public Worker
{
1638 ReentrantReplyServer2()
1639 : Worker("reentrant_reply2", Channel::MODE_SERVER
),
1643 bool OnMessageReceived(const Message
& message
) override
{
1644 IPC_BEGIN_MESSAGE_MAP(ReentrantReplyServer2
, message
)
1645 IPC_MESSAGE_HANDLER_DELAY_REPLY(
1646 SyncChannelTestMsg_Reentrant1
, OnReentrant1
)
1647 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Reentrant3
, OnReentrant3
)
1648 IPC_END_MESSAGE_MAP()
1652 void OnReentrant1(Message
* reply
) {
1657 void OnReentrant3() {
1659 Message
* reply
= reply_
;
1661 reply
->set_unblock(true);
1669 class ReentrantReplyClient
: public Worker
{
1671 ReentrantReplyClient(WaitableEvent
* server_ready
)
1672 : Worker("reentrant_reply1", Channel::MODE_CLIENT
),
1673 server_ready_(server_ready
) { }
1675 void Run() override
{
1676 server_ready_
->Wait();
1677 Send(new SyncChannelTestMsg_Reentrant2());
1682 WaitableEvent
* server_ready_
;
1685 TEST_F(IPCSyncChannelTest
, ReentrantReply
) {
1686 std::vector
<Worker
*> workers
;
1687 WaitableEvent
server_ready(false, false);
1688 workers
.push_back(new ReentrantReplyServer2());
1689 workers
.push_back(new ReentrantReplyServer1(&server_ready
));
1690 workers
.push_back(new ReentrantReplyClient(&server_ready
));
1694 //------------------------------------------------------------------------------
1696 // Generate a validated channel ID using Channel::GenerateVerifiedChannelID().
1698 class VerifiedServer
: public Worker
{
1700 VerifiedServer(base::Thread
* listener_thread
,
1701 const std::string
& channel_name
,
1702 const std::string
& reply_text
)
1703 : Worker(channel_name
, Channel::MODE_SERVER
),
1704 reply_text_(reply_text
) {
1705 Worker::OverrideThread(listener_thread
);
1708 void OnNestedTestMsg(Message
* reply_msg
) override
{
1709 VLOG(1) << __FUNCTION__
<< " Sending reply: " << reply_text_
;
1710 SyncChannelNestedTestMsg_String::WriteReplyParams(reply_msg
, reply_text_
);
1712 ASSERT_EQ(channel()->GetPeerPID(), base::GetCurrentProcId());
1717 std::string reply_text_
;
1720 class VerifiedClient
: public Worker
{
1722 VerifiedClient(base::Thread
* listener_thread
,
1723 const std::string
& channel_name
,
1724 const std::string
& expected_text
)
1725 : Worker(channel_name
, Channel::MODE_CLIENT
),
1726 expected_text_(expected_text
) {
1727 Worker::OverrideThread(listener_thread
);
1730 void Run() override
{
1731 std::string response
;
1732 SyncMessage
* msg
= new SyncChannelNestedTestMsg_String(&response
);
1733 bool result
= Send(msg
);
1735 DCHECK_EQ(response
, expected_text_
);
1736 // expected_text_ is only used in the above DCHECK. This line suppresses the
1737 // "unused private field" warning in release builds.
1738 (void)expected_text_
;
1740 VLOG(1) << __FUNCTION__
<< " Received reply: " << response
;
1741 ASSERT_EQ(channel()->GetPeerPID(), base::GetCurrentProcId());
1746 std::string expected_text_
;
1750 std::vector
<Worker
*> workers
;
1752 // A shared worker thread for servers
1753 base::Thread
server_worker_thread("Verified_ServerListener");
1754 ASSERT_TRUE(server_worker_thread
.Start());
1756 base::Thread
client_worker_thread("Verified_ClientListener");
1757 ASSERT_TRUE(client_worker_thread
.Start());
1759 std::string channel_id
= Channel::GenerateVerifiedChannelID("Verified");
1762 worker
= new VerifiedServer(&server_worker_thread
,
1764 "Got first message");
1765 workers
.push_back(worker
);
1767 worker
= new VerifiedClient(&client_worker_thread
,
1769 "Got first message");
1770 workers
.push_back(worker
);
1775 // Windows needs to send an out-of-band secret to verify the client end of the
1776 // channel. Test that we still connect correctly in that case.
1777 TEST_F(IPCSyncChannelTest
, Verified
) {