blob: 2566f9babdb14d81d92a00cbb1a0b995b34225f2 [file] [log] [blame]
tfarina@chromium.orgb73eaee2010-06-07 11:10:18 +09001// Copyright (c) 2010 The Chromium Authors. All rights reserved.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4//
5// Unit test for SyncChannel.
6
7#include <string>
8#include <vector>
9
10#include "base/basictypes.h"
11#include "base/logging.h"
12#include "base/message_loop.h"
13#include "base/platform_thread.h"
14#include "base/stl_util-inl.h"
15#include "base/string_util.h"
timurrrr@chromium.orgf39c3ff2010-05-14 17:24:42 +090016#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090017#include "base/thread.h"
18#include "base/waitable_event.h"
19#include "ipc/ipc_message.h"
20#include "ipc/ipc_sync_channel.h"
jabdelmalek@google.comeb921652010-04-07 05:33:36 +090021#include "ipc/ipc_sync_message_filter.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090022#include "testing/gtest/include/gtest/gtest.h"
23
24
25#define MESSAGES_INTERNAL_FILE "ipc/ipc_sync_message_unittest.h"
26#include "ipc/ipc_message_macros.h"
27
28using namespace IPC;
29using base::WaitableEvent;
30
31namespace {
32
33// Base class for a "process" with listener and IPC threads.
34class Worker : public Channel::Listener, public Message::Sender {
35 public:
36 // Will create a channel without a name.
37 Worker(Channel::Mode mode, const std::string& thread_name)
38 : done_(new WaitableEvent(false, false)),
39 channel_created_(new WaitableEvent(false, false)),
40 mode_(mode),
41 ipc_thread_((thread_name + "_ipc").c_str()),
42 listener_thread_((thread_name + "_listener").c_str()),
43 overrided_thread_(NULL),
timurrrr@chromium.org03100a82009-10-27 20:28:58 +090044 shutdown_event_(true, false) {
45 // The data race on vfptr is real but is very hard
46 // to suppress using standard Valgrind mechanism (suppressions).
47 // We have to use ANNOTATE_BENIGN_RACE to hide the reports and
48 // make ThreadSanitizer bots green.
49 ANNOTATE_BENIGN_RACE(this, "Race on vfptr, http://crbug.com/25841");
50 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090051
52 // Will create a named channel and use this name for the threads' name.
53 Worker(const std::string& channel_name, Channel::Mode mode)
54 : done_(new WaitableEvent(false, false)),
55 channel_created_(new WaitableEvent(false, false)),
56 channel_name_(channel_name),
57 mode_(mode),
58 ipc_thread_((channel_name + "_ipc").c_str()),
59 listener_thread_((channel_name + "_listener").c_str()),
60 overrided_thread_(NULL),
timurrrr@chromium.org03100a82009-10-27 20:28:58 +090061 shutdown_event_(true, false) {
62 // The data race on vfptr is real but is very hard
63 // to suppress using standard Valgrind mechanism (suppressions).
64 // We have to use ANNOTATE_BENIGN_RACE to hide the reports and
65 // make ThreadSanitizer bots green.
66 ANNOTATE_BENIGN_RACE(this, "Race on vfptr, http://crbug.com/25841");
67 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090068
69 // The IPC thread needs to outlive SyncChannel, so force the correct order of
70 // destruction.
71 virtual ~Worker() {
72 WaitableEvent listener_done(false, false), ipc_done(false, false);
73 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
74 this, &Worker::OnListenerThreadShutdown1, &listener_done,
75 &ipc_done));
76 listener_done.Wait();
77 ipc_done.Wait();
78 ipc_thread_.Stop();
79 listener_thread_.Stop();
80 }
81 void AddRef() { }
82 void Release() { }
darin@chromium.org5cb996e2009-09-30 13:29:20 +090083 static bool ImplementsThreadSafeReferenceCounting() { return true; }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090084 bool Send(Message* msg) { return channel_->Send(msg); }
85 bool SendWithTimeout(Message* msg, int timeout_ms) {
86 return channel_->SendWithTimeout(msg, timeout_ms);
87 }
88 void WaitForChannelCreation() { channel_created_->Wait(); }
89 void CloseChannel() {
90 DCHECK(MessageLoop::current() == ListenerThread()->message_loop());
91 channel_->Close();
92 }
93 void Start() {
94 StartThread(&listener_thread_, MessageLoop::TYPE_DEFAULT);
95 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
96 this, &Worker::OnStart));
97 }
98 void OverrideThread(base::Thread* overrided_thread) {
99 DCHECK(overrided_thread_ == NULL);
100 overrided_thread_ = overrided_thread;
101 }
102 bool SendAnswerToLife(bool pump, int timeout, bool succeed) {
103 int answer = 0;
104 SyncMessage* msg = new SyncChannelTestMsg_AnswerToLife(&answer);
105 if (pump)
106 msg->EnableMessagePumping();
107 bool result = SendWithTimeout(msg, timeout);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900108 DCHECK_EQ(result, succeed);
109 DCHECK_EQ(answer, (succeed ? 42 : 0));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900110 return result;
111 }
112 bool SendDouble(bool pump, bool succeed) {
113 int answer = 0;
114 SyncMessage* msg = new SyncChannelTestMsg_Double(5, &answer);
115 if (pump)
116 msg->EnableMessagePumping();
117 bool result = Send(msg);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900118 DCHECK_EQ(result, succeed);
119 DCHECK_EQ(answer, (succeed ? 10 : 0));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900120 return result;
121 }
122 Channel::Mode mode() { return mode_; }
123 WaitableEvent* done_event() { return done_.get(); }
jabdelmalek@google.comeb921652010-04-07 05:33:36 +0900124 WaitableEvent* shutdown_event() { return &shutdown_event_; }
jam@chromium.orgebd07182009-12-01 11:34:18 +0900125 void ResetChannel() { channel_.reset(); }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900126 // Derived classes need to call this when they've completed their part of
127 // the test.
128 void Done() { done_->Signal(); }
jabdelmalek@google.comeb921652010-04-07 05:33:36 +0900129
130 protected:
131 IPC::SyncChannel* channel() { return channel_.get(); }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900132 // Functions for dervied classes to implement if they wish.
133 virtual void Run() { }
134 virtual void OnAnswer(int* answer) { NOTREACHED(); }
135 virtual void OnAnswerDelay(Message* reply_msg) {
136 // The message handler map below can only take one entry for
137 // SyncChannelTestMsg_AnswerToLife, so since some classes want
138 // the normal version while other want the delayed reply, we
139 // call the normal version if the derived class didn't override
140 // this function.
141 int answer;
142 OnAnswer(&answer);
143 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, answer);
144 Send(reply_msg);
145 }
146 virtual void OnDouble(int in, int* out) { NOTREACHED(); }
147 virtual void OnDoubleDelay(int in, Message* reply_msg) {
148 int result;
149 OnDouble(in, &result);
150 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, result);
151 Send(reply_msg);
152 }
153
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900154 virtual void OnNestedTestMsg(Message* reply_msg) {
155 NOTREACHED();
156 }
157
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900158 private:
159 base::Thread* ListenerThread() {
160 return overrided_thread_ ? overrided_thread_ : &listener_thread_;
161 }
162 // Called on the listener thread to create the sync channel.
163 void OnStart() {
164 // Link ipc_thread_, listener_thread_ and channel_ altogether.
165 StartThread(&ipc_thread_, MessageLoop::TYPE_IO);
166 channel_.reset(new SyncChannel(
167 channel_name_, mode_, this, NULL, ipc_thread_.message_loop(), true,
168 &shutdown_event_));
169 channel_created_->Signal();
170 Run();
171 }
172
173 void OnListenerThreadShutdown1(WaitableEvent* listener_event,
174 WaitableEvent* ipc_event) {
175 // SyncChannel needs to be destructed on the thread that it was created on.
176 channel_.reset();
177
178 MessageLoop::current()->RunAllPending();
179
180 ipc_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
181 this, &Worker::OnIPCThreadShutdown, listener_event, ipc_event));
182 }
183
184 void OnIPCThreadShutdown(WaitableEvent* listener_event,
185 WaitableEvent* ipc_event) {
186 MessageLoop::current()->RunAllPending();
187 ipc_event->Signal();
188
189 listener_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
190 this, &Worker::OnListenerThreadShutdown2, listener_event));
191 }
192
193 void OnListenerThreadShutdown2(WaitableEvent* listener_event) {
194 MessageLoop::current()->RunAllPending();
195 listener_event->Signal();
196 }
197
198 void OnMessageReceived(const Message& message) {
199 IPC_BEGIN_MESSAGE_MAP(Worker, message)
200 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_Double, OnDoubleDelay)
201 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_AnswerToLife,
202 OnAnswerDelay)
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900203 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelNestedTestMsg_String,
204 OnNestedTestMsg)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900205 IPC_END_MESSAGE_MAP()
206 }
207
208 void StartThread(base::Thread* thread, MessageLoop::Type type) {
209 base::Thread::Options options;
210 options.message_loop_type = type;
211 thread->StartWithOptions(options);
212 }
213
214 scoped_ptr<WaitableEvent> done_;
215 scoped_ptr<WaitableEvent> channel_created_;
216 std::string channel_name_;
217 Channel::Mode mode_;
218 scoped_ptr<SyncChannel> channel_;
219 base::Thread ipc_thread_;
220 base::Thread listener_thread_;
221 base::Thread* overrided_thread_;
222
223 base::WaitableEvent shutdown_event_;
224
tfarina@chromium.orgb73eaee2010-06-07 11:10:18 +0900225 DISALLOW_COPY_AND_ASSIGN(Worker);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900226};
227
228
229// Starts the test with the given workers. This function deletes the workers
230// when it's done.
231void RunTest(std::vector<Worker*> workers) {
232 // First we create the workers that are channel servers, or else the other
233 // workers' channel initialization might fail because the pipe isn't created..
234 for (size_t i = 0; i < workers.size(); ++i) {
235 if (workers[i]->mode() == Channel::MODE_SERVER) {
236 workers[i]->Start();
237 workers[i]->WaitForChannelCreation();
238 }
239 }
240
241 // now create the clients
242 for (size_t i = 0; i < workers.size(); ++i) {
243 if (workers[i]->mode() == Channel::MODE_CLIENT)
244 workers[i]->Start();
245 }
246
247 // wait for all the workers to finish
248 for (size_t i = 0; i < workers.size(); ++i)
249 workers[i]->done_event()->Wait();
250
251 STLDeleteContainerPointers(workers.begin(), workers.end());
252}
253
254} // namespace
255
256class IPCSyncChannelTest : public testing::Test {
257 private:
258 MessageLoop message_loop_;
259};
260
261//-----------------------------------------------------------------------------
262
263namespace {
264
265class SimpleServer : public Worker {
266 public:
267 SimpleServer(bool pump_during_send)
268 : Worker(Channel::MODE_SERVER, "simpler_server"),
269 pump_during_send_(pump_during_send) { }
270 void Run() {
271 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
272 Done();
273 }
274
275 bool pump_during_send_;
276};
277
278class SimpleClient : public Worker {
279 public:
280 SimpleClient() : Worker(Channel::MODE_CLIENT, "simple_client") { }
281
282 void OnAnswer(int* answer) {
283 *answer = 42;
284 Done();
285 }
286};
287
288void Simple(bool pump_during_send) {
289 std::vector<Worker*> workers;
290 workers.push_back(new SimpleServer(pump_during_send));
291 workers.push_back(new SimpleClient());
292 RunTest(workers);
293}
294
295} // namespace
296
297// Tests basic synchronous call
298TEST_F(IPCSyncChannelTest, Simple) {
299 Simple(false);
300 Simple(true);
301}
302
303//-----------------------------------------------------------------------------
304
305namespace {
306
307class DelayClient : public Worker {
308 public:
309 DelayClient() : Worker(Channel::MODE_CLIENT, "delay_client") { }
310
311 void OnAnswerDelay(Message* reply_msg) {
312 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
313 Send(reply_msg);
314 Done();
315 }
316};
317
318void DelayReply(bool pump_during_send) {
319 std::vector<Worker*> workers;
320 workers.push_back(new SimpleServer(pump_during_send));
321 workers.push_back(new DelayClient());
322 RunTest(workers);
323}
324
325} // namespace
326
327// Tests that asynchronous replies work
328TEST_F(IPCSyncChannelTest, DelayReply) {
329 DelayReply(false);
330 DelayReply(true);
331}
332
333//-----------------------------------------------------------------------------
334
335namespace {
336
337class NoHangServer : public Worker {
338 public:
339 explicit NoHangServer(WaitableEvent* got_first_reply, bool pump_during_send)
340 : Worker(Channel::MODE_SERVER, "no_hang_server"),
341 got_first_reply_(got_first_reply),
342 pump_during_send_(pump_during_send) { }
343 void Run() {
344 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
345 got_first_reply_->Signal();
346
347 SendAnswerToLife(pump_during_send_, base::kNoTimeout, false);
348 Done();
349 }
350
351 WaitableEvent* got_first_reply_;
352 bool pump_during_send_;
353};
354
355class NoHangClient : public Worker {
356 public:
357 explicit NoHangClient(WaitableEvent* got_first_reply)
358 : Worker(Channel::MODE_CLIENT, "no_hang_client"),
359 got_first_reply_(got_first_reply) { }
360
361 virtual void OnAnswerDelay(Message* reply_msg) {
362 // Use the DELAY_REPLY macro so that we can force the reply to be sent
363 // before this function returns (when the channel will be reset).
364 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
365 Send(reply_msg);
366 got_first_reply_->Wait();
367 CloseChannel();
368 Done();
369 }
370
371 WaitableEvent* got_first_reply_;
372};
373
374void NoHang(bool pump_during_send) {
375 WaitableEvent got_first_reply(false, false);
376 std::vector<Worker*> workers;
377 workers.push_back(new NoHangServer(&got_first_reply, pump_during_send));
378 workers.push_back(new NoHangClient(&got_first_reply));
379 RunTest(workers);
380}
381
382} // namespace
383
384// Tests that caller doesn't hang if receiver dies
385TEST_F(IPCSyncChannelTest, NoHang) {
386 NoHang(false);
387 NoHang(true);
388}
389
390//-----------------------------------------------------------------------------
391
392namespace {
393
394class UnblockServer : public Worker {
395 public:
jam@chromium.orgebd07182009-12-01 11:34:18 +0900396 UnblockServer(bool pump_during_send, bool delete_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900397 : Worker(Channel::MODE_SERVER, "unblock_server"),
jam@chromium.orgebd07182009-12-01 11:34:18 +0900398 pump_during_send_(pump_during_send),
399 delete_during_send_(delete_during_send) { }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900400 void Run() {
jam@chromium.orgebd07182009-12-01 11:34:18 +0900401 if (delete_during_send_) {
402 // Use custom code since race conditions mean the answer may or may not be
403 // available.
404 int answer = 0;
405 SyncMessage* msg = new SyncChannelTestMsg_AnswerToLife(&answer);
406 if (pump_during_send_)
407 msg->EnableMessagePumping();
408 Send(msg);
409 } else {
410 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
411 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900412 Done();
413 }
414
jam@chromium.orgebd07182009-12-01 11:34:18 +0900415 void OnDoubleDelay(int in, Message* reply_msg) {
416 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, in * 2);
417 Send(reply_msg);
418 if (delete_during_send_)
419 ResetChannel();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900420 }
421
422 bool pump_during_send_;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900423 bool delete_during_send_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900424};
425
426class UnblockClient : public Worker {
427 public:
428 UnblockClient(bool pump_during_send)
429 : Worker(Channel::MODE_CLIENT, "unblock_client"),
430 pump_during_send_(pump_during_send) { }
431
432 void OnAnswer(int* answer) {
433 SendDouble(pump_during_send_, true);
434 *answer = 42;
435 Done();
436 }
437
438 bool pump_during_send_;
439};
440
jam@chromium.orgebd07182009-12-01 11:34:18 +0900441void Unblock(bool server_pump, bool client_pump, bool delete_during_send) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900442 std::vector<Worker*> workers;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900443 workers.push_back(new UnblockServer(server_pump, delete_during_send));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900444 workers.push_back(new UnblockClient(client_pump));
445 RunTest(workers);
446}
447
448} // namespace
449
450// Tests that the caller unblocks to answer a sync message from the receiver.
451TEST_F(IPCSyncChannelTest, Unblock) {
jam@chromium.orgebd07182009-12-01 11:34:18 +0900452 Unblock(false, false, false);
453 Unblock(false, true, false);
454 Unblock(true, false, false);
455 Unblock(true, true, false);
456}
457
458//-----------------------------------------------------------------------------
459
460// Tests that the the IPC::SyncChannel object can be deleted during a Send.
461TEST_F(IPCSyncChannelTest, ChannelDeleteDuringSend) {
462 Unblock(false, false, true);
463 Unblock(false, true, true);
464 Unblock(true, false, true);
465 Unblock(true, true, true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900466}
467
468//-----------------------------------------------------------------------------
469
470namespace {
471
472class RecursiveServer : public Worker {
473 public:
474 explicit RecursiveServer(
475 bool expected_send_result, bool pump_first, bool pump_second)
476 : Worker(Channel::MODE_SERVER, "recursive_server"),
477 expected_send_result_(expected_send_result),
478 pump_first_(pump_first), pump_second_(pump_second) { }
479 void Run() {
480 SendDouble(pump_first_, expected_send_result_);
481 Done();
482 }
483
484 void OnDouble(int in, int* out) {
485 *out = in * 2;
486 SendAnswerToLife(pump_second_, base::kNoTimeout, expected_send_result_);
487 }
488
489 bool expected_send_result_, pump_first_, pump_second_;
490};
491
492class RecursiveClient : public Worker {
493 public:
494 explicit RecursiveClient(bool pump_during_send, bool close_channel)
495 : Worker(Channel::MODE_CLIENT, "recursive_client"),
496 pump_during_send_(pump_during_send), close_channel_(close_channel) { }
497
498 void OnDoubleDelay(int in, Message* reply_msg) {
499 SendDouble(pump_during_send_, !close_channel_);
500 if (close_channel_) {
501 delete reply_msg;
502 } else {
503 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, in * 2);
504 Send(reply_msg);
505 }
506 Done();
507 }
508
509 void OnAnswerDelay(Message* reply_msg) {
510 if (close_channel_) {
511 delete reply_msg;
512 CloseChannel();
513 } else {
514 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
515 Send(reply_msg);
516 }
517 }
518
519 bool pump_during_send_, close_channel_;
520};
521
522void Recursive(
523 bool server_pump_first, bool server_pump_second, bool client_pump) {
524 std::vector<Worker*> workers;
525 workers.push_back(
526 new RecursiveServer(true, server_pump_first, server_pump_second));
527 workers.push_back(new RecursiveClient(client_pump, false));
528 RunTest(workers);
529}
530
531} // namespace
532
533// Tests a server calling Send while another Send is pending.
534TEST_F(IPCSyncChannelTest, Recursive) {
535 Recursive(false, false, false);
536 Recursive(false, false, true);
537 Recursive(false, true, false);
538 Recursive(false, true, true);
539 Recursive(true, false, false);
540 Recursive(true, false, true);
541 Recursive(true, true, false);
542 Recursive(true, true, true);
543}
544
545//-----------------------------------------------------------------------------
546
547namespace {
548
549void RecursiveNoHang(
550 bool server_pump_first, bool server_pump_second, bool client_pump) {
551 std::vector<Worker*> workers;
552 workers.push_back(
553 new RecursiveServer(false, server_pump_first, server_pump_second));
554 workers.push_back(new RecursiveClient(client_pump, true));
555 RunTest(workers);
556}
557
558} // namespace
559
560// Tests that if a caller makes a sync call during an existing sync call and
561// the receiver dies, neither of the Send() calls hang.
562TEST_F(IPCSyncChannelTest, RecursiveNoHang) {
563 RecursiveNoHang(false, false, false);
564 RecursiveNoHang(false, false, true);
565 RecursiveNoHang(false, true, false);
566 RecursiveNoHang(false, true, true);
567 RecursiveNoHang(true, false, false);
568 RecursiveNoHang(true, false, true);
569 RecursiveNoHang(true, true, false);
570 RecursiveNoHang(true, true, true);
571}
572
573//-----------------------------------------------------------------------------
574
575namespace {
576
577class MultipleServer1 : public Worker {
578 public:
579 MultipleServer1(bool pump_during_send)
580 : Worker("test_channel1", Channel::MODE_SERVER),
581 pump_during_send_(pump_during_send) { }
582
583 void Run() {
584 SendDouble(pump_during_send_, true);
585 Done();
586 }
587
588 bool pump_during_send_;
589};
590
591class MultipleClient1 : public Worker {
592 public:
593 MultipleClient1(WaitableEvent* client1_msg_received,
594 WaitableEvent* client1_can_reply) :
595 Worker("test_channel1", Channel::MODE_CLIENT),
596 client1_msg_received_(client1_msg_received),
597 client1_can_reply_(client1_can_reply) { }
598
599 void OnDouble(int in, int* out) {
600 client1_msg_received_->Signal();
601 *out = in * 2;
602 client1_can_reply_->Wait();
603 Done();
604 }
605
606 private:
607 WaitableEvent *client1_msg_received_, *client1_can_reply_;
608};
609
610class MultipleServer2 : public Worker {
611 public:
612 MultipleServer2() : Worker("test_channel2", Channel::MODE_SERVER) { }
613
614 void OnAnswer(int* result) {
615 *result = 42;
616 Done();
617 }
618};
619
620class MultipleClient2 : public Worker {
621 public:
622 MultipleClient2(
623 WaitableEvent* client1_msg_received, WaitableEvent* client1_can_reply,
624 bool pump_during_send)
625 : Worker("test_channel2", Channel::MODE_CLIENT),
626 client1_msg_received_(client1_msg_received),
627 client1_can_reply_(client1_can_reply),
628 pump_during_send_(pump_during_send) { }
629
630 void Run() {
631 client1_msg_received_->Wait();
632 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
633 client1_can_reply_->Signal();
634 Done();
635 }
636
637 private:
638 WaitableEvent *client1_msg_received_, *client1_can_reply_;
639 bool pump_during_send_;
640};
641
642void Multiple(bool server_pump, bool client_pump) {
643 std::vector<Worker*> workers;
644
645 // A shared worker thread so that server1 and server2 run on one thread.
646 base::Thread worker_thread("Multiple");
647 ASSERT_TRUE(worker_thread.Start());
648
649 // Server1 sends a sync msg to client1, which blocks the reply until
650 // server2 (which runs on the same worker thread as server1) responds
651 // to a sync msg from client2.
652 WaitableEvent client1_msg_received(false, false);
653 WaitableEvent client1_can_reply(false, false);
654
655 Worker* worker;
656
657 worker = new MultipleServer2();
658 worker->OverrideThread(&worker_thread);
659 workers.push_back(worker);
660
661 worker = new MultipleClient2(
662 &client1_msg_received, &client1_can_reply, client_pump);
663 workers.push_back(worker);
664
665 worker = new MultipleServer1(server_pump);
666 worker->OverrideThread(&worker_thread);
667 workers.push_back(worker);
668
669 worker = new MultipleClient1(
670 &client1_msg_received, &client1_can_reply);
671 workers.push_back(worker);
672
673 RunTest(workers);
674}
675
676} // namespace
677
678// Tests that multiple SyncObjects on the same listener thread can unblock each
679// other.
680TEST_F(IPCSyncChannelTest, Multiple) {
681 Multiple(false, false);
682 Multiple(false, true);
683 Multiple(true, false);
684 Multiple(true, true);
685}
686
687//-----------------------------------------------------------------------------
688
689namespace {
690
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900691// This class provides server side functionality to test the case where
692// multiple sync channels are in use on the same thread on the client and
693// nested calls are issued.
694class QueuedReplyServer : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900695 public:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900696 QueuedReplyServer(base::Thread* listener_thread,
697 const std::string& channel_name,
698 const std::string& reply_text)
699 : Worker(channel_name, Channel::MODE_SERVER),
700 reply_text_(reply_text) {
701 Worker::OverrideThread(listener_thread);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900702 }
703
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900704 virtual void OnNestedTestMsg(Message* reply_msg) {
705 LOG(INFO) << __FUNCTION__ << " Sending reply: "
706 << reply_text_.c_str();
707 SyncChannelNestedTestMsg_String::WriteReplyParams(
708 reply_msg, reply_text_);
709 Send(reply_msg);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900710 Done();
711 }
712
713 private:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900714 std::string reply_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900715};
716
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900717// The QueuedReplyClient class provides functionality to test the case where
718// multiple sync channels are in use on the same thread and they make nested
719// sync calls, i.e. while the first channel waits for a response it makes a
720// sync call on another channel.
721// The callstack should unwind correctly, i.e. the outermost call should
722// complete first, and so on.
723class QueuedReplyClient : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900724 public:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900725 QueuedReplyClient(base::Thread* listener_thread,
726 const std::string& channel_name,
727 const std::string& expected_text,
728 bool pump_during_send)
729 : Worker(channel_name, Channel::MODE_CLIENT),
730 expected_text_(expected_text),
731 pump_during_send_(pump_during_send) {
732 Worker::OverrideThread(listener_thread);
733 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900734
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900735 virtual void Run() {
736 std::string response;
737 SyncMessage* msg = new SyncChannelNestedTestMsg_String(&response);
738 if (pump_during_send_)
739 msg->EnableMessagePumping();
740 bool result = Send(msg);
741 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900742 DCHECK_EQ(response, expected_text_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900743
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900744 LOG(INFO) << __FUNCTION__ << " Received reply: "
745 << response.c_str();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900746 Done();
747 }
748
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900749 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900750 bool pump_during_send_;
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900751 std::string expected_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900752};
753
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900754void QueuedReply(bool client_pump) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900755 std::vector<Worker*> workers;
756
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900757 // A shared worker thread for servers
758 base::Thread server_worker_thread("QueuedReply_ServerListener");
759 ASSERT_TRUE(server_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900760
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900761 base::Thread client_worker_thread("QueuedReply_ClientListener");
762 ASSERT_TRUE(client_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900763
764 Worker* worker;
765
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900766 worker = new QueuedReplyServer(&server_worker_thread,
767 "QueuedReply_Server1",
768 "Got first message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900769 workers.push_back(worker);
770
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900771 worker = new QueuedReplyServer(&server_worker_thread,
772 "QueuedReply_Server2",
773 "Got second message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900774 workers.push_back(worker);
775
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900776 worker = new QueuedReplyClient(&client_worker_thread,
777 "QueuedReply_Server1",
778 "Got first message",
779 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900780 workers.push_back(worker);
781
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900782 worker = new QueuedReplyClient(&client_worker_thread,
783 "QueuedReply_Server2",
784 "Got second message",
785 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900786 workers.push_back(worker);
787
788 RunTest(workers);
789}
790
791} // namespace
792
793// While a blocking send is in progress, the listener thread might answer other
794// synchronous messages. This tests that if during the response to another
795// message the reply to the original messages comes, it is queued up correctly
796// and the original Send is unblocked later.
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900797// We also test that the send call stacks unwind correctly when the channel
798// pumps messages while waiting for a response.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900799TEST_F(IPCSyncChannelTest, QueuedReply) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900800 QueuedReply(false);
801 QueuedReply(true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900802}
803
804//-----------------------------------------------------------------------------
805
806namespace {
807
808class BadServer : public Worker {
809 public:
810 BadServer(bool pump_during_send)
811 : Worker(Channel::MODE_SERVER, "simpler_server"),
812 pump_during_send_(pump_during_send) { }
813 void Run() {
814 int answer = 0;
815
816 SyncMessage* msg = new SyncMessage(
817 MSG_ROUTING_CONTROL, SyncChannelTestMsg_Double::ID,
818 Message::PRIORITY_NORMAL, NULL);
819 if (pump_during_send_)
820 msg->EnableMessagePumping();
821
822 // Temporarily set the minimum logging very high so that the assertion
823 // in ipc_message_utils doesn't fire.
824 int log_level = logging::GetMinLogLevel();
825 logging::SetMinLogLevel(kint32max);
826 bool result = Send(msg);
827 logging::SetMinLogLevel(log_level);
828 DCHECK(!result);
829
830 // Need to send another message to get the client to call Done().
831 result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
832 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900833 DCHECK_EQ(answer, 42);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900834
835 Done();
836 }
837
838 bool pump_during_send_;
839};
840
841void BadMessage(bool pump_during_send) {
842 std::vector<Worker*> workers;
843 workers.push_back(new BadServer(pump_during_send));
844 workers.push_back(new SimpleClient());
845 RunTest(workers);
846}
847
848} // namespace
849
850// Tests that if a message is not serialized correctly, the Send() will fail.
851TEST_F(IPCSyncChannelTest, BadMessage) {
852 BadMessage(false);
853 BadMessage(true);
854}
855
856//-----------------------------------------------------------------------------
857
858namespace {
859
860class ChattyClient : public Worker {
861 public:
862 ChattyClient() :
863 Worker(Channel::MODE_CLIENT, "chatty_client") { }
864
865 void OnAnswer(int* answer) {
866 // The PostMessage limit is 10k. Send 20% more than that.
867 const int kMessageLimit = 10000;
868 const int kMessagesToSend = kMessageLimit * 120 / 100;
869 for (int i = 0; i < kMessagesToSend; ++i) {
870 if (!SendDouble(false, true))
871 break;
872 }
873 *answer = 42;
874 Done();
875 }
876};
877
878void ChattyServer(bool pump_during_send) {
879 std::vector<Worker*> workers;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900880 workers.push_back(new UnblockServer(pump_during_send, false));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900881 workers.push_back(new ChattyClient());
882 RunTest(workers);
883}
884
885} // namespace
886
887// Tests http://b/1093251 - that sending lots of sync messages while
888// the receiver is waiting for a sync reply does not overflow the PostMessage
889// queue.
890TEST_F(IPCSyncChannelTest, ChattyServer) {
891 ChattyServer(false);
892 ChattyServer(true);
893}
894
895//------------------------------------------------------------------------------
896
897namespace {
898
899class TimeoutServer : public Worker {
900 public:
901 TimeoutServer(int timeout_ms,
902 std::vector<bool> timeout_seq,
903 bool pump_during_send)
904 : Worker(Channel::MODE_SERVER, "timeout_server"),
905 timeout_ms_(timeout_ms),
906 timeout_seq_(timeout_seq),
907 pump_during_send_(pump_during_send) {
908 }
909
910 void Run() {
911 for (std::vector<bool>::const_iterator iter = timeout_seq_.begin();
912 iter != timeout_seq_.end(); ++iter) {
913 SendAnswerToLife(pump_during_send_, timeout_ms_, !*iter);
914 }
915 Done();
916 }
917
918 private:
919 int timeout_ms_;
920 std::vector<bool> timeout_seq_;
921 bool pump_during_send_;
922};
923
924class UnresponsiveClient : public Worker {
925 public:
926 UnresponsiveClient(std::vector<bool> timeout_seq)
927 : Worker(Channel::MODE_CLIENT, "unresponsive_client"),
928 timeout_seq_(timeout_seq) {
929 }
930
931 void OnAnswerDelay(Message* reply_msg) {
932 DCHECK(!timeout_seq_.empty());
933 if (!timeout_seq_[0]) {
934 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
935 Send(reply_msg);
936 } else {
937 // Don't reply.
938 delete reply_msg;
939 }
940 timeout_seq_.erase(timeout_seq_.begin());
941 if (timeout_seq_.empty())
942 Done();
943 }
944
945 private:
946 // Whether we should time-out or respond to the various messages we receive.
947 std::vector<bool> timeout_seq_;
948};
949
950void SendWithTimeoutOK(bool pump_during_send) {
951 std::vector<Worker*> workers;
952 std::vector<bool> timeout_seq;
953 timeout_seq.push_back(false);
954 timeout_seq.push_back(false);
955 timeout_seq.push_back(false);
956 workers.push_back(new TimeoutServer(5000, timeout_seq, pump_during_send));
957 workers.push_back(new SimpleClient());
958 RunTest(workers);
959}
960
961void SendWithTimeoutTimeout(bool pump_during_send) {
962 std::vector<Worker*> workers;
963 std::vector<bool> timeout_seq;
964 timeout_seq.push_back(true);
965 timeout_seq.push_back(false);
966 timeout_seq.push_back(false);
967 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
968 workers.push_back(new UnresponsiveClient(timeout_seq));
969 RunTest(workers);
970}
971
972void SendWithTimeoutMixedOKAndTimeout(bool pump_during_send) {
973 std::vector<Worker*> workers;
974 std::vector<bool> timeout_seq;
975 timeout_seq.push_back(true);
976 timeout_seq.push_back(false);
977 timeout_seq.push_back(false);
978 timeout_seq.push_back(true);
979 timeout_seq.push_back(false);
980 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
981 workers.push_back(new UnresponsiveClient(timeout_seq));
982 RunTest(workers);
983}
984
985} // namespace
986
987// Tests that SendWithTimeout does not time-out if the response comes back fast
988// enough.
989TEST_F(IPCSyncChannelTest, SendWithTimeoutOK) {
990 SendWithTimeoutOK(false);
991 SendWithTimeoutOK(true);
992}
993
994// Tests that SendWithTimeout does time-out.
995TEST_F(IPCSyncChannelTest, SendWithTimeoutTimeout) {
996 SendWithTimeoutTimeout(false);
997 SendWithTimeoutTimeout(true);
998}
999
1000// Sends some message that time-out and some that succeed.
1001TEST_F(IPCSyncChannelTest, SendWithTimeoutMixedOKAndTimeout) {
1002 SendWithTimeoutMixedOKAndTimeout(false);
1003 SendWithTimeoutMixedOKAndTimeout(true);
1004}
1005
1006//------------------------------------------------------------------------------
1007
1008namespace {
1009
1010class NestedTask : public Task {
1011 public:
1012 NestedTask(Worker* server) : server_(server) { }
1013 void Run() {
1014 // Sleep a bit so that we wake up after the reply has been received.
1015 PlatformThread::Sleep(250);
1016 server_->SendAnswerToLife(true, base::kNoTimeout, true);
1017 }
1018
1019 Worker* server_;
1020};
1021
1022static bool timeout_occured = false;
1023
1024class TimeoutTask : public Task {
1025 public:
1026 void Run() {
1027 timeout_occured = true;
1028 }
1029};
1030
1031class DoneEventRaceServer : public Worker {
1032 public:
1033 DoneEventRaceServer()
1034 : Worker(Channel::MODE_SERVER, "done_event_race_server") { }
1035
1036 void Run() {
1037 MessageLoop::current()->PostTask(FROM_HERE, new NestedTask(this));
1038 MessageLoop::current()->PostDelayedTask(FROM_HERE, new TimeoutTask(), 9000);
1039 // Even though we have a timeout on the Send, it will succeed since for this
1040 // bug, the reply message comes back and is deserialized, however the done
1041 // event wasn't set. So we indirectly use the timeout task to notice if a
1042 // timeout occurred.
1043 SendAnswerToLife(true, 10000, true);
1044 DCHECK(!timeout_occured);
1045 Done();
1046 }
1047};
1048
1049} // namespace
1050
1051// Tests http://b/1474092 - that if after the done_event is set but before
1052// OnObjectSignaled is called another message is sent out, then after its
1053// reply comes back OnObjectSignaled will be called for the first message.
1054TEST_F(IPCSyncChannelTest, DoneEventRace) {
1055 std::vector<Worker*> workers;
1056 workers.push_back(new DoneEventRaceServer());
1057 workers.push_back(new SimpleClient());
1058 RunTest(workers);
1059}
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001060
1061//-----------------------------------------------------------------------------
1062
1063namespace {
1064
1065class TestSyncMessageFilter : public IPC::SyncMessageFilter {
1066 public:
1067 TestSyncMessageFilter(base::WaitableEvent* shutdown_event, Worker* worker)
1068 : SyncMessageFilter(shutdown_event),
1069 worker_(worker),
1070 thread_("helper_thread") {
1071 base::Thread::Options options;
1072 options.message_loop_type = MessageLoop::TYPE_DEFAULT;
1073 thread_.StartWithOptions(options);
1074 }
1075
1076 virtual void OnFilterAdded(Channel* channel) {
1077 SyncMessageFilter::OnFilterAdded(channel);
1078 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
1079 this, &TestSyncMessageFilter::SendMessageOnHelperThread));
1080 }
1081
1082 void SendMessageOnHelperThread() {
1083 int answer = 0;
1084 bool result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
1085 DCHECK(result);
1086 DCHECK_EQ(answer, 42);
1087
1088 worker_->Done();
1089 }
1090
1091 Worker* worker_;
1092 base::Thread thread_;
1093};
1094
1095class SyncMessageFilterServer : public Worker {
1096 public:
1097 SyncMessageFilterServer()
1098 : Worker(Channel::MODE_SERVER, "sync_message_filter_server") {
1099 filter_ = new TestSyncMessageFilter(shutdown_event(), this);
1100 }
1101
1102 void Run() {
1103 channel()->AddFilter(filter_.get());
1104 }
1105
1106 scoped_refptr<TestSyncMessageFilter> filter_;
1107};
1108
1109} // namespace
1110
1111// Tests basic synchronous call
1112TEST_F(IPCSyncChannelTest, SyncMessageFilter) {
1113 std::vector<Worker*> workers;
1114 workers.push_back(new SyncMessageFilterServer());
1115 workers.push_back(new SimpleClient());
1116 RunTest(workers);
1117}