blob: ffd2efd230b1da0feb390f4966176d32b7cc74e1 [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
erg@google.come6ffcb52010-08-18 03:38:24 +090029// Definition of IPC Messages used for this test.
30#define MESSAGES_INTERNAL_IMPL_FILE "ipc/ipc_sync_message_unittest.h"
31#include "ipc/ipc_message_impl_macros.h"
32
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090033using namespace IPC;
34using base::WaitableEvent;
35
36namespace {
37
38// Base class for a "process" with listener and IPC threads.
39class Worker : public Channel::Listener, public Message::Sender {
40 public:
41 // Will create a channel without a name.
42 Worker(Channel::Mode mode, const std::string& thread_name)
43 : done_(new WaitableEvent(false, false)),
44 channel_created_(new WaitableEvent(false, false)),
45 mode_(mode),
46 ipc_thread_((thread_name + "_ipc").c_str()),
47 listener_thread_((thread_name + "_listener").c_str()),
48 overrided_thread_(NULL),
timurrrr@chromium.org03100a82009-10-27 20:28:58 +090049 shutdown_event_(true, false) {
50 // The data race on vfptr is real but is very hard
51 // to suppress using standard Valgrind mechanism (suppressions).
52 // We have to use ANNOTATE_BENIGN_RACE to hide the reports and
53 // make ThreadSanitizer bots green.
54 ANNOTATE_BENIGN_RACE(this, "Race on vfptr, http://crbug.com/25841");
55 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090056
57 // Will create a named channel and use this name for the threads' name.
58 Worker(const std::string& channel_name, Channel::Mode mode)
59 : done_(new WaitableEvent(false, false)),
60 channel_created_(new WaitableEvent(false, false)),
61 channel_name_(channel_name),
62 mode_(mode),
63 ipc_thread_((channel_name + "_ipc").c_str()),
64 listener_thread_((channel_name + "_listener").c_str()),
65 overrided_thread_(NULL),
timurrrr@chromium.org03100a82009-10-27 20:28:58 +090066 shutdown_event_(true, false) {
67 // The data race on vfptr is real but is very hard
68 // to suppress using standard Valgrind mechanism (suppressions).
69 // We have to use ANNOTATE_BENIGN_RACE to hide the reports and
70 // make ThreadSanitizer bots green.
71 ANNOTATE_BENIGN_RACE(this, "Race on vfptr, http://crbug.com/25841");
72 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090073
74 // The IPC thread needs to outlive SyncChannel, so force the correct order of
75 // destruction.
76 virtual ~Worker() {
77 WaitableEvent listener_done(false, false), ipc_done(false, false);
78 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
79 this, &Worker::OnListenerThreadShutdown1, &listener_done,
80 &ipc_done));
81 listener_done.Wait();
82 ipc_done.Wait();
83 ipc_thread_.Stop();
84 listener_thread_.Stop();
85 }
86 void AddRef() { }
87 void Release() { }
darin@chromium.org5cb996e2009-09-30 13:29:20 +090088 static bool ImplementsThreadSafeReferenceCounting() { return true; }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090089 bool Send(Message* msg) { return channel_->Send(msg); }
90 bool SendWithTimeout(Message* msg, int timeout_ms) {
91 return channel_->SendWithTimeout(msg, timeout_ms);
92 }
93 void WaitForChannelCreation() { channel_created_->Wait(); }
94 void CloseChannel() {
95 DCHECK(MessageLoop::current() == ListenerThread()->message_loop());
96 channel_->Close();
97 }
98 void Start() {
99 StartThread(&listener_thread_, MessageLoop::TYPE_DEFAULT);
100 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
101 this, &Worker::OnStart));
102 }
103 void OverrideThread(base::Thread* overrided_thread) {
104 DCHECK(overrided_thread_ == NULL);
105 overrided_thread_ = overrided_thread;
106 }
107 bool SendAnswerToLife(bool pump, int timeout, bool succeed) {
108 int answer = 0;
109 SyncMessage* msg = new SyncChannelTestMsg_AnswerToLife(&answer);
110 if (pump)
111 msg->EnableMessagePumping();
112 bool result = SendWithTimeout(msg, timeout);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900113 DCHECK_EQ(result, succeed);
114 DCHECK_EQ(answer, (succeed ? 42 : 0));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900115 return result;
116 }
117 bool SendDouble(bool pump, bool succeed) {
118 int answer = 0;
119 SyncMessage* msg = new SyncChannelTestMsg_Double(5, &answer);
120 if (pump)
121 msg->EnableMessagePumping();
122 bool result = Send(msg);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900123 DCHECK_EQ(result, succeed);
124 DCHECK_EQ(answer, (succeed ? 10 : 0));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900125 return result;
126 }
127 Channel::Mode mode() { return mode_; }
128 WaitableEvent* done_event() { return done_.get(); }
jabdelmalek@google.comeb921652010-04-07 05:33:36 +0900129 WaitableEvent* shutdown_event() { return &shutdown_event_; }
jam@chromium.orgebd07182009-12-01 11:34:18 +0900130 void ResetChannel() { channel_.reset(); }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900131 // Derived classes need to call this when they've completed their part of
132 // the test.
133 void Done() { done_->Signal(); }
jabdelmalek@google.comeb921652010-04-07 05:33:36 +0900134
135 protected:
136 IPC::SyncChannel* channel() { return channel_.get(); }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900137 // Functions for dervied classes to implement if they wish.
138 virtual void Run() { }
139 virtual void OnAnswer(int* answer) { NOTREACHED(); }
140 virtual void OnAnswerDelay(Message* reply_msg) {
141 // The message handler map below can only take one entry for
142 // SyncChannelTestMsg_AnswerToLife, so since some classes want
143 // the normal version while other want the delayed reply, we
144 // call the normal version if the derived class didn't override
145 // this function.
146 int answer;
147 OnAnswer(&answer);
148 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, answer);
149 Send(reply_msg);
150 }
151 virtual void OnDouble(int in, int* out) { NOTREACHED(); }
152 virtual void OnDoubleDelay(int in, Message* reply_msg) {
153 int result;
154 OnDouble(in, &result);
155 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, result);
156 Send(reply_msg);
157 }
158
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900159 virtual void OnNestedTestMsg(Message* reply_msg) {
160 NOTREACHED();
161 }
162
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900163 base::Thread* ListenerThread() {
164 return overrided_thread_ ? overrided_thread_ : &listener_thread_;
165 }
ananta@chromium.org999f2972010-09-03 06:45:50 +0900166
167 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900168 // Called on the listener thread to create the sync channel.
169 void OnStart() {
170 // Link ipc_thread_, listener_thread_ and channel_ altogether.
171 StartThread(&ipc_thread_, MessageLoop::TYPE_IO);
172 channel_.reset(new SyncChannel(
173 channel_name_, mode_, this, NULL, ipc_thread_.message_loop(), true,
174 &shutdown_event_));
175 channel_created_->Signal();
176 Run();
177 }
178
179 void OnListenerThreadShutdown1(WaitableEvent* listener_event,
180 WaitableEvent* ipc_event) {
181 // SyncChannel needs to be destructed on the thread that it was created on.
182 channel_.reset();
183
184 MessageLoop::current()->RunAllPending();
185
186 ipc_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
187 this, &Worker::OnIPCThreadShutdown, listener_event, ipc_event));
188 }
189
190 void OnIPCThreadShutdown(WaitableEvent* listener_event,
191 WaitableEvent* ipc_event) {
192 MessageLoop::current()->RunAllPending();
193 ipc_event->Signal();
194
195 listener_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
196 this, &Worker::OnListenerThreadShutdown2, listener_event));
197 }
198
199 void OnListenerThreadShutdown2(WaitableEvent* listener_event) {
200 MessageLoop::current()->RunAllPending();
201 listener_event->Signal();
202 }
203
204 void OnMessageReceived(const Message& message) {
205 IPC_BEGIN_MESSAGE_MAP(Worker, message)
206 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_Double, OnDoubleDelay)
207 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_AnswerToLife,
208 OnAnswerDelay)
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900209 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelNestedTestMsg_String,
210 OnNestedTestMsg)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900211 IPC_END_MESSAGE_MAP()
212 }
213
214 void StartThread(base::Thread* thread, MessageLoop::Type type) {
215 base::Thread::Options options;
216 options.message_loop_type = type;
217 thread->StartWithOptions(options);
218 }
219
220 scoped_ptr<WaitableEvent> done_;
221 scoped_ptr<WaitableEvent> channel_created_;
222 std::string channel_name_;
223 Channel::Mode mode_;
224 scoped_ptr<SyncChannel> channel_;
225 base::Thread ipc_thread_;
226 base::Thread listener_thread_;
227 base::Thread* overrided_thread_;
228
229 base::WaitableEvent shutdown_event_;
230
tfarina@chromium.orgb73eaee2010-06-07 11:10:18 +0900231 DISALLOW_COPY_AND_ASSIGN(Worker);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900232};
233
234
235// Starts the test with the given workers. This function deletes the workers
236// when it's done.
237void RunTest(std::vector<Worker*> workers) {
238 // First we create the workers that are channel servers, or else the other
239 // workers' channel initialization might fail because the pipe isn't created..
240 for (size_t i = 0; i < workers.size(); ++i) {
241 if (workers[i]->mode() == Channel::MODE_SERVER) {
242 workers[i]->Start();
243 workers[i]->WaitForChannelCreation();
244 }
245 }
246
247 // now create the clients
248 for (size_t i = 0; i < workers.size(); ++i) {
249 if (workers[i]->mode() == Channel::MODE_CLIENT)
250 workers[i]->Start();
251 }
252
253 // wait for all the workers to finish
254 for (size_t i = 0; i < workers.size(); ++i)
255 workers[i]->done_event()->Wait();
256
257 STLDeleteContainerPointers(workers.begin(), workers.end());
258}
259
260} // namespace
261
262class IPCSyncChannelTest : public testing::Test {
263 private:
264 MessageLoop message_loop_;
265};
266
267//-----------------------------------------------------------------------------
268
269namespace {
270
271class SimpleServer : public Worker {
272 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900273 explicit SimpleServer(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900274 : Worker(Channel::MODE_SERVER, "simpler_server"),
275 pump_during_send_(pump_during_send) { }
276 void Run() {
277 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
278 Done();
279 }
280
281 bool pump_during_send_;
282};
283
284class SimpleClient : public Worker {
285 public:
286 SimpleClient() : Worker(Channel::MODE_CLIENT, "simple_client") { }
287
288 void OnAnswer(int* answer) {
289 *answer = 42;
290 Done();
291 }
292};
293
294void Simple(bool pump_during_send) {
295 std::vector<Worker*> workers;
296 workers.push_back(new SimpleServer(pump_during_send));
297 workers.push_back(new SimpleClient());
298 RunTest(workers);
299}
300
301} // namespace
302
303// Tests basic synchronous call
304TEST_F(IPCSyncChannelTest, Simple) {
305 Simple(false);
306 Simple(true);
307}
308
309//-----------------------------------------------------------------------------
310
311namespace {
312
313class DelayClient : public Worker {
314 public:
315 DelayClient() : Worker(Channel::MODE_CLIENT, "delay_client") { }
316
317 void OnAnswerDelay(Message* reply_msg) {
318 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
319 Send(reply_msg);
320 Done();
321 }
322};
323
324void DelayReply(bool pump_during_send) {
325 std::vector<Worker*> workers;
326 workers.push_back(new SimpleServer(pump_during_send));
327 workers.push_back(new DelayClient());
328 RunTest(workers);
329}
330
331} // namespace
332
333// Tests that asynchronous replies work
334TEST_F(IPCSyncChannelTest, DelayReply) {
335 DelayReply(false);
336 DelayReply(true);
337}
338
339//-----------------------------------------------------------------------------
340
341namespace {
342
343class NoHangServer : public Worker {
344 public:
345 explicit NoHangServer(WaitableEvent* got_first_reply, bool pump_during_send)
346 : Worker(Channel::MODE_SERVER, "no_hang_server"),
347 got_first_reply_(got_first_reply),
348 pump_during_send_(pump_during_send) { }
349 void Run() {
350 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
351 got_first_reply_->Signal();
352
353 SendAnswerToLife(pump_during_send_, base::kNoTimeout, false);
354 Done();
355 }
356
357 WaitableEvent* got_first_reply_;
358 bool pump_during_send_;
359};
360
361class NoHangClient : public Worker {
362 public:
363 explicit NoHangClient(WaitableEvent* got_first_reply)
364 : Worker(Channel::MODE_CLIENT, "no_hang_client"),
365 got_first_reply_(got_first_reply) { }
366
367 virtual void OnAnswerDelay(Message* reply_msg) {
368 // Use the DELAY_REPLY macro so that we can force the reply to be sent
369 // before this function returns (when the channel will be reset).
370 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
371 Send(reply_msg);
372 got_first_reply_->Wait();
373 CloseChannel();
374 Done();
375 }
376
377 WaitableEvent* got_first_reply_;
378};
379
380void NoHang(bool pump_during_send) {
381 WaitableEvent got_first_reply(false, false);
382 std::vector<Worker*> workers;
383 workers.push_back(new NoHangServer(&got_first_reply, pump_during_send));
384 workers.push_back(new NoHangClient(&got_first_reply));
385 RunTest(workers);
386}
387
388} // namespace
389
390// Tests that caller doesn't hang if receiver dies
391TEST_F(IPCSyncChannelTest, NoHang) {
392 NoHang(false);
393 NoHang(true);
394}
395
396//-----------------------------------------------------------------------------
397
398namespace {
399
400class UnblockServer : public Worker {
401 public:
jam@chromium.orgebd07182009-12-01 11:34:18 +0900402 UnblockServer(bool pump_during_send, bool delete_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900403 : Worker(Channel::MODE_SERVER, "unblock_server"),
jam@chromium.orgebd07182009-12-01 11:34:18 +0900404 pump_during_send_(pump_during_send),
405 delete_during_send_(delete_during_send) { }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900406 void Run() {
jam@chromium.orgebd07182009-12-01 11:34:18 +0900407 if (delete_during_send_) {
408 // Use custom code since race conditions mean the answer may or may not be
409 // available.
410 int answer = 0;
411 SyncMessage* msg = new SyncChannelTestMsg_AnswerToLife(&answer);
412 if (pump_during_send_)
413 msg->EnableMessagePumping();
414 Send(msg);
415 } else {
416 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
417 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900418 Done();
419 }
420
jam@chromium.orgebd07182009-12-01 11:34:18 +0900421 void OnDoubleDelay(int in, Message* reply_msg) {
422 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, in * 2);
423 Send(reply_msg);
424 if (delete_during_send_)
425 ResetChannel();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900426 }
427
428 bool pump_during_send_;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900429 bool delete_during_send_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900430};
431
432class UnblockClient : public Worker {
433 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900434 explicit UnblockClient(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900435 : Worker(Channel::MODE_CLIENT, "unblock_client"),
436 pump_during_send_(pump_during_send) { }
437
438 void OnAnswer(int* answer) {
439 SendDouble(pump_during_send_, true);
440 *answer = 42;
441 Done();
442 }
443
444 bool pump_during_send_;
445};
446
jam@chromium.orgebd07182009-12-01 11:34:18 +0900447void Unblock(bool server_pump, bool client_pump, bool delete_during_send) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900448 std::vector<Worker*> workers;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900449 workers.push_back(new UnblockServer(server_pump, delete_during_send));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900450 workers.push_back(new UnblockClient(client_pump));
451 RunTest(workers);
452}
453
454} // namespace
455
456// Tests that the caller unblocks to answer a sync message from the receiver.
457TEST_F(IPCSyncChannelTest, Unblock) {
jam@chromium.orgebd07182009-12-01 11:34:18 +0900458 Unblock(false, false, false);
459 Unblock(false, true, false);
460 Unblock(true, false, false);
461 Unblock(true, true, false);
462}
463
464//-----------------------------------------------------------------------------
465
466// Tests that the the IPC::SyncChannel object can be deleted during a Send.
467TEST_F(IPCSyncChannelTest, ChannelDeleteDuringSend) {
468 Unblock(false, false, true);
469 Unblock(false, true, true);
470 Unblock(true, false, true);
471 Unblock(true, true, true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900472}
473
474//-----------------------------------------------------------------------------
475
476namespace {
477
478class RecursiveServer : public Worker {
479 public:
480 explicit RecursiveServer(
481 bool expected_send_result, bool pump_first, bool pump_second)
482 : Worker(Channel::MODE_SERVER, "recursive_server"),
483 expected_send_result_(expected_send_result),
484 pump_first_(pump_first), pump_second_(pump_second) { }
485 void Run() {
486 SendDouble(pump_first_, expected_send_result_);
487 Done();
488 }
489
490 void OnDouble(int in, int* out) {
491 *out = in * 2;
492 SendAnswerToLife(pump_second_, base::kNoTimeout, expected_send_result_);
493 }
494
495 bool expected_send_result_, pump_first_, pump_second_;
496};
497
498class RecursiveClient : public Worker {
499 public:
500 explicit RecursiveClient(bool pump_during_send, bool close_channel)
501 : Worker(Channel::MODE_CLIENT, "recursive_client"),
502 pump_during_send_(pump_during_send), close_channel_(close_channel) { }
503
504 void OnDoubleDelay(int in, Message* reply_msg) {
505 SendDouble(pump_during_send_, !close_channel_);
506 if (close_channel_) {
507 delete reply_msg;
508 } else {
509 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, in * 2);
510 Send(reply_msg);
511 }
512 Done();
513 }
514
515 void OnAnswerDelay(Message* reply_msg) {
516 if (close_channel_) {
517 delete reply_msg;
518 CloseChannel();
519 } else {
520 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
521 Send(reply_msg);
522 }
523 }
524
525 bool pump_during_send_, close_channel_;
526};
527
528void Recursive(
529 bool server_pump_first, bool server_pump_second, bool client_pump) {
530 std::vector<Worker*> workers;
531 workers.push_back(
532 new RecursiveServer(true, server_pump_first, server_pump_second));
533 workers.push_back(new RecursiveClient(client_pump, false));
534 RunTest(workers);
535}
536
537} // namespace
538
539// Tests a server calling Send while another Send is pending.
540TEST_F(IPCSyncChannelTest, Recursive) {
541 Recursive(false, false, false);
542 Recursive(false, false, true);
543 Recursive(false, true, false);
544 Recursive(false, true, true);
545 Recursive(true, false, false);
546 Recursive(true, false, true);
547 Recursive(true, true, false);
548 Recursive(true, true, true);
549}
550
551//-----------------------------------------------------------------------------
552
553namespace {
554
555void RecursiveNoHang(
556 bool server_pump_first, bool server_pump_second, bool client_pump) {
557 std::vector<Worker*> workers;
558 workers.push_back(
559 new RecursiveServer(false, server_pump_first, server_pump_second));
560 workers.push_back(new RecursiveClient(client_pump, true));
561 RunTest(workers);
562}
563
564} // namespace
565
566// Tests that if a caller makes a sync call during an existing sync call and
567// the receiver dies, neither of the Send() calls hang.
568TEST_F(IPCSyncChannelTest, RecursiveNoHang) {
569 RecursiveNoHang(false, false, false);
570 RecursiveNoHang(false, false, true);
571 RecursiveNoHang(false, true, false);
572 RecursiveNoHang(false, true, true);
573 RecursiveNoHang(true, false, false);
574 RecursiveNoHang(true, false, true);
575 RecursiveNoHang(true, true, false);
576 RecursiveNoHang(true, true, true);
577}
578
579//-----------------------------------------------------------------------------
580
581namespace {
582
583class MultipleServer1 : public Worker {
584 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900585 explicit MultipleServer1(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900586 : Worker("test_channel1", Channel::MODE_SERVER),
587 pump_during_send_(pump_during_send) { }
588
589 void Run() {
590 SendDouble(pump_during_send_, true);
591 Done();
592 }
593
594 bool pump_during_send_;
595};
596
597class MultipleClient1 : public Worker {
598 public:
599 MultipleClient1(WaitableEvent* client1_msg_received,
600 WaitableEvent* client1_can_reply) :
601 Worker("test_channel1", Channel::MODE_CLIENT),
602 client1_msg_received_(client1_msg_received),
603 client1_can_reply_(client1_can_reply) { }
604
605 void OnDouble(int in, int* out) {
606 client1_msg_received_->Signal();
607 *out = in * 2;
608 client1_can_reply_->Wait();
609 Done();
610 }
611
612 private:
613 WaitableEvent *client1_msg_received_, *client1_can_reply_;
614};
615
616class MultipleServer2 : public Worker {
617 public:
618 MultipleServer2() : Worker("test_channel2", Channel::MODE_SERVER) { }
619
620 void OnAnswer(int* result) {
621 *result = 42;
622 Done();
623 }
624};
625
626class MultipleClient2 : public Worker {
627 public:
628 MultipleClient2(
629 WaitableEvent* client1_msg_received, WaitableEvent* client1_can_reply,
630 bool pump_during_send)
631 : Worker("test_channel2", Channel::MODE_CLIENT),
632 client1_msg_received_(client1_msg_received),
633 client1_can_reply_(client1_can_reply),
634 pump_during_send_(pump_during_send) { }
635
636 void Run() {
637 client1_msg_received_->Wait();
638 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
639 client1_can_reply_->Signal();
640 Done();
641 }
642
643 private:
644 WaitableEvent *client1_msg_received_, *client1_can_reply_;
645 bool pump_during_send_;
646};
647
648void Multiple(bool server_pump, bool client_pump) {
649 std::vector<Worker*> workers;
650
651 // A shared worker thread so that server1 and server2 run on one thread.
652 base::Thread worker_thread("Multiple");
653 ASSERT_TRUE(worker_thread.Start());
654
655 // Server1 sends a sync msg to client1, which blocks the reply until
656 // server2 (which runs on the same worker thread as server1) responds
657 // to a sync msg from client2.
658 WaitableEvent client1_msg_received(false, false);
659 WaitableEvent client1_can_reply(false, false);
660
661 Worker* worker;
662
663 worker = new MultipleServer2();
664 worker->OverrideThread(&worker_thread);
665 workers.push_back(worker);
666
667 worker = new MultipleClient2(
668 &client1_msg_received, &client1_can_reply, client_pump);
669 workers.push_back(worker);
670
671 worker = new MultipleServer1(server_pump);
672 worker->OverrideThread(&worker_thread);
673 workers.push_back(worker);
674
675 worker = new MultipleClient1(
676 &client1_msg_received, &client1_can_reply);
677 workers.push_back(worker);
678
679 RunTest(workers);
680}
681
682} // namespace
683
684// Tests that multiple SyncObjects on the same listener thread can unblock each
685// other.
686TEST_F(IPCSyncChannelTest, Multiple) {
687 Multiple(false, false);
688 Multiple(false, true);
689 Multiple(true, false);
690 Multiple(true, true);
691}
692
693//-----------------------------------------------------------------------------
694
695namespace {
696
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900697// This class provides server side functionality to test the case where
698// multiple sync channels are in use on the same thread on the client and
699// nested calls are issued.
700class QueuedReplyServer : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900701 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900702 QueuedReplyServer(base::Thread* listener_thread,
703 const std::string& channel_name,
704 const std::string& reply_text)
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900705 : Worker(channel_name, Channel::MODE_SERVER),
706 reply_text_(reply_text) {
707 Worker::OverrideThread(listener_thread);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900708 }
709
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900710 virtual void OnNestedTestMsg(Message* reply_msg) {
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900711 VLOG(1) << __FUNCTION__ << " Sending reply: " << reply_text_;
712 SyncChannelNestedTestMsg_String::WriteReplyParams(reply_msg, reply_text_);
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900713 Send(reply_msg);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900714 Done();
715 }
716
717 private:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900718 std::string reply_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900719};
720
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900721// The QueuedReplyClient class provides functionality to test the case where
722// multiple sync channels are in use on the same thread and they make nested
723// sync calls, i.e. while the first channel waits for a response it makes a
724// sync call on another channel.
725// The callstack should unwind correctly, i.e. the outermost call should
726// complete first, and so on.
727class QueuedReplyClient : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900728 public:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900729 QueuedReplyClient(base::Thread* listener_thread,
730 const std::string& channel_name,
731 const std::string& expected_text,
732 bool pump_during_send)
733 : Worker(channel_name, Channel::MODE_CLIENT),
thomasvl@google.com9a242072010-07-23 23:18:59 +0900734 pump_during_send_(pump_during_send),
735 expected_text_(expected_text) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900736 Worker::OverrideThread(listener_thread);
737 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900738
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900739 virtual void Run() {
740 std::string response;
741 SyncMessage* msg = new SyncChannelNestedTestMsg_String(&response);
742 if (pump_during_send_)
743 msg->EnableMessagePumping();
744 bool result = Send(msg);
745 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900746 DCHECK_EQ(response, expected_text_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900747
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900748 VLOG(1) << __FUNCTION__ << " Received reply: " << response;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900749 Done();
750 }
751
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900752 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900753 bool pump_during_send_;
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900754 std::string expected_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900755};
756
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900757void QueuedReply(bool client_pump) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900758 std::vector<Worker*> workers;
759
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900760 // A shared worker thread for servers
761 base::Thread server_worker_thread("QueuedReply_ServerListener");
762 ASSERT_TRUE(server_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900763
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900764 base::Thread client_worker_thread("QueuedReply_ClientListener");
765 ASSERT_TRUE(client_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900766
767 Worker* worker;
768
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900769 worker = new QueuedReplyServer(&server_worker_thread,
770 "QueuedReply_Server1",
771 "Got first message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900772 workers.push_back(worker);
773
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900774 worker = new QueuedReplyServer(&server_worker_thread,
775 "QueuedReply_Server2",
776 "Got second message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900777 workers.push_back(worker);
778
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900779 worker = new QueuedReplyClient(&client_worker_thread,
780 "QueuedReply_Server1",
781 "Got first message",
782 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900783 workers.push_back(worker);
784
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900785 worker = new QueuedReplyClient(&client_worker_thread,
786 "QueuedReply_Server2",
787 "Got second message",
788 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900789 workers.push_back(worker);
790
791 RunTest(workers);
792}
793
794} // namespace
795
796// While a blocking send is in progress, the listener thread might answer other
797// synchronous messages. This tests that if during the response to another
798// message the reply to the original messages comes, it is queued up correctly
799// and the original Send is unblocked later.
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900800// We also test that the send call stacks unwind correctly when the channel
801// pumps messages while waiting for a response.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900802TEST_F(IPCSyncChannelTest, QueuedReply) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900803 QueuedReply(false);
804 QueuedReply(true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900805}
806
807//-----------------------------------------------------------------------------
808
809namespace {
810
811class BadServer : public Worker {
812 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900813 explicit BadServer(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900814 : Worker(Channel::MODE_SERVER, "simpler_server"),
815 pump_during_send_(pump_during_send) { }
816 void Run() {
817 int answer = 0;
818
819 SyncMessage* msg = new SyncMessage(
820 MSG_ROUTING_CONTROL, SyncChannelTestMsg_Double::ID,
821 Message::PRIORITY_NORMAL, NULL);
822 if (pump_during_send_)
823 msg->EnableMessagePumping();
824
825 // Temporarily set the minimum logging very high so that the assertion
826 // in ipc_message_utils doesn't fire.
827 int log_level = logging::GetMinLogLevel();
828 logging::SetMinLogLevel(kint32max);
829 bool result = Send(msg);
830 logging::SetMinLogLevel(log_level);
831 DCHECK(!result);
832
833 // Need to send another message to get the client to call Done().
834 result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
835 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900836 DCHECK_EQ(answer, 42);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900837
838 Done();
839 }
840
841 bool pump_during_send_;
842};
843
844void BadMessage(bool pump_during_send) {
845 std::vector<Worker*> workers;
846 workers.push_back(new BadServer(pump_during_send));
847 workers.push_back(new SimpleClient());
848 RunTest(workers);
849}
850
851} // namespace
852
853// Tests that if a message is not serialized correctly, the Send() will fail.
854TEST_F(IPCSyncChannelTest, BadMessage) {
855 BadMessage(false);
856 BadMessage(true);
857}
858
859//-----------------------------------------------------------------------------
860
861namespace {
862
863class ChattyClient : public Worker {
864 public:
865 ChattyClient() :
866 Worker(Channel::MODE_CLIENT, "chatty_client") { }
867
868 void OnAnswer(int* answer) {
869 // The PostMessage limit is 10k. Send 20% more than that.
870 const int kMessageLimit = 10000;
871 const int kMessagesToSend = kMessageLimit * 120 / 100;
872 for (int i = 0; i < kMessagesToSend; ++i) {
873 if (!SendDouble(false, true))
874 break;
875 }
876 *answer = 42;
877 Done();
878 }
879};
880
881void ChattyServer(bool pump_during_send) {
882 std::vector<Worker*> workers;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900883 workers.push_back(new UnblockServer(pump_during_send, false));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900884 workers.push_back(new ChattyClient());
885 RunTest(workers);
886}
887
888} // namespace
889
890// Tests http://b/1093251 - that sending lots of sync messages while
891// the receiver is waiting for a sync reply does not overflow the PostMessage
892// queue.
893TEST_F(IPCSyncChannelTest, ChattyServer) {
894 ChattyServer(false);
895 ChattyServer(true);
896}
897
898//------------------------------------------------------------------------------
899
900namespace {
901
902class TimeoutServer : public Worker {
903 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900904 TimeoutServer(int timeout_ms,
905 std::vector<bool> timeout_seq,
906 bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900907 : Worker(Channel::MODE_SERVER, "timeout_server"),
908 timeout_ms_(timeout_ms),
909 timeout_seq_(timeout_seq),
910 pump_during_send_(pump_during_send) {
911 }
912
913 void Run() {
914 for (std::vector<bool>::const_iterator iter = timeout_seq_.begin();
915 iter != timeout_seq_.end(); ++iter) {
916 SendAnswerToLife(pump_during_send_, timeout_ms_, !*iter);
917 }
918 Done();
919 }
920
921 private:
922 int timeout_ms_;
923 std::vector<bool> timeout_seq_;
924 bool pump_during_send_;
925};
926
927class UnresponsiveClient : public Worker {
928 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900929 explicit UnresponsiveClient(std::vector<bool> timeout_seq)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900930 : Worker(Channel::MODE_CLIENT, "unresponsive_client"),
931 timeout_seq_(timeout_seq) {
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900932 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900933
934 void OnAnswerDelay(Message* reply_msg) {
935 DCHECK(!timeout_seq_.empty());
936 if (!timeout_seq_[0]) {
937 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
938 Send(reply_msg);
939 } else {
940 // Don't reply.
941 delete reply_msg;
942 }
943 timeout_seq_.erase(timeout_seq_.begin());
944 if (timeout_seq_.empty())
945 Done();
946 }
947
948 private:
949 // Whether we should time-out or respond to the various messages we receive.
950 std::vector<bool> timeout_seq_;
951};
952
953void SendWithTimeoutOK(bool pump_during_send) {
954 std::vector<Worker*> workers;
955 std::vector<bool> timeout_seq;
956 timeout_seq.push_back(false);
957 timeout_seq.push_back(false);
958 timeout_seq.push_back(false);
959 workers.push_back(new TimeoutServer(5000, timeout_seq, pump_during_send));
960 workers.push_back(new SimpleClient());
961 RunTest(workers);
962}
963
964void SendWithTimeoutTimeout(bool pump_during_send) {
965 std::vector<Worker*> workers;
966 std::vector<bool> timeout_seq;
967 timeout_seq.push_back(true);
968 timeout_seq.push_back(false);
969 timeout_seq.push_back(false);
970 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
971 workers.push_back(new UnresponsiveClient(timeout_seq));
972 RunTest(workers);
973}
974
975void SendWithTimeoutMixedOKAndTimeout(bool pump_during_send) {
976 std::vector<Worker*> workers;
977 std::vector<bool> timeout_seq;
978 timeout_seq.push_back(true);
979 timeout_seq.push_back(false);
980 timeout_seq.push_back(false);
981 timeout_seq.push_back(true);
982 timeout_seq.push_back(false);
983 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
984 workers.push_back(new UnresponsiveClient(timeout_seq));
985 RunTest(workers);
986}
987
988} // namespace
989
990// Tests that SendWithTimeout does not time-out if the response comes back fast
991// enough.
992TEST_F(IPCSyncChannelTest, SendWithTimeoutOK) {
993 SendWithTimeoutOK(false);
994 SendWithTimeoutOK(true);
995}
996
997// Tests that SendWithTimeout does time-out.
998TEST_F(IPCSyncChannelTest, SendWithTimeoutTimeout) {
999 SendWithTimeoutTimeout(false);
1000 SendWithTimeoutTimeout(true);
1001}
1002
1003// Sends some message that time-out and some that succeed.
1004TEST_F(IPCSyncChannelTest, SendWithTimeoutMixedOKAndTimeout) {
1005 SendWithTimeoutMixedOKAndTimeout(false);
1006 SendWithTimeoutMixedOKAndTimeout(true);
1007}
1008
1009//------------------------------------------------------------------------------
1010
1011namespace {
1012
1013class NestedTask : public Task {
1014 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +09001015 explicit NestedTask(Worker* server) : server_(server) { }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001016 void Run() {
1017 // Sleep a bit so that we wake up after the reply has been received.
1018 PlatformThread::Sleep(250);
1019 server_->SendAnswerToLife(true, base::kNoTimeout, true);
1020 }
1021
1022 Worker* server_;
1023};
1024
1025static bool timeout_occured = false;
1026
1027class TimeoutTask : public Task {
1028 public:
1029 void Run() {
1030 timeout_occured = true;
1031 }
1032};
1033
1034class DoneEventRaceServer : public Worker {
1035 public:
1036 DoneEventRaceServer()
1037 : Worker(Channel::MODE_SERVER, "done_event_race_server") { }
1038
1039 void Run() {
1040 MessageLoop::current()->PostTask(FROM_HERE, new NestedTask(this));
1041 MessageLoop::current()->PostDelayedTask(FROM_HERE, new TimeoutTask(), 9000);
1042 // Even though we have a timeout on the Send, it will succeed since for this
1043 // bug, the reply message comes back and is deserialized, however the done
1044 // event wasn't set. So we indirectly use the timeout task to notice if a
1045 // timeout occurred.
1046 SendAnswerToLife(true, 10000, true);
1047 DCHECK(!timeout_occured);
1048 Done();
1049 }
1050};
1051
1052} // namespace
1053
1054// Tests http://b/1474092 - that if after the done_event is set but before
1055// OnObjectSignaled is called another message is sent out, then after its
1056// reply comes back OnObjectSignaled will be called for the first message.
1057TEST_F(IPCSyncChannelTest, DoneEventRace) {
1058 std::vector<Worker*> workers;
1059 workers.push_back(new DoneEventRaceServer());
1060 workers.push_back(new SimpleClient());
1061 RunTest(workers);
1062}
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001063
1064//-----------------------------------------------------------------------------
1065
1066namespace {
1067
1068class TestSyncMessageFilter : public IPC::SyncMessageFilter {
1069 public:
1070 TestSyncMessageFilter(base::WaitableEvent* shutdown_event, Worker* worker)
1071 : SyncMessageFilter(shutdown_event),
1072 worker_(worker),
1073 thread_("helper_thread") {
1074 base::Thread::Options options;
1075 options.message_loop_type = MessageLoop::TYPE_DEFAULT;
1076 thread_.StartWithOptions(options);
1077 }
1078
1079 virtual void OnFilterAdded(Channel* channel) {
1080 SyncMessageFilter::OnFilterAdded(channel);
1081 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
1082 this, &TestSyncMessageFilter::SendMessageOnHelperThread));
1083 }
1084
1085 void SendMessageOnHelperThread() {
1086 int answer = 0;
1087 bool result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
1088 DCHECK(result);
1089 DCHECK_EQ(answer, 42);
1090
1091 worker_->Done();
1092 }
1093
1094 Worker* worker_;
1095 base::Thread thread_;
1096};
1097
1098class SyncMessageFilterServer : public Worker {
1099 public:
1100 SyncMessageFilterServer()
1101 : Worker(Channel::MODE_SERVER, "sync_message_filter_server") {
1102 filter_ = new TestSyncMessageFilter(shutdown_event(), this);
1103 }
1104
1105 void Run() {
1106 channel()->AddFilter(filter_.get());
1107 }
1108
1109 scoped_refptr<TestSyncMessageFilter> filter_;
1110};
1111
ananta@chromium.org999f2972010-09-03 06:45:50 +09001112// This class provides functionality to test the case that a Send on the sync
1113// channel does not crash after the channel has been closed.
1114class ServerSendAfterClose : public Worker {
1115 public:
1116 ServerSendAfterClose()
1117 : Worker(Channel::MODE_SERVER, "simpler_server"),
1118 send_result_(true) {
1119 }
1120
1121 bool SendDummy() {
1122 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
1123 this, &ServerSendAfterClose::Send, new SyncChannelTestMsg_NoArgs));
1124 return true;
1125 }
1126
1127 bool send_result() const {
1128 return send_result_;
1129 }
1130
1131 private:
1132 virtual void Run() {
1133 CloseChannel();
1134 Done();
1135 }
1136
1137 bool Send(Message* msg) {
1138 send_result_ = Worker::Send(msg);
1139 Done();
1140 return send_result_;
1141 }
1142
1143 bool send_result_;
1144};
1145
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001146} // namespace
1147
1148// Tests basic synchronous call
1149TEST_F(IPCSyncChannelTest, SyncMessageFilter) {
1150 std::vector<Worker*> workers;
1151 workers.push_back(new SyncMessageFilterServer());
1152 workers.push_back(new SimpleClient());
1153 RunTest(workers);
1154}
ananta@chromium.org999f2972010-09-03 06:45:50 +09001155
1156// Test the case when the channel is closed and a Send is attempted after that.
1157TEST_F(IPCSyncChannelTest, SendAfterClose) {
1158 ServerSendAfterClose server;
1159 server.Start();
1160
1161 server.done_event()->Wait();
1162 server.done_event()->Reset();
1163
1164 server.SendDummy();
1165 server.done_event()->Wait();
1166
1167 EXPECT_FALSE(server.send_result());
1168}
1169
1170