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