blob: 32190008e4ae6aadb1727d41e9cde914d02e37b3 [file] [log] [blame]
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4//
5// 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"
16#include "base/thread.h"
17#include "base/waitable_event.h"
18#include "ipc/ipc_message.h"
19#include "ipc/ipc_sync_channel.h"
20#include "testing/gtest/include/gtest/gtest.h"
21
22
23#define MESSAGES_INTERNAL_FILE "ipc/ipc_sync_message_unittest.h"
24#include "ipc/ipc_message_macros.h"
25
26using namespace IPC;
27using base::WaitableEvent;
28
29namespace {
30
31// Base class for a "process" with listener and IPC threads.
32class Worker : public Channel::Listener, public Message::Sender {
33 public:
34 // Will create a channel without a name.
35 Worker(Channel::Mode mode, const std::string& thread_name)
36 : done_(new WaitableEvent(false, false)),
37 channel_created_(new WaitableEvent(false, false)),
38 mode_(mode),
39 ipc_thread_((thread_name + "_ipc").c_str()),
40 listener_thread_((thread_name + "_listener").c_str()),
41 overrided_thread_(NULL),
42 shutdown_event_(true, false) { }
43
44 // Will create a named channel and use this name for the threads' name.
45 Worker(const std::string& channel_name, Channel::Mode mode)
46 : done_(new WaitableEvent(false, false)),
47 channel_created_(new WaitableEvent(false, false)),
48 channel_name_(channel_name),
49 mode_(mode),
50 ipc_thread_((channel_name + "_ipc").c_str()),
51 listener_thread_((channel_name + "_listener").c_str()),
52 overrided_thread_(NULL),
53 shutdown_event_(true, false) { }
54
55 // The IPC thread needs to outlive SyncChannel, so force the correct order of
56 // destruction.
57 virtual ~Worker() {
58 WaitableEvent listener_done(false, false), ipc_done(false, false);
59 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
60 this, &Worker::OnListenerThreadShutdown1, &listener_done,
61 &ipc_done));
62 listener_done.Wait();
63 ipc_done.Wait();
64 ipc_thread_.Stop();
65 listener_thread_.Stop();
66 }
67 void AddRef() { }
68 void Release() { }
darin@chromium.org5cb996e2009-09-30 13:29:20 +090069 static bool ImplementsThreadSafeReferenceCounting() { return true; }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090070 bool Send(Message* msg) { return channel_->Send(msg); }
71 bool SendWithTimeout(Message* msg, int timeout_ms) {
72 return channel_->SendWithTimeout(msg, timeout_ms);
73 }
74 void WaitForChannelCreation() { channel_created_->Wait(); }
75 void CloseChannel() {
76 DCHECK(MessageLoop::current() == ListenerThread()->message_loop());
77 channel_->Close();
78 }
79 void Start() {
80 StartThread(&listener_thread_, MessageLoop::TYPE_DEFAULT);
81 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
82 this, &Worker::OnStart));
83 }
84 void OverrideThread(base::Thread* overrided_thread) {
85 DCHECK(overrided_thread_ == NULL);
86 overrided_thread_ = overrided_thread;
87 }
88 bool SendAnswerToLife(bool pump, int timeout, bool succeed) {
89 int answer = 0;
90 SyncMessage* msg = new SyncChannelTestMsg_AnswerToLife(&answer);
91 if (pump)
92 msg->EnableMessagePumping();
93 bool result = SendWithTimeout(msg, timeout);
94 DCHECK(result == succeed);
95 DCHECK(answer == (succeed ? 42 : 0));
96 return result;
97 }
98 bool SendDouble(bool pump, bool succeed) {
99 int answer = 0;
100 SyncMessage* msg = new SyncChannelTestMsg_Double(5, &answer);
101 if (pump)
102 msg->EnableMessagePumping();
103 bool result = Send(msg);
104 DCHECK(result == succeed);
105 DCHECK(answer == (succeed ? 10 : 0));
106 return result;
107 }
108 Channel::Mode mode() { return mode_; }
109 WaitableEvent* done_event() { return done_.get(); }
110
111 protected:
112 // Derived classes need to call this when they've completed their part of
113 // the test.
114 void Done() { done_->Signal(); }
115 // Functions for dervied classes to implement if they wish.
116 virtual void Run() { }
117 virtual void OnAnswer(int* answer) { NOTREACHED(); }
118 virtual void OnAnswerDelay(Message* reply_msg) {
119 // The message handler map below can only take one entry for
120 // SyncChannelTestMsg_AnswerToLife, so since some classes want
121 // the normal version while other want the delayed reply, we
122 // call the normal version if the derived class didn't override
123 // this function.
124 int answer;
125 OnAnswer(&answer);
126 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, answer);
127 Send(reply_msg);
128 }
129 virtual void OnDouble(int in, int* out) { NOTREACHED(); }
130 virtual void OnDoubleDelay(int in, Message* reply_msg) {
131 int result;
132 OnDouble(in, &result);
133 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, result);
134 Send(reply_msg);
135 }
136
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900137 virtual void OnNestedTestMsg(Message* reply_msg) {
138 NOTREACHED();
139 }
140
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900141 private:
142 base::Thread* ListenerThread() {
143 return overrided_thread_ ? overrided_thread_ : &listener_thread_;
144 }
145 // Called on the listener thread to create the sync channel.
146 void OnStart() {
147 // Link ipc_thread_, listener_thread_ and channel_ altogether.
148 StartThread(&ipc_thread_, MessageLoop::TYPE_IO);
149 channel_.reset(new SyncChannel(
150 channel_name_, mode_, this, NULL, ipc_thread_.message_loop(), true,
151 &shutdown_event_));
152 channel_created_->Signal();
153 Run();
154 }
155
156 void OnListenerThreadShutdown1(WaitableEvent* listener_event,
157 WaitableEvent* ipc_event) {
158 // SyncChannel needs to be destructed on the thread that it was created on.
159 channel_.reset();
160
161 MessageLoop::current()->RunAllPending();
162
163 ipc_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
164 this, &Worker::OnIPCThreadShutdown, listener_event, ipc_event));
165 }
166
167 void OnIPCThreadShutdown(WaitableEvent* listener_event,
168 WaitableEvent* ipc_event) {
169 MessageLoop::current()->RunAllPending();
170 ipc_event->Signal();
171
172 listener_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
173 this, &Worker::OnListenerThreadShutdown2, listener_event));
174 }
175
176 void OnListenerThreadShutdown2(WaitableEvent* listener_event) {
177 MessageLoop::current()->RunAllPending();
178 listener_event->Signal();
179 }
180
181 void OnMessageReceived(const Message& message) {
182 IPC_BEGIN_MESSAGE_MAP(Worker, message)
183 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_Double, OnDoubleDelay)
184 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_AnswerToLife,
185 OnAnswerDelay)
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900186 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelNestedTestMsg_String,
187 OnNestedTestMsg)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900188 IPC_END_MESSAGE_MAP()
189 }
190
191 void StartThread(base::Thread* thread, MessageLoop::Type type) {
192 base::Thread::Options options;
193 options.message_loop_type = type;
194 thread->StartWithOptions(options);
195 }
196
197 scoped_ptr<WaitableEvent> done_;
198 scoped_ptr<WaitableEvent> channel_created_;
199 std::string channel_name_;
200 Channel::Mode mode_;
201 scoped_ptr<SyncChannel> channel_;
202 base::Thread ipc_thread_;
203 base::Thread listener_thread_;
204 base::Thread* overrided_thread_;
205
206 base::WaitableEvent shutdown_event_;
207
208 DISALLOW_EVIL_CONSTRUCTORS(Worker);
209};
210
211
212// Starts the test with the given workers. This function deletes the workers
213// when it's done.
214void RunTest(std::vector<Worker*> workers) {
215 // First we create the workers that are channel servers, or else the other
216 // workers' channel initialization might fail because the pipe isn't created..
217 for (size_t i = 0; i < workers.size(); ++i) {
218 if (workers[i]->mode() == Channel::MODE_SERVER) {
219 workers[i]->Start();
220 workers[i]->WaitForChannelCreation();
221 }
222 }
223
224 // now create the clients
225 for (size_t i = 0; i < workers.size(); ++i) {
226 if (workers[i]->mode() == Channel::MODE_CLIENT)
227 workers[i]->Start();
228 }
229
230 // wait for all the workers to finish
231 for (size_t i = 0; i < workers.size(); ++i)
232 workers[i]->done_event()->Wait();
233
234 STLDeleteContainerPointers(workers.begin(), workers.end());
235}
236
237} // namespace
238
239class IPCSyncChannelTest : public testing::Test {
240 private:
241 MessageLoop message_loop_;
242};
243
244//-----------------------------------------------------------------------------
245
246namespace {
247
248class SimpleServer : public Worker {
249 public:
250 SimpleServer(bool pump_during_send)
251 : Worker(Channel::MODE_SERVER, "simpler_server"),
252 pump_during_send_(pump_during_send) { }
253 void Run() {
254 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
255 Done();
256 }
257
258 bool pump_during_send_;
259};
260
261class SimpleClient : public Worker {
262 public:
263 SimpleClient() : Worker(Channel::MODE_CLIENT, "simple_client") { }
264
265 void OnAnswer(int* answer) {
266 *answer = 42;
267 Done();
268 }
269};
270
271void Simple(bool pump_during_send) {
272 std::vector<Worker*> workers;
273 workers.push_back(new SimpleServer(pump_during_send));
274 workers.push_back(new SimpleClient());
275 RunTest(workers);
276}
277
278} // namespace
279
280// Tests basic synchronous call
281TEST_F(IPCSyncChannelTest, Simple) {
282 Simple(false);
283 Simple(true);
284}
285
286//-----------------------------------------------------------------------------
287
288namespace {
289
290class DelayClient : public Worker {
291 public:
292 DelayClient() : Worker(Channel::MODE_CLIENT, "delay_client") { }
293
294 void OnAnswerDelay(Message* reply_msg) {
295 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
296 Send(reply_msg);
297 Done();
298 }
299};
300
301void DelayReply(bool pump_during_send) {
302 std::vector<Worker*> workers;
303 workers.push_back(new SimpleServer(pump_during_send));
304 workers.push_back(new DelayClient());
305 RunTest(workers);
306}
307
308} // namespace
309
310// Tests that asynchronous replies work
311TEST_F(IPCSyncChannelTest, DelayReply) {
312 DelayReply(false);
313 DelayReply(true);
314}
315
316//-----------------------------------------------------------------------------
317
318namespace {
319
320class NoHangServer : public Worker {
321 public:
322 explicit NoHangServer(WaitableEvent* got_first_reply, bool pump_during_send)
323 : Worker(Channel::MODE_SERVER, "no_hang_server"),
324 got_first_reply_(got_first_reply),
325 pump_during_send_(pump_during_send) { }
326 void Run() {
327 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
328 got_first_reply_->Signal();
329
330 SendAnswerToLife(pump_during_send_, base::kNoTimeout, false);
331 Done();
332 }
333
334 WaitableEvent* got_first_reply_;
335 bool pump_during_send_;
336};
337
338class NoHangClient : public Worker {
339 public:
340 explicit NoHangClient(WaitableEvent* got_first_reply)
341 : Worker(Channel::MODE_CLIENT, "no_hang_client"),
342 got_first_reply_(got_first_reply) { }
343
344 virtual void OnAnswerDelay(Message* reply_msg) {
345 // Use the DELAY_REPLY macro so that we can force the reply to be sent
346 // before this function returns (when the channel will be reset).
347 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
348 Send(reply_msg);
349 got_first_reply_->Wait();
350 CloseChannel();
351 Done();
352 }
353
354 WaitableEvent* got_first_reply_;
355};
356
357void NoHang(bool pump_during_send) {
358 WaitableEvent got_first_reply(false, false);
359 std::vector<Worker*> workers;
360 workers.push_back(new NoHangServer(&got_first_reply, pump_during_send));
361 workers.push_back(new NoHangClient(&got_first_reply));
362 RunTest(workers);
363}
364
365} // namespace
366
367// Tests that caller doesn't hang if receiver dies
368TEST_F(IPCSyncChannelTest, NoHang) {
369 NoHang(false);
370 NoHang(true);
371}
372
373//-----------------------------------------------------------------------------
374
375namespace {
376
377class UnblockServer : public Worker {
378 public:
379 UnblockServer(bool pump_during_send)
380 : Worker(Channel::MODE_SERVER, "unblock_server"),
381 pump_during_send_(pump_during_send) { }
382 void Run() {
383 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
384 Done();
385 }
386
387 void OnDouble(int in, int* out) {
388 *out = in * 2;
389 }
390
391 bool pump_during_send_;
392};
393
394class UnblockClient : public Worker {
395 public:
396 UnblockClient(bool pump_during_send)
397 : Worker(Channel::MODE_CLIENT, "unblock_client"),
398 pump_during_send_(pump_during_send) { }
399
400 void OnAnswer(int* answer) {
401 SendDouble(pump_during_send_, true);
402 *answer = 42;
403 Done();
404 }
405
406 bool pump_during_send_;
407};
408
409void Unblock(bool server_pump, bool client_pump) {
410 std::vector<Worker*> workers;
411 workers.push_back(new UnblockServer(server_pump));
412 workers.push_back(new UnblockClient(client_pump));
413 RunTest(workers);
414}
415
416} // namespace
417
418// Tests that the caller unblocks to answer a sync message from the receiver.
419TEST_F(IPCSyncChannelTest, Unblock) {
420 Unblock(false, false);
421 Unblock(false, true);
422 Unblock(true, false);
423 Unblock(true, true);
424}
425
426//-----------------------------------------------------------------------------
427
428namespace {
429
430class RecursiveServer : public Worker {
431 public:
432 explicit RecursiveServer(
433 bool expected_send_result, bool pump_first, bool pump_second)
434 : Worker(Channel::MODE_SERVER, "recursive_server"),
435 expected_send_result_(expected_send_result),
436 pump_first_(pump_first), pump_second_(pump_second) { }
437 void Run() {
438 SendDouble(pump_first_, expected_send_result_);
439 Done();
440 }
441
442 void OnDouble(int in, int* out) {
443 *out = in * 2;
444 SendAnswerToLife(pump_second_, base::kNoTimeout, expected_send_result_);
445 }
446
447 bool expected_send_result_, pump_first_, pump_second_;
448};
449
450class RecursiveClient : public Worker {
451 public:
452 explicit RecursiveClient(bool pump_during_send, bool close_channel)
453 : Worker(Channel::MODE_CLIENT, "recursive_client"),
454 pump_during_send_(pump_during_send), close_channel_(close_channel) { }
455
456 void OnDoubleDelay(int in, Message* reply_msg) {
457 SendDouble(pump_during_send_, !close_channel_);
458 if (close_channel_) {
459 delete reply_msg;
460 } else {
461 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, in * 2);
462 Send(reply_msg);
463 }
464 Done();
465 }
466
467 void OnAnswerDelay(Message* reply_msg) {
468 if (close_channel_) {
469 delete reply_msg;
470 CloseChannel();
471 } else {
472 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
473 Send(reply_msg);
474 }
475 }
476
477 bool pump_during_send_, close_channel_;
478};
479
480void Recursive(
481 bool server_pump_first, bool server_pump_second, bool client_pump) {
482 std::vector<Worker*> workers;
483 workers.push_back(
484 new RecursiveServer(true, server_pump_first, server_pump_second));
485 workers.push_back(new RecursiveClient(client_pump, false));
486 RunTest(workers);
487}
488
489} // namespace
490
491// Tests a server calling Send while another Send is pending.
492TEST_F(IPCSyncChannelTest, Recursive) {
493 Recursive(false, false, false);
494 Recursive(false, false, true);
495 Recursive(false, true, false);
496 Recursive(false, true, true);
497 Recursive(true, false, false);
498 Recursive(true, false, true);
499 Recursive(true, true, false);
500 Recursive(true, true, true);
501}
502
503//-----------------------------------------------------------------------------
504
505namespace {
506
507void RecursiveNoHang(
508 bool server_pump_first, bool server_pump_second, bool client_pump) {
509 std::vector<Worker*> workers;
510 workers.push_back(
511 new RecursiveServer(false, server_pump_first, server_pump_second));
512 workers.push_back(new RecursiveClient(client_pump, true));
513 RunTest(workers);
514}
515
516} // namespace
517
518// Tests that if a caller makes a sync call during an existing sync call and
519// the receiver dies, neither of the Send() calls hang.
520TEST_F(IPCSyncChannelTest, RecursiveNoHang) {
521 RecursiveNoHang(false, false, false);
522 RecursiveNoHang(false, false, true);
523 RecursiveNoHang(false, true, false);
524 RecursiveNoHang(false, true, true);
525 RecursiveNoHang(true, false, false);
526 RecursiveNoHang(true, false, true);
527 RecursiveNoHang(true, true, false);
528 RecursiveNoHang(true, true, true);
529}
530
531//-----------------------------------------------------------------------------
532
533namespace {
534
535class MultipleServer1 : public Worker {
536 public:
537 MultipleServer1(bool pump_during_send)
538 : Worker("test_channel1", Channel::MODE_SERVER),
539 pump_during_send_(pump_during_send) { }
540
541 void Run() {
542 SendDouble(pump_during_send_, true);
543 Done();
544 }
545
546 bool pump_during_send_;
547};
548
549class MultipleClient1 : public Worker {
550 public:
551 MultipleClient1(WaitableEvent* client1_msg_received,
552 WaitableEvent* client1_can_reply) :
553 Worker("test_channel1", Channel::MODE_CLIENT),
554 client1_msg_received_(client1_msg_received),
555 client1_can_reply_(client1_can_reply) { }
556
557 void OnDouble(int in, int* out) {
558 client1_msg_received_->Signal();
559 *out = in * 2;
560 client1_can_reply_->Wait();
561 Done();
562 }
563
564 private:
565 WaitableEvent *client1_msg_received_, *client1_can_reply_;
566};
567
568class MultipleServer2 : public Worker {
569 public:
570 MultipleServer2() : Worker("test_channel2", Channel::MODE_SERVER) { }
571
572 void OnAnswer(int* result) {
573 *result = 42;
574 Done();
575 }
576};
577
578class MultipleClient2 : public Worker {
579 public:
580 MultipleClient2(
581 WaitableEvent* client1_msg_received, WaitableEvent* client1_can_reply,
582 bool pump_during_send)
583 : Worker("test_channel2", Channel::MODE_CLIENT),
584 client1_msg_received_(client1_msg_received),
585 client1_can_reply_(client1_can_reply),
586 pump_during_send_(pump_during_send) { }
587
588 void Run() {
589 client1_msg_received_->Wait();
590 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
591 client1_can_reply_->Signal();
592 Done();
593 }
594
595 private:
596 WaitableEvent *client1_msg_received_, *client1_can_reply_;
597 bool pump_during_send_;
598};
599
600void Multiple(bool server_pump, bool client_pump) {
601 std::vector<Worker*> workers;
602
603 // A shared worker thread so that server1 and server2 run on one thread.
604 base::Thread worker_thread("Multiple");
605 ASSERT_TRUE(worker_thread.Start());
606
607 // Server1 sends a sync msg to client1, which blocks the reply until
608 // server2 (which runs on the same worker thread as server1) responds
609 // to a sync msg from client2.
610 WaitableEvent client1_msg_received(false, false);
611 WaitableEvent client1_can_reply(false, false);
612
613 Worker* worker;
614
615 worker = new MultipleServer2();
616 worker->OverrideThread(&worker_thread);
617 workers.push_back(worker);
618
619 worker = new MultipleClient2(
620 &client1_msg_received, &client1_can_reply, client_pump);
621 workers.push_back(worker);
622
623 worker = new MultipleServer1(server_pump);
624 worker->OverrideThread(&worker_thread);
625 workers.push_back(worker);
626
627 worker = new MultipleClient1(
628 &client1_msg_received, &client1_can_reply);
629 workers.push_back(worker);
630
631 RunTest(workers);
632}
633
634} // namespace
635
636// Tests that multiple SyncObjects on the same listener thread can unblock each
637// other.
638TEST_F(IPCSyncChannelTest, Multiple) {
639 Multiple(false, false);
640 Multiple(false, true);
641 Multiple(true, false);
642 Multiple(true, true);
643}
644
645//-----------------------------------------------------------------------------
646
647namespace {
648
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900649// This class provides server side functionality to test the case where
650// multiple sync channels are in use on the same thread on the client and
651// nested calls are issued.
652class QueuedReplyServer : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900653 public:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900654 QueuedReplyServer(base::Thread* listener_thread,
655 const std::string& channel_name,
656 const std::string& reply_text)
657 : Worker(channel_name, Channel::MODE_SERVER),
658 reply_text_(reply_text) {
659 Worker::OverrideThread(listener_thread);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900660 }
661
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900662 virtual void OnNestedTestMsg(Message* reply_msg) {
663 LOG(INFO) << __FUNCTION__ << " Sending reply: "
664 << reply_text_.c_str();
665 SyncChannelNestedTestMsg_String::WriteReplyParams(
666 reply_msg, reply_text_);
667 Send(reply_msg);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900668 Done();
669 }
670
671 private:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900672 std::string reply_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900673};
674
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900675// The QueuedReplyClient class provides functionality to test the case where
676// multiple sync channels are in use on the same thread and they make nested
677// sync calls, i.e. while the first channel waits for a response it makes a
678// sync call on another channel.
679// The callstack should unwind correctly, i.e. the outermost call should
680// complete first, and so on.
681class QueuedReplyClient : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900682 public:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900683 QueuedReplyClient(base::Thread* listener_thread,
684 const std::string& channel_name,
685 const std::string& expected_text,
686 bool pump_during_send)
687 : Worker(channel_name, Channel::MODE_CLIENT),
688 expected_text_(expected_text),
689 pump_during_send_(pump_during_send) {
690 Worker::OverrideThread(listener_thread);
691 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900692
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900693 virtual void Run() {
694 std::string response;
695 SyncMessage* msg = new SyncChannelNestedTestMsg_String(&response);
696 if (pump_during_send_)
697 msg->EnableMessagePumping();
698 bool result = Send(msg);
699 DCHECK(result);
700 DCHECK(response == expected_text_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900701
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900702 LOG(INFO) << __FUNCTION__ << " Received reply: "
703 << response.c_str();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900704 Done();
705 }
706
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900707 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900708 bool pump_during_send_;
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900709 std::string expected_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900710};
711
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900712void QueuedReply(bool client_pump) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900713 std::vector<Worker*> workers;
714
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900715 // A shared worker thread for servers
716 base::Thread server_worker_thread("QueuedReply_ServerListener");
717 ASSERT_TRUE(server_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900718
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900719 base::Thread client_worker_thread("QueuedReply_ClientListener");
720 ASSERT_TRUE(client_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900721
722 Worker* worker;
723
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900724 worker = new QueuedReplyServer(&server_worker_thread,
725 "QueuedReply_Server1",
726 "Got first message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900727 workers.push_back(worker);
728
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900729 worker = new QueuedReplyServer(&server_worker_thread,
730 "QueuedReply_Server2",
731 "Got second message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900732 workers.push_back(worker);
733
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900734 worker = new QueuedReplyClient(&client_worker_thread,
735 "QueuedReply_Server1",
736 "Got first message",
737 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900738 workers.push_back(worker);
739
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900740 worker = new QueuedReplyClient(&client_worker_thread,
741 "QueuedReply_Server2",
742 "Got second message",
743 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900744 workers.push_back(worker);
745
746 RunTest(workers);
747}
748
749} // namespace
750
751// While a blocking send is in progress, the listener thread might answer other
752// synchronous messages. This tests that if during the response to another
753// message the reply to the original messages comes, it is queued up correctly
754// and the original Send is unblocked later.
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900755// We also test that the send call stacks unwind correctly when the channel
756// pumps messages while waiting for a response.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900757TEST_F(IPCSyncChannelTest, QueuedReply) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900758 QueuedReply(false);
759 QueuedReply(true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900760}
761
762//-----------------------------------------------------------------------------
763
764namespace {
765
766class BadServer : public Worker {
767 public:
768 BadServer(bool pump_during_send)
769 : Worker(Channel::MODE_SERVER, "simpler_server"),
770 pump_during_send_(pump_during_send) { }
771 void Run() {
772 int answer = 0;
773
774 SyncMessage* msg = new SyncMessage(
775 MSG_ROUTING_CONTROL, SyncChannelTestMsg_Double::ID,
776 Message::PRIORITY_NORMAL, NULL);
777 if (pump_during_send_)
778 msg->EnableMessagePumping();
779
780 // Temporarily set the minimum logging very high so that the assertion
781 // in ipc_message_utils doesn't fire.
782 int log_level = logging::GetMinLogLevel();
783 logging::SetMinLogLevel(kint32max);
784 bool result = Send(msg);
785 logging::SetMinLogLevel(log_level);
786 DCHECK(!result);
787
788 // Need to send another message to get the client to call Done().
789 result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
790 DCHECK(result);
791 DCHECK(answer == 42);
792
793 Done();
794 }
795
796 bool pump_during_send_;
797};
798
799void BadMessage(bool pump_during_send) {
800 std::vector<Worker*> workers;
801 workers.push_back(new BadServer(pump_during_send));
802 workers.push_back(new SimpleClient());
803 RunTest(workers);
804}
805
806} // namespace
807
808// Tests that if a message is not serialized correctly, the Send() will fail.
809TEST_F(IPCSyncChannelTest, BadMessage) {
810 BadMessage(false);
811 BadMessage(true);
812}
813
814//-----------------------------------------------------------------------------
815
816namespace {
817
818class ChattyClient : public Worker {
819 public:
820 ChattyClient() :
821 Worker(Channel::MODE_CLIENT, "chatty_client") { }
822
823 void OnAnswer(int* answer) {
824 // The PostMessage limit is 10k. Send 20% more than that.
825 const int kMessageLimit = 10000;
826 const int kMessagesToSend = kMessageLimit * 120 / 100;
827 for (int i = 0; i < kMessagesToSend; ++i) {
828 if (!SendDouble(false, true))
829 break;
830 }
831 *answer = 42;
832 Done();
833 }
834};
835
836void ChattyServer(bool pump_during_send) {
837 std::vector<Worker*> workers;
838 workers.push_back(new UnblockServer(pump_during_send));
839 workers.push_back(new ChattyClient());
840 RunTest(workers);
841}
842
843} // namespace
844
845// Tests http://b/1093251 - that sending lots of sync messages while
846// the receiver is waiting for a sync reply does not overflow the PostMessage
847// queue.
848TEST_F(IPCSyncChannelTest, ChattyServer) {
849 ChattyServer(false);
850 ChattyServer(true);
851}
852
853//------------------------------------------------------------------------------
854
855namespace {
856
857class TimeoutServer : public Worker {
858 public:
859 TimeoutServer(int timeout_ms,
860 std::vector<bool> timeout_seq,
861 bool pump_during_send)
862 : Worker(Channel::MODE_SERVER, "timeout_server"),
863 timeout_ms_(timeout_ms),
864 timeout_seq_(timeout_seq),
865 pump_during_send_(pump_during_send) {
866 }
867
868 void Run() {
869 for (std::vector<bool>::const_iterator iter = timeout_seq_.begin();
870 iter != timeout_seq_.end(); ++iter) {
871 SendAnswerToLife(pump_during_send_, timeout_ms_, !*iter);
872 }
873 Done();
874 }
875
876 private:
877 int timeout_ms_;
878 std::vector<bool> timeout_seq_;
879 bool pump_during_send_;
880};
881
882class UnresponsiveClient : public Worker {
883 public:
884 UnresponsiveClient(std::vector<bool> timeout_seq)
885 : Worker(Channel::MODE_CLIENT, "unresponsive_client"),
886 timeout_seq_(timeout_seq) {
887 }
888
889 void OnAnswerDelay(Message* reply_msg) {
890 DCHECK(!timeout_seq_.empty());
891 if (!timeout_seq_[0]) {
892 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
893 Send(reply_msg);
894 } else {
895 // Don't reply.
896 delete reply_msg;
897 }
898 timeout_seq_.erase(timeout_seq_.begin());
899 if (timeout_seq_.empty())
900 Done();
901 }
902
903 private:
904 // Whether we should time-out or respond to the various messages we receive.
905 std::vector<bool> timeout_seq_;
906};
907
908void SendWithTimeoutOK(bool pump_during_send) {
909 std::vector<Worker*> workers;
910 std::vector<bool> timeout_seq;
911 timeout_seq.push_back(false);
912 timeout_seq.push_back(false);
913 timeout_seq.push_back(false);
914 workers.push_back(new TimeoutServer(5000, timeout_seq, pump_during_send));
915 workers.push_back(new SimpleClient());
916 RunTest(workers);
917}
918
919void SendWithTimeoutTimeout(bool pump_during_send) {
920 std::vector<Worker*> workers;
921 std::vector<bool> timeout_seq;
922 timeout_seq.push_back(true);
923 timeout_seq.push_back(false);
924 timeout_seq.push_back(false);
925 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
926 workers.push_back(new UnresponsiveClient(timeout_seq));
927 RunTest(workers);
928}
929
930void SendWithTimeoutMixedOKAndTimeout(bool pump_during_send) {
931 std::vector<Worker*> workers;
932 std::vector<bool> timeout_seq;
933 timeout_seq.push_back(true);
934 timeout_seq.push_back(false);
935 timeout_seq.push_back(false);
936 timeout_seq.push_back(true);
937 timeout_seq.push_back(false);
938 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
939 workers.push_back(new UnresponsiveClient(timeout_seq));
940 RunTest(workers);
941}
942
943} // namespace
944
945// Tests that SendWithTimeout does not time-out if the response comes back fast
946// enough.
947TEST_F(IPCSyncChannelTest, SendWithTimeoutOK) {
948 SendWithTimeoutOK(false);
949 SendWithTimeoutOK(true);
950}
951
952// Tests that SendWithTimeout does time-out.
953TEST_F(IPCSyncChannelTest, SendWithTimeoutTimeout) {
954 SendWithTimeoutTimeout(false);
955 SendWithTimeoutTimeout(true);
956}
957
958// Sends some message that time-out and some that succeed.
959TEST_F(IPCSyncChannelTest, SendWithTimeoutMixedOKAndTimeout) {
960 SendWithTimeoutMixedOKAndTimeout(false);
961 SendWithTimeoutMixedOKAndTimeout(true);
962}
963
964//------------------------------------------------------------------------------
965
966namespace {
967
968class NestedTask : public Task {
969 public:
970 NestedTask(Worker* server) : server_(server) { }
971 void Run() {
972 // Sleep a bit so that we wake up after the reply has been received.
973 PlatformThread::Sleep(250);
974 server_->SendAnswerToLife(true, base::kNoTimeout, true);
975 }
976
977 Worker* server_;
978};
979
980static bool timeout_occured = false;
981
982class TimeoutTask : public Task {
983 public:
984 void Run() {
985 timeout_occured = true;
986 }
987};
988
989class DoneEventRaceServer : public Worker {
990 public:
991 DoneEventRaceServer()
992 : Worker(Channel::MODE_SERVER, "done_event_race_server") { }
993
994 void Run() {
995 MessageLoop::current()->PostTask(FROM_HERE, new NestedTask(this));
996 MessageLoop::current()->PostDelayedTask(FROM_HERE, new TimeoutTask(), 9000);
997 // Even though we have a timeout on the Send, it will succeed since for this
998 // bug, the reply message comes back and is deserialized, however the done
999 // event wasn't set. So we indirectly use the timeout task to notice if a
1000 // timeout occurred.
1001 SendAnswerToLife(true, 10000, true);
1002 DCHECK(!timeout_occured);
1003 Done();
1004 }
1005};
1006
1007} // namespace
1008
1009// Tests http://b/1474092 - that if after the done_event is set but before
1010// OnObjectSignaled is called another message is sent out, then after its
1011// reply comes back OnObjectSignaled will be called for the first message.
1012TEST_F(IPCSyncChannelTest, DoneEventRace) {
1013 std::vector<Worker*> workers;
1014 workers.push_back(new DoneEventRaceServer());
1015 workers.push_back(new SimpleClient());
1016 RunTest(workers);
1017}