blob: e580ba4340291b14485dd1785ca55a114f4066ea [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
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +09007#include "ipc/ipc_sync_channel.h"
8
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09009#include <string>
10#include <vector>
11
12#include "base/basictypes.h"
13#include "base/logging.h"
14#include "base/message_loop.h"
15#include "base/platform_thread.h"
erg@chromium.orga7528522010-07-16 02:23:23 +090016#include "base/scoped_ptr.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090017#include "base/stl_util-inl.h"
18#include "base/string_util.h"
timurrrr@chromium.orgf39c3ff2010-05-14 17:24:42 +090019#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090020#include "base/thread.h"
21#include "base/waitable_event.h"
22#include "ipc/ipc_message.h"
jabdelmalek@google.comeb921652010-04-07 05:33:36 +090023#include "ipc/ipc_sync_message_filter.h"
jam@chromium.org86a8de12010-12-09 08:34:16 +090024#include "ipc/ipc_sync_message_unittest.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090025#include "testing/gtest/include/gtest/gtest.h"
26
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090027using namespace IPC;
28using base::WaitableEvent;
29
30namespace {
31
32// Base class for a "process" with listener and IPC threads.
33class Worker : public Channel::Listener, public Message::Sender {
34 public:
35 // Will create a channel without a name.
36 Worker(Channel::Mode mode, const std::string& thread_name)
37 : done_(new WaitableEvent(false, false)),
38 channel_created_(new WaitableEvent(false, false)),
39 mode_(mode),
40 ipc_thread_((thread_name + "_ipc").c_str()),
41 listener_thread_((thread_name + "_listener").c_str()),
42 overrided_thread_(NULL),
timurrrr@chromium.org03100a82009-10-27 20:28:58 +090043 shutdown_event_(true, false) {
44 // The data race on vfptr is real but is very hard
45 // to suppress using standard Valgrind mechanism (suppressions).
46 // We have to use ANNOTATE_BENIGN_RACE to hide the reports and
47 // make ThreadSanitizer bots green.
48 ANNOTATE_BENIGN_RACE(this, "Race on vfptr, http://crbug.com/25841");
49 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090050
51 // Will create a named channel and use this name for the threads' name.
52 Worker(const std::string& channel_name, Channel::Mode mode)
53 : done_(new WaitableEvent(false, false)),
54 channel_created_(new WaitableEvent(false, false)),
55 channel_name_(channel_name),
56 mode_(mode),
57 ipc_thread_((channel_name + "_ipc").c_str()),
58 listener_thread_((channel_name + "_listener").c_str()),
59 overrided_thread_(NULL),
timurrrr@chromium.org03100a82009-10-27 20:28:58 +090060 shutdown_event_(true, false) {
61 // The data race on vfptr is real but is very hard
62 // to suppress using standard Valgrind mechanism (suppressions).
63 // We have to use ANNOTATE_BENIGN_RACE to hide the reports and
64 // make ThreadSanitizer bots green.
65 ANNOTATE_BENIGN_RACE(this, "Race on vfptr, http://crbug.com/25841");
66 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090067
68 // The IPC thread needs to outlive SyncChannel, so force the correct order of
69 // destruction.
70 virtual ~Worker() {
71 WaitableEvent listener_done(false, false), ipc_done(false, false);
72 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
73 this, &Worker::OnListenerThreadShutdown1, &listener_done,
74 &ipc_done));
75 listener_done.Wait();
76 ipc_done.Wait();
77 ipc_thread_.Stop();
78 listener_thread_.Stop();
79 }
80 void AddRef() { }
81 void Release() { }
darin@chromium.org5cb996e2009-09-30 13:29:20 +090082 static bool ImplementsThreadSafeReferenceCounting() { return true; }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090083 bool Send(Message* msg) { return channel_->Send(msg); }
84 bool SendWithTimeout(Message* msg, int timeout_ms) {
85 return channel_->SendWithTimeout(msg, timeout_ms);
86 }
87 void WaitForChannelCreation() { channel_created_->Wait(); }
88 void CloseChannel() {
89 DCHECK(MessageLoop::current() == ListenerThread()->message_loop());
90 channel_->Close();
91 }
92 void Start() {
93 StartThread(&listener_thread_, MessageLoop::TYPE_DEFAULT);
94 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
95 this, &Worker::OnStart));
96 }
97 void OverrideThread(base::Thread* overrided_thread) {
98 DCHECK(overrided_thread_ == NULL);
99 overrided_thread_ = overrided_thread;
100 }
101 bool SendAnswerToLife(bool pump, int timeout, bool succeed) {
102 int answer = 0;
103 SyncMessage* msg = new SyncChannelTestMsg_AnswerToLife(&answer);
104 if (pump)
105 msg->EnableMessagePumping();
106 bool result = SendWithTimeout(msg, timeout);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900107 DCHECK_EQ(result, succeed);
108 DCHECK_EQ(answer, (succeed ? 42 : 0));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900109 return result;
110 }
111 bool SendDouble(bool pump, bool succeed) {
112 int answer = 0;
113 SyncMessage* msg = new SyncChannelTestMsg_Double(5, &answer);
114 if (pump)
115 msg->EnableMessagePumping();
116 bool result = Send(msg);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900117 DCHECK_EQ(result, succeed);
118 DCHECK_EQ(answer, (succeed ? 10 : 0));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900119 return result;
120 }
121 Channel::Mode mode() { return mode_; }
122 WaitableEvent* done_event() { return done_.get(); }
jabdelmalek@google.comeb921652010-04-07 05:33:36 +0900123 WaitableEvent* shutdown_event() { return &shutdown_event_; }
jam@chromium.orgebd07182009-12-01 11:34:18 +0900124 void ResetChannel() { channel_.reset(); }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900125 // Derived classes need to call this when they've completed their part of
126 // the test.
127 void Done() { done_->Signal(); }
jabdelmalek@google.comeb921652010-04-07 05:33:36 +0900128
129 protected:
130 IPC::SyncChannel* channel() { return channel_.get(); }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900131 // Functions for dervied classes to implement if they wish.
132 virtual void Run() { }
133 virtual void OnAnswer(int* answer) { NOTREACHED(); }
134 virtual void OnAnswerDelay(Message* reply_msg) {
135 // The message handler map below can only take one entry for
136 // SyncChannelTestMsg_AnswerToLife, so since some classes want
137 // the normal version while other want the delayed reply, we
138 // call the normal version if the derived class didn't override
139 // this function.
140 int answer;
141 OnAnswer(&answer);
142 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, answer);
143 Send(reply_msg);
144 }
145 virtual void OnDouble(int in, int* out) { NOTREACHED(); }
146 virtual void OnDoubleDelay(int in, Message* reply_msg) {
147 int result;
148 OnDouble(in, &result);
149 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, result);
150 Send(reply_msg);
151 }
152
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900153 virtual void OnNestedTestMsg(Message* reply_msg) {
154 NOTREACHED();
155 }
156
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900157 base::Thread* ListenerThread() {
158 return overrided_thread_ ? overrided_thread_ : &listener_thread_;
159 }
ananta@chromium.org999f2972010-09-03 06:45:50 +0900160
161 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900162 // Called on the listener thread to create the sync channel.
163 void OnStart() {
164 // Link ipc_thread_, listener_thread_ and channel_ altogether.
165 StartThread(&ipc_thread_, MessageLoop::TYPE_IO);
166 channel_.reset(new SyncChannel(
jam@chromium.orge57135c2010-12-03 04:16:07 +0900167 channel_name_, mode_, this, ipc_thread_.message_loop(), true,
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900168 &shutdown_event_));
169 channel_created_->Signal();
170 Run();
171 }
172
173 void OnListenerThreadShutdown1(WaitableEvent* listener_event,
174 WaitableEvent* ipc_event) {
175 // SyncChannel needs to be destructed on the thread that it was created on.
176 channel_.reset();
177
178 MessageLoop::current()->RunAllPending();
179
180 ipc_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
181 this, &Worker::OnIPCThreadShutdown, listener_event, ipc_event));
182 }
183
184 void OnIPCThreadShutdown(WaitableEvent* listener_event,
185 WaitableEvent* ipc_event) {
186 MessageLoop::current()->RunAllPending();
187 ipc_event->Signal();
188
189 listener_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
190 this, &Worker::OnListenerThreadShutdown2, listener_event));
191 }
192
193 void OnListenerThreadShutdown2(WaitableEvent* listener_event) {
194 MessageLoop::current()->RunAllPending();
195 listener_event->Signal();
196 }
197
jam@chromium.org8a2c7842010-12-24 15:19:28 +0900198 bool OnMessageReceived(const Message& message) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900199 IPC_BEGIN_MESSAGE_MAP(Worker, message)
200 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_Double, OnDoubleDelay)
201 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_AnswerToLife,
202 OnAnswerDelay)
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900203 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelNestedTestMsg_String,
204 OnNestedTestMsg)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900205 IPC_END_MESSAGE_MAP()
jam@chromium.org8a2c7842010-12-24 15:19:28 +0900206 return true;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900207 }
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) {
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900706 VLOG(1) << __FUNCTION__ << " Sending reply: " << reply_text_;
707 SyncChannelNestedTestMsg_String::WriteReplyParams(reply_msg, reply_text_);
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900708 Send(reply_msg);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900709 Done();
710 }
711
712 private:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900713 std::string reply_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900714};
715
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900716// The QueuedReplyClient class provides functionality to test the case where
717// multiple sync channels are in use on the same thread and they make nested
718// sync calls, i.e. while the first channel waits for a response it makes a
719// sync call on another channel.
720// The callstack should unwind correctly, i.e. the outermost call should
721// complete first, and so on.
722class QueuedReplyClient : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900723 public:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900724 QueuedReplyClient(base::Thread* listener_thread,
725 const std::string& channel_name,
726 const std::string& expected_text,
727 bool pump_during_send)
728 : Worker(channel_name, Channel::MODE_CLIENT),
thomasvl@google.com9a242072010-07-23 23:18:59 +0900729 pump_during_send_(pump_during_send),
730 expected_text_(expected_text) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900731 Worker::OverrideThread(listener_thread);
732 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900733
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900734 virtual void Run() {
735 std::string response;
736 SyncMessage* msg = new SyncChannelNestedTestMsg_String(&response);
737 if (pump_during_send_)
738 msg->EnableMessagePumping();
739 bool result = Send(msg);
740 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900741 DCHECK_EQ(response, expected_text_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900742
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900743 VLOG(1) << __FUNCTION__ << " Received reply: " << response;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900744 Done();
745 }
746
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900747 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900748 bool pump_during_send_;
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900749 std::string expected_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900750};
751
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900752void QueuedReply(bool client_pump) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900753 std::vector<Worker*> workers;
754
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900755 // A shared worker thread for servers
756 base::Thread server_worker_thread("QueuedReply_ServerListener");
757 ASSERT_TRUE(server_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900758
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900759 base::Thread client_worker_thread("QueuedReply_ClientListener");
760 ASSERT_TRUE(client_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900761
762 Worker* worker;
763
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900764 worker = new QueuedReplyServer(&server_worker_thread,
765 "QueuedReply_Server1",
766 "Got first message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900767 workers.push_back(worker);
768
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900769 worker = new QueuedReplyServer(&server_worker_thread,
770 "QueuedReply_Server2",
771 "Got second 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 QueuedReplyClient(&client_worker_thread,
775 "QueuedReply_Server1",
776 "Got first message",
777 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900778 workers.push_back(worker);
779
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900780 worker = new QueuedReplyClient(&client_worker_thread,
781 "QueuedReply_Server2",
782 "Got second message",
783 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900784 workers.push_back(worker);
785
786 RunTest(workers);
787}
788
789} // namespace
790
791// While a blocking send is in progress, the listener thread might answer other
792// synchronous messages. This tests that if during the response to another
793// message the reply to the original messages comes, it is queued up correctly
794// and the original Send is unblocked later.
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900795// We also test that the send call stacks unwind correctly when the channel
796// pumps messages while waiting for a response.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900797TEST_F(IPCSyncChannelTest, QueuedReply) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900798 QueuedReply(false);
799 QueuedReply(true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900800}
801
802//-----------------------------------------------------------------------------
803
804namespace {
805
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900806void DropAssert(const std::string&) {}
807
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900808class BadServer : public Worker {
809 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900810 explicit BadServer(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900811 : Worker(Channel::MODE_SERVER, "simpler_server"),
812 pump_during_send_(pump_during_send) { }
813 void Run() {
814 int answer = 0;
815
816 SyncMessage* msg = new SyncMessage(
817 MSG_ROUTING_CONTROL, SyncChannelTestMsg_Double::ID,
818 Message::PRIORITY_NORMAL, NULL);
819 if (pump_during_send_)
820 msg->EnableMessagePumping();
821
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900822 // Temporarily ignore asserts so that the assertion in
823 // ipc_message_utils doesn't cause termination.
824 logging::SetLogAssertHandler(&DropAssert);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900825 bool result = Send(msg);
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900826 logging::SetLogAssertHandler(NULL);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900827 DCHECK(!result);
828
829 // Need to send another message to get the client to call Done().
830 result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
831 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900832 DCHECK_EQ(answer, 42);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900833
834 Done();
835 }
836
837 bool pump_during_send_;
838};
839
840void BadMessage(bool pump_during_send) {
841 std::vector<Worker*> workers;
842 workers.push_back(new BadServer(pump_during_send));
843 workers.push_back(new SimpleClient());
844 RunTest(workers);
845}
846
847} // namespace
848
849// Tests that if a message is not serialized correctly, the Send() will fail.
850TEST_F(IPCSyncChannelTest, BadMessage) {
851 BadMessage(false);
852 BadMessage(true);
853}
854
855//-----------------------------------------------------------------------------
856
857namespace {
858
859class ChattyClient : public Worker {
860 public:
861 ChattyClient() :
862 Worker(Channel::MODE_CLIENT, "chatty_client") { }
863
864 void OnAnswer(int* answer) {
865 // The PostMessage limit is 10k. Send 20% more than that.
866 const int kMessageLimit = 10000;
867 const int kMessagesToSend = kMessageLimit * 120 / 100;
868 for (int i = 0; i < kMessagesToSend; ++i) {
869 if (!SendDouble(false, true))
870 break;
871 }
872 *answer = 42;
873 Done();
874 }
875};
876
877void ChattyServer(bool pump_during_send) {
878 std::vector<Worker*> workers;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900879 workers.push_back(new UnblockServer(pump_during_send, false));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900880 workers.push_back(new ChattyClient());
881 RunTest(workers);
882}
883
884} // namespace
885
886// Tests http://b/1093251 - that sending lots of sync messages while
887// the receiver is waiting for a sync reply does not overflow the PostMessage
888// queue.
889TEST_F(IPCSyncChannelTest, ChattyServer) {
890 ChattyServer(false);
891 ChattyServer(true);
892}
893
894//------------------------------------------------------------------------------
895
896namespace {
897
898class TimeoutServer : public Worker {
899 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900900 TimeoutServer(int timeout_ms,
901 std::vector<bool> timeout_seq,
902 bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900903 : Worker(Channel::MODE_SERVER, "timeout_server"),
904 timeout_ms_(timeout_ms),
905 timeout_seq_(timeout_seq),
906 pump_during_send_(pump_during_send) {
907 }
908
909 void Run() {
910 for (std::vector<bool>::const_iterator iter = timeout_seq_.begin();
911 iter != timeout_seq_.end(); ++iter) {
912 SendAnswerToLife(pump_during_send_, timeout_ms_, !*iter);
913 }
914 Done();
915 }
916
917 private:
918 int timeout_ms_;
919 std::vector<bool> timeout_seq_;
920 bool pump_during_send_;
921};
922
923class UnresponsiveClient : public Worker {
924 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900925 explicit UnresponsiveClient(std::vector<bool> timeout_seq)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900926 : Worker(Channel::MODE_CLIENT, "unresponsive_client"),
927 timeout_seq_(timeout_seq) {
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900928 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900929
930 void OnAnswerDelay(Message* reply_msg) {
931 DCHECK(!timeout_seq_.empty());
932 if (!timeout_seq_[0]) {
933 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
934 Send(reply_msg);
935 } else {
936 // Don't reply.
937 delete reply_msg;
938 }
939 timeout_seq_.erase(timeout_seq_.begin());
940 if (timeout_seq_.empty())
941 Done();
942 }
943
944 private:
945 // Whether we should time-out or respond to the various messages we receive.
946 std::vector<bool> timeout_seq_;
947};
948
949void SendWithTimeoutOK(bool pump_during_send) {
950 std::vector<Worker*> workers;
951 std::vector<bool> timeout_seq;
952 timeout_seq.push_back(false);
953 timeout_seq.push_back(false);
954 timeout_seq.push_back(false);
955 workers.push_back(new TimeoutServer(5000, timeout_seq, pump_during_send));
956 workers.push_back(new SimpleClient());
957 RunTest(workers);
958}
959
960void SendWithTimeoutTimeout(bool pump_during_send) {
961 std::vector<Worker*> workers;
962 std::vector<bool> timeout_seq;
963 timeout_seq.push_back(true);
964 timeout_seq.push_back(false);
965 timeout_seq.push_back(false);
966 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
967 workers.push_back(new UnresponsiveClient(timeout_seq));
968 RunTest(workers);
969}
970
971void SendWithTimeoutMixedOKAndTimeout(bool pump_during_send) {
972 std::vector<Worker*> workers;
973 std::vector<bool> timeout_seq;
974 timeout_seq.push_back(true);
975 timeout_seq.push_back(false);
976 timeout_seq.push_back(false);
977 timeout_seq.push_back(true);
978 timeout_seq.push_back(false);
979 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
980 workers.push_back(new UnresponsiveClient(timeout_seq));
981 RunTest(workers);
982}
983
984} // namespace
985
986// Tests that SendWithTimeout does not time-out if the response comes back fast
987// enough.
988TEST_F(IPCSyncChannelTest, SendWithTimeoutOK) {
989 SendWithTimeoutOK(false);
990 SendWithTimeoutOK(true);
991}
992
993// Tests that SendWithTimeout does time-out.
994TEST_F(IPCSyncChannelTest, SendWithTimeoutTimeout) {
995 SendWithTimeoutTimeout(false);
996 SendWithTimeoutTimeout(true);
997}
998
999// Sends some message that time-out and some that succeed.
1000TEST_F(IPCSyncChannelTest, SendWithTimeoutMixedOKAndTimeout) {
1001 SendWithTimeoutMixedOKAndTimeout(false);
1002 SendWithTimeoutMixedOKAndTimeout(true);
1003}
1004
1005//------------------------------------------------------------------------------
1006
1007namespace {
1008
1009class NestedTask : public Task {
1010 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +09001011 explicit NestedTask(Worker* server) : server_(server) { }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001012 void Run() {
1013 // Sleep a bit so that we wake up after the reply has been received.
1014 PlatformThread::Sleep(250);
1015 server_->SendAnswerToLife(true, base::kNoTimeout, true);
1016 }
1017
1018 Worker* server_;
1019};
1020
1021static bool timeout_occured = false;
1022
1023class TimeoutTask : public Task {
1024 public:
1025 void Run() {
1026 timeout_occured = true;
1027 }
1028};
1029
1030class DoneEventRaceServer : public Worker {
1031 public:
1032 DoneEventRaceServer()
1033 : Worker(Channel::MODE_SERVER, "done_event_race_server") { }
1034
1035 void Run() {
1036 MessageLoop::current()->PostTask(FROM_HERE, new NestedTask(this));
1037 MessageLoop::current()->PostDelayedTask(FROM_HERE, new TimeoutTask(), 9000);
1038 // Even though we have a timeout on the Send, it will succeed since for this
1039 // bug, the reply message comes back and is deserialized, however the done
1040 // event wasn't set. So we indirectly use the timeout task to notice if a
1041 // timeout occurred.
1042 SendAnswerToLife(true, 10000, true);
1043 DCHECK(!timeout_occured);
1044 Done();
1045 }
1046};
1047
1048} // namespace
1049
1050// Tests http://b/1474092 - that if after the done_event is set but before
1051// OnObjectSignaled is called another message is sent out, then after its
1052// reply comes back OnObjectSignaled will be called for the first message.
1053TEST_F(IPCSyncChannelTest, DoneEventRace) {
1054 std::vector<Worker*> workers;
1055 workers.push_back(new DoneEventRaceServer());
1056 workers.push_back(new SimpleClient());
1057 RunTest(workers);
1058}
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001059
1060//-----------------------------------------------------------------------------
1061
1062namespace {
1063
1064class TestSyncMessageFilter : public IPC::SyncMessageFilter {
1065 public:
1066 TestSyncMessageFilter(base::WaitableEvent* shutdown_event, Worker* worker)
1067 : SyncMessageFilter(shutdown_event),
1068 worker_(worker),
1069 thread_("helper_thread") {
1070 base::Thread::Options options;
1071 options.message_loop_type = MessageLoop::TYPE_DEFAULT;
1072 thread_.StartWithOptions(options);
1073 }
1074
1075 virtual void OnFilterAdded(Channel* channel) {
1076 SyncMessageFilter::OnFilterAdded(channel);
1077 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
1078 this, &TestSyncMessageFilter::SendMessageOnHelperThread));
1079 }
1080
1081 void SendMessageOnHelperThread() {
1082 int answer = 0;
1083 bool result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
1084 DCHECK(result);
1085 DCHECK_EQ(answer, 42);
1086
1087 worker_->Done();
1088 }
1089
1090 Worker* worker_;
1091 base::Thread thread_;
1092};
1093
1094class SyncMessageFilterServer : public Worker {
1095 public:
1096 SyncMessageFilterServer()
1097 : Worker(Channel::MODE_SERVER, "sync_message_filter_server") {
1098 filter_ = new TestSyncMessageFilter(shutdown_event(), this);
1099 }
1100
1101 void Run() {
1102 channel()->AddFilter(filter_.get());
1103 }
1104
1105 scoped_refptr<TestSyncMessageFilter> filter_;
1106};
1107
ananta@chromium.org999f2972010-09-03 06:45:50 +09001108// This class provides functionality to test the case that a Send on the sync
1109// channel does not crash after the channel has been closed.
1110class ServerSendAfterClose : public Worker {
1111 public:
1112 ServerSendAfterClose()
1113 : Worker(Channel::MODE_SERVER, "simpler_server"),
1114 send_result_(true) {
1115 }
1116
1117 bool SendDummy() {
1118 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
1119 this, &ServerSendAfterClose::Send, new SyncChannelTestMsg_NoArgs));
1120 return true;
1121 }
1122
1123 bool send_result() const {
1124 return send_result_;
1125 }
1126
1127 private:
1128 virtual void Run() {
1129 CloseChannel();
1130 Done();
1131 }
1132
1133 bool Send(Message* msg) {
1134 send_result_ = Worker::Send(msg);
1135 Done();
1136 return send_result_;
1137 }
1138
1139 bool send_result_;
1140};
1141
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001142} // namespace
1143
1144// Tests basic synchronous call
1145TEST_F(IPCSyncChannelTest, SyncMessageFilter) {
1146 std::vector<Worker*> workers;
1147 workers.push_back(new SyncMessageFilterServer());
1148 workers.push_back(new SimpleClient());
1149 RunTest(workers);
1150}
ananta@chromium.org999f2972010-09-03 06:45:50 +09001151
1152// Test the case when the channel is closed and a Send is attempted after that.
1153TEST_F(IPCSyncChannelTest, SendAfterClose) {
1154 ServerSendAfterClose server;
1155 server.Start();
1156
1157 server.done_event()->Wait();
1158 server.done_event()->Reset();
1159
1160 server.SendDummy();
1161 server.done_event()->Wait();
1162
1163 EXPECT_FALSE(server.send_result());
1164}
1165
1166