blob: 561714665d519469341d36d437d48b1373e158b7 [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"
jam@chromium.org86a8de12010-12-09 08:34:16 +090023#include "ipc/ipc_sync_message_unittest.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090024#include "testing/gtest/include/gtest/gtest.h"
25
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090026using namespace IPC;
27using base::WaitableEvent;
28
29namespace {
30
31// Base class for a "process" with listener and IPC threads.
32class Worker : public Channel::Listener, public Message::Sender {
33 public:
34 // Will create a channel without a name.
35 Worker(Channel::Mode mode, const std::string& thread_name)
36 : done_(new WaitableEvent(false, false)),
37 channel_created_(new WaitableEvent(false, false)),
38 mode_(mode),
39 ipc_thread_((thread_name + "_ipc").c_str()),
40 listener_thread_((thread_name + "_listener").c_str()),
41 overrided_thread_(NULL),
timurrrr@chromium.org03100a82009-10-27 20:28:58 +090042 shutdown_event_(true, false) {
43 // The data race on vfptr is real but is very hard
44 // to suppress using standard Valgrind mechanism (suppressions).
45 // We have to use ANNOTATE_BENIGN_RACE to hide the reports and
46 // make ThreadSanitizer bots green.
47 ANNOTATE_BENIGN_RACE(this, "Race on vfptr, http://crbug.com/25841");
48 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090049
50 // Will create a named channel and use this name for the threads' name.
51 Worker(const std::string& channel_name, Channel::Mode mode)
52 : done_(new WaitableEvent(false, false)),
53 channel_created_(new WaitableEvent(false, false)),
54 channel_name_(channel_name),
55 mode_(mode),
56 ipc_thread_((channel_name + "_ipc").c_str()),
57 listener_thread_((channel_name + "_listener").c_str()),
58 overrided_thread_(NULL),
timurrrr@chromium.org03100a82009-10-27 20:28:58 +090059 shutdown_event_(true, false) {
60 // The data race on vfptr is real but is very hard
61 // to suppress using standard Valgrind mechanism (suppressions).
62 // We have to use ANNOTATE_BENIGN_RACE to hide the reports and
63 // make ThreadSanitizer bots green.
64 ANNOTATE_BENIGN_RACE(this, "Race on vfptr, http://crbug.com/25841");
65 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090066
67 // The IPC thread needs to outlive SyncChannel, so force the correct order of
68 // destruction.
69 virtual ~Worker() {
70 WaitableEvent listener_done(false, false), ipc_done(false, false);
71 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
72 this, &Worker::OnListenerThreadShutdown1, &listener_done,
73 &ipc_done));
74 listener_done.Wait();
75 ipc_done.Wait();
76 ipc_thread_.Stop();
77 listener_thread_.Stop();
78 }
79 void AddRef() { }
80 void Release() { }
darin@chromium.org5cb996e2009-09-30 13:29:20 +090081 static bool ImplementsThreadSafeReferenceCounting() { return true; }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090082 bool Send(Message* msg) { return channel_->Send(msg); }
83 bool SendWithTimeout(Message* msg, int timeout_ms) {
84 return channel_->SendWithTimeout(msg, timeout_ms);
85 }
86 void WaitForChannelCreation() { channel_created_->Wait(); }
87 void CloseChannel() {
88 DCHECK(MessageLoop::current() == ListenerThread()->message_loop());
89 channel_->Close();
90 }
91 void Start() {
92 StartThread(&listener_thread_, MessageLoop::TYPE_DEFAULT);
93 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
94 this, &Worker::OnStart));
95 }
96 void OverrideThread(base::Thread* overrided_thread) {
97 DCHECK(overrided_thread_ == NULL);
98 overrided_thread_ = overrided_thread;
99 }
100 bool SendAnswerToLife(bool pump, int timeout, bool succeed) {
101 int answer = 0;
102 SyncMessage* msg = new SyncChannelTestMsg_AnswerToLife(&answer);
103 if (pump)
104 msg->EnableMessagePumping();
105 bool result = SendWithTimeout(msg, timeout);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900106 DCHECK_EQ(result, succeed);
107 DCHECK_EQ(answer, (succeed ? 42 : 0));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900108 return result;
109 }
110 bool SendDouble(bool pump, bool succeed) {
111 int answer = 0;
112 SyncMessage* msg = new SyncChannelTestMsg_Double(5, &answer);
113 if (pump)
114 msg->EnableMessagePumping();
115 bool result = Send(msg);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900116 DCHECK_EQ(result, succeed);
117 DCHECK_EQ(answer, (succeed ? 10 : 0));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900118 return result;
119 }
120 Channel::Mode mode() { return mode_; }
121 WaitableEvent* done_event() { return done_.get(); }
jabdelmalek@google.comeb921652010-04-07 05:33:36 +0900122 WaitableEvent* shutdown_event() { return &shutdown_event_; }
jam@chromium.orgebd07182009-12-01 11:34:18 +0900123 void ResetChannel() { channel_.reset(); }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900124 // Derived classes need to call this when they've completed their part of
125 // the test.
126 void Done() { done_->Signal(); }
jabdelmalek@google.comeb921652010-04-07 05:33:36 +0900127
128 protected:
129 IPC::SyncChannel* channel() { return channel_.get(); }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900130 // Functions for dervied classes to implement if they wish.
131 virtual void Run() { }
132 virtual void OnAnswer(int* answer) { NOTREACHED(); }
133 virtual void OnAnswerDelay(Message* reply_msg) {
134 // The message handler map below can only take one entry for
135 // SyncChannelTestMsg_AnswerToLife, so since some classes want
136 // the normal version while other want the delayed reply, we
137 // call the normal version if the derived class didn't override
138 // this function.
139 int answer;
140 OnAnswer(&answer);
141 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, answer);
142 Send(reply_msg);
143 }
144 virtual void OnDouble(int in, int* out) { NOTREACHED(); }
145 virtual void OnDoubleDelay(int in, Message* reply_msg) {
146 int result;
147 OnDouble(in, &result);
148 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, result);
149 Send(reply_msg);
150 }
151
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900152 virtual void OnNestedTestMsg(Message* reply_msg) {
153 NOTREACHED();
154 }
155
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900156 base::Thread* ListenerThread() {
157 return overrided_thread_ ? overrided_thread_ : &listener_thread_;
158 }
ananta@chromium.org999f2972010-09-03 06:45:50 +0900159
160 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900161 // Called on the listener thread to create the sync channel.
162 void OnStart() {
163 // Link ipc_thread_, listener_thread_ and channel_ altogether.
164 StartThread(&ipc_thread_, MessageLoop::TYPE_IO);
165 channel_.reset(new SyncChannel(
jam@chromium.orge57135c2010-12-03 04:16:07 +0900166 channel_name_, mode_, this, ipc_thread_.message_loop(), true,
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900167 &shutdown_event_));
168 channel_created_->Signal();
169 Run();
170 }
171
172 void OnListenerThreadShutdown1(WaitableEvent* listener_event,
173 WaitableEvent* ipc_event) {
174 // SyncChannel needs to be destructed on the thread that it was created on.
175 channel_.reset();
176
177 MessageLoop::current()->RunAllPending();
178
179 ipc_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
180 this, &Worker::OnIPCThreadShutdown, listener_event, ipc_event));
181 }
182
183 void OnIPCThreadShutdown(WaitableEvent* listener_event,
184 WaitableEvent* ipc_event) {
185 MessageLoop::current()->RunAllPending();
186 ipc_event->Signal();
187
188 listener_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
189 this, &Worker::OnListenerThreadShutdown2, listener_event));
190 }
191
192 void OnListenerThreadShutdown2(WaitableEvent* listener_event) {
193 MessageLoop::current()->RunAllPending();
194 listener_event->Signal();
195 }
196
197 void OnMessageReceived(const Message& message) {
198 IPC_BEGIN_MESSAGE_MAP(Worker, message)
199 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_Double, OnDoubleDelay)
200 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_AnswerToLife,
201 OnAnswerDelay)
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900202 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelNestedTestMsg_String,
203 OnNestedTestMsg)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900204 IPC_END_MESSAGE_MAP()
205 }
206
207 void StartThread(base::Thread* thread, MessageLoop::Type type) {
208 base::Thread::Options options;
209 options.message_loop_type = type;
210 thread->StartWithOptions(options);
211 }
212
213 scoped_ptr<WaitableEvent> done_;
214 scoped_ptr<WaitableEvent> channel_created_;
215 std::string channel_name_;
216 Channel::Mode mode_;
217 scoped_ptr<SyncChannel> channel_;
218 base::Thread ipc_thread_;
219 base::Thread listener_thread_;
220 base::Thread* overrided_thread_;
221
222 base::WaitableEvent shutdown_event_;
223
tfarina@chromium.orgb73eaee2010-06-07 11:10:18 +0900224 DISALLOW_COPY_AND_ASSIGN(Worker);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900225};
226
227
228// Starts the test with the given workers. This function deletes the workers
229// when it's done.
230void RunTest(std::vector<Worker*> workers) {
231 // First we create the workers that are channel servers, or else the other
232 // workers' channel initialization might fail because the pipe isn't created..
233 for (size_t i = 0; i < workers.size(); ++i) {
234 if (workers[i]->mode() == Channel::MODE_SERVER) {
235 workers[i]->Start();
236 workers[i]->WaitForChannelCreation();
237 }
238 }
239
240 // now create the clients
241 for (size_t i = 0; i < workers.size(); ++i) {
242 if (workers[i]->mode() == Channel::MODE_CLIENT)
243 workers[i]->Start();
244 }
245
246 // wait for all the workers to finish
247 for (size_t i = 0; i < workers.size(); ++i)
248 workers[i]->done_event()->Wait();
249
250 STLDeleteContainerPointers(workers.begin(), workers.end());
251}
252
253} // namespace
254
255class IPCSyncChannelTest : public testing::Test {
256 private:
257 MessageLoop message_loop_;
258};
259
260//-----------------------------------------------------------------------------
261
262namespace {
263
264class SimpleServer : public Worker {
265 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900266 explicit SimpleServer(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900267 : Worker(Channel::MODE_SERVER, "simpler_server"),
268 pump_during_send_(pump_during_send) { }
269 void Run() {
270 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
271 Done();
272 }
273
274 bool pump_during_send_;
275};
276
277class SimpleClient : public Worker {
278 public:
279 SimpleClient() : Worker(Channel::MODE_CLIENT, "simple_client") { }
280
281 void OnAnswer(int* answer) {
282 *answer = 42;
283 Done();
284 }
285};
286
287void Simple(bool pump_during_send) {
288 std::vector<Worker*> workers;
289 workers.push_back(new SimpleServer(pump_during_send));
290 workers.push_back(new SimpleClient());
291 RunTest(workers);
292}
293
294} // namespace
295
296// Tests basic synchronous call
297TEST_F(IPCSyncChannelTest, Simple) {
298 Simple(false);
299 Simple(true);
300}
301
302//-----------------------------------------------------------------------------
303
304namespace {
305
306class DelayClient : public Worker {
307 public:
308 DelayClient() : Worker(Channel::MODE_CLIENT, "delay_client") { }
309
310 void OnAnswerDelay(Message* reply_msg) {
311 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
312 Send(reply_msg);
313 Done();
314 }
315};
316
317void DelayReply(bool pump_during_send) {
318 std::vector<Worker*> workers;
319 workers.push_back(new SimpleServer(pump_during_send));
320 workers.push_back(new DelayClient());
321 RunTest(workers);
322}
323
324} // namespace
325
326// Tests that asynchronous replies work
327TEST_F(IPCSyncChannelTest, DelayReply) {
328 DelayReply(false);
329 DelayReply(true);
330}
331
332//-----------------------------------------------------------------------------
333
334namespace {
335
336class NoHangServer : public Worker {
337 public:
338 explicit NoHangServer(WaitableEvent* got_first_reply, bool pump_during_send)
339 : Worker(Channel::MODE_SERVER, "no_hang_server"),
340 got_first_reply_(got_first_reply),
341 pump_during_send_(pump_during_send) { }
342 void Run() {
343 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
344 got_first_reply_->Signal();
345
346 SendAnswerToLife(pump_during_send_, base::kNoTimeout, false);
347 Done();
348 }
349
350 WaitableEvent* got_first_reply_;
351 bool pump_during_send_;
352};
353
354class NoHangClient : public Worker {
355 public:
356 explicit NoHangClient(WaitableEvent* got_first_reply)
357 : Worker(Channel::MODE_CLIENT, "no_hang_client"),
358 got_first_reply_(got_first_reply) { }
359
360 virtual void OnAnswerDelay(Message* reply_msg) {
361 // Use the DELAY_REPLY macro so that we can force the reply to be sent
362 // before this function returns (when the channel will be reset).
363 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
364 Send(reply_msg);
365 got_first_reply_->Wait();
366 CloseChannel();
367 Done();
368 }
369
370 WaitableEvent* got_first_reply_;
371};
372
373void NoHang(bool pump_during_send) {
374 WaitableEvent got_first_reply(false, false);
375 std::vector<Worker*> workers;
376 workers.push_back(new NoHangServer(&got_first_reply, pump_during_send));
377 workers.push_back(new NoHangClient(&got_first_reply));
378 RunTest(workers);
379}
380
381} // namespace
382
383// Tests that caller doesn't hang if receiver dies
384TEST_F(IPCSyncChannelTest, NoHang) {
385 NoHang(false);
386 NoHang(true);
387}
388
389//-----------------------------------------------------------------------------
390
391namespace {
392
393class UnblockServer : public Worker {
394 public:
jam@chromium.orgebd07182009-12-01 11:34:18 +0900395 UnblockServer(bool pump_during_send, bool delete_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900396 : Worker(Channel::MODE_SERVER, "unblock_server"),
jam@chromium.orgebd07182009-12-01 11:34:18 +0900397 pump_during_send_(pump_during_send),
398 delete_during_send_(delete_during_send) { }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900399 void Run() {
jam@chromium.orgebd07182009-12-01 11:34:18 +0900400 if (delete_during_send_) {
401 // Use custom code since race conditions mean the answer may or may not be
402 // available.
403 int answer = 0;
404 SyncMessage* msg = new SyncChannelTestMsg_AnswerToLife(&answer);
405 if (pump_during_send_)
406 msg->EnableMessagePumping();
407 Send(msg);
408 } else {
409 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
410 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900411 Done();
412 }
413
jam@chromium.orgebd07182009-12-01 11:34:18 +0900414 void OnDoubleDelay(int in, Message* reply_msg) {
415 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, in * 2);
416 Send(reply_msg);
417 if (delete_during_send_)
418 ResetChannel();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900419 }
420
421 bool pump_during_send_;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900422 bool delete_during_send_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900423};
424
425class UnblockClient : public Worker {
426 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900427 explicit UnblockClient(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900428 : Worker(Channel::MODE_CLIENT, "unblock_client"),
429 pump_during_send_(pump_during_send) { }
430
431 void OnAnswer(int* answer) {
432 SendDouble(pump_during_send_, true);
433 *answer = 42;
434 Done();
435 }
436
437 bool pump_during_send_;
438};
439
jam@chromium.orgebd07182009-12-01 11:34:18 +0900440void Unblock(bool server_pump, bool client_pump, bool delete_during_send) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900441 std::vector<Worker*> workers;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900442 workers.push_back(new UnblockServer(server_pump, delete_during_send));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900443 workers.push_back(new UnblockClient(client_pump));
444 RunTest(workers);
445}
446
447} // namespace
448
449// Tests that the caller unblocks to answer a sync message from the receiver.
450TEST_F(IPCSyncChannelTest, Unblock) {
jam@chromium.orgebd07182009-12-01 11:34:18 +0900451 Unblock(false, false, false);
452 Unblock(false, true, false);
453 Unblock(true, false, false);
454 Unblock(true, true, false);
455}
456
457//-----------------------------------------------------------------------------
458
459// Tests that the the IPC::SyncChannel object can be deleted during a Send.
460TEST_F(IPCSyncChannelTest, ChannelDeleteDuringSend) {
461 Unblock(false, false, true);
462 Unblock(false, true, true);
463 Unblock(true, false, true);
464 Unblock(true, true, true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900465}
466
467//-----------------------------------------------------------------------------
468
469namespace {
470
471class RecursiveServer : public Worker {
472 public:
473 explicit RecursiveServer(
474 bool expected_send_result, bool pump_first, bool pump_second)
475 : Worker(Channel::MODE_SERVER, "recursive_server"),
476 expected_send_result_(expected_send_result),
477 pump_first_(pump_first), pump_second_(pump_second) { }
478 void Run() {
479 SendDouble(pump_first_, expected_send_result_);
480 Done();
481 }
482
483 void OnDouble(int in, int* out) {
484 *out = in * 2;
485 SendAnswerToLife(pump_second_, base::kNoTimeout, expected_send_result_);
486 }
487
488 bool expected_send_result_, pump_first_, pump_second_;
489};
490
491class RecursiveClient : public Worker {
492 public:
493 explicit RecursiveClient(bool pump_during_send, bool close_channel)
494 : Worker(Channel::MODE_CLIENT, "recursive_client"),
495 pump_during_send_(pump_during_send), close_channel_(close_channel) { }
496
497 void OnDoubleDelay(int in, Message* reply_msg) {
498 SendDouble(pump_during_send_, !close_channel_);
499 if (close_channel_) {
500 delete reply_msg;
501 } else {
502 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, in * 2);
503 Send(reply_msg);
504 }
505 Done();
506 }
507
508 void OnAnswerDelay(Message* reply_msg) {
509 if (close_channel_) {
510 delete reply_msg;
511 CloseChannel();
512 } else {
513 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
514 Send(reply_msg);
515 }
516 }
517
518 bool pump_during_send_, close_channel_;
519};
520
521void Recursive(
522 bool server_pump_first, bool server_pump_second, bool client_pump) {
523 std::vector<Worker*> workers;
524 workers.push_back(
525 new RecursiveServer(true, server_pump_first, server_pump_second));
526 workers.push_back(new RecursiveClient(client_pump, false));
527 RunTest(workers);
528}
529
530} // namespace
531
532// Tests a server calling Send while another Send is pending.
533TEST_F(IPCSyncChannelTest, Recursive) {
534 Recursive(false, false, false);
535 Recursive(false, false, true);
536 Recursive(false, true, false);
537 Recursive(false, true, true);
538 Recursive(true, false, false);
539 Recursive(true, false, true);
540 Recursive(true, true, false);
541 Recursive(true, true, true);
542}
543
544//-----------------------------------------------------------------------------
545
546namespace {
547
548void RecursiveNoHang(
549 bool server_pump_first, bool server_pump_second, bool client_pump) {
550 std::vector<Worker*> workers;
551 workers.push_back(
552 new RecursiveServer(false, server_pump_first, server_pump_second));
553 workers.push_back(new RecursiveClient(client_pump, true));
554 RunTest(workers);
555}
556
557} // namespace
558
559// Tests that if a caller makes a sync call during an existing sync call and
560// the receiver dies, neither of the Send() calls hang.
561TEST_F(IPCSyncChannelTest, RecursiveNoHang) {
562 RecursiveNoHang(false, false, false);
563 RecursiveNoHang(false, false, true);
564 RecursiveNoHang(false, true, false);
565 RecursiveNoHang(false, true, true);
566 RecursiveNoHang(true, false, false);
567 RecursiveNoHang(true, false, true);
568 RecursiveNoHang(true, true, false);
569 RecursiveNoHang(true, true, true);
570}
571
572//-----------------------------------------------------------------------------
573
574namespace {
575
576class MultipleServer1 : public Worker {
577 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900578 explicit MultipleServer1(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900579 : Worker("test_channel1", Channel::MODE_SERVER),
580 pump_during_send_(pump_during_send) { }
581
582 void Run() {
583 SendDouble(pump_during_send_, true);
584 Done();
585 }
586
587 bool pump_during_send_;
588};
589
590class MultipleClient1 : public Worker {
591 public:
592 MultipleClient1(WaitableEvent* client1_msg_received,
593 WaitableEvent* client1_can_reply) :
594 Worker("test_channel1", Channel::MODE_CLIENT),
595 client1_msg_received_(client1_msg_received),
596 client1_can_reply_(client1_can_reply) { }
597
598 void OnDouble(int in, int* out) {
599 client1_msg_received_->Signal();
600 *out = in * 2;
601 client1_can_reply_->Wait();
602 Done();
603 }
604
605 private:
606 WaitableEvent *client1_msg_received_, *client1_can_reply_;
607};
608
609class MultipleServer2 : public Worker {
610 public:
611 MultipleServer2() : Worker("test_channel2", Channel::MODE_SERVER) { }
612
613 void OnAnswer(int* result) {
614 *result = 42;
615 Done();
616 }
617};
618
619class MultipleClient2 : public Worker {
620 public:
621 MultipleClient2(
622 WaitableEvent* client1_msg_received, WaitableEvent* client1_can_reply,
623 bool pump_during_send)
624 : Worker("test_channel2", Channel::MODE_CLIENT),
625 client1_msg_received_(client1_msg_received),
626 client1_can_reply_(client1_can_reply),
627 pump_during_send_(pump_during_send) { }
628
629 void Run() {
630 client1_msg_received_->Wait();
631 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
632 client1_can_reply_->Signal();
633 Done();
634 }
635
636 private:
637 WaitableEvent *client1_msg_received_, *client1_can_reply_;
638 bool pump_during_send_;
639};
640
641void Multiple(bool server_pump, bool client_pump) {
642 std::vector<Worker*> workers;
643
644 // A shared worker thread so that server1 and server2 run on one thread.
645 base::Thread worker_thread("Multiple");
646 ASSERT_TRUE(worker_thread.Start());
647
648 // Server1 sends a sync msg to client1, which blocks the reply until
649 // server2 (which runs on the same worker thread as server1) responds
650 // to a sync msg from client2.
651 WaitableEvent client1_msg_received(false, false);
652 WaitableEvent client1_can_reply(false, false);
653
654 Worker* worker;
655
656 worker = new MultipleServer2();
657 worker->OverrideThread(&worker_thread);
658 workers.push_back(worker);
659
660 worker = new MultipleClient2(
661 &client1_msg_received, &client1_can_reply, client_pump);
662 workers.push_back(worker);
663
664 worker = new MultipleServer1(server_pump);
665 worker->OverrideThread(&worker_thread);
666 workers.push_back(worker);
667
668 worker = new MultipleClient1(
669 &client1_msg_received, &client1_can_reply);
670 workers.push_back(worker);
671
672 RunTest(workers);
673}
674
675} // namespace
676
677// Tests that multiple SyncObjects on the same listener thread can unblock each
678// other.
679TEST_F(IPCSyncChannelTest, Multiple) {
680 Multiple(false, false);
681 Multiple(false, true);
682 Multiple(true, false);
683 Multiple(true, true);
684}
685
686//-----------------------------------------------------------------------------
687
688namespace {
689
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900690// This class provides server side functionality to test the case where
691// multiple sync channels are in use on the same thread on the client and
692// nested calls are issued.
693class QueuedReplyServer : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900694 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900695 QueuedReplyServer(base::Thread* listener_thread,
696 const std::string& channel_name,
697 const std::string& reply_text)
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900698 : Worker(channel_name, Channel::MODE_SERVER),
699 reply_text_(reply_text) {
700 Worker::OverrideThread(listener_thread);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900701 }
702
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900703 virtual void OnNestedTestMsg(Message* reply_msg) {
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900704 VLOG(1) << __FUNCTION__ << " Sending reply: " << reply_text_;
705 SyncChannelNestedTestMsg_String::WriteReplyParams(reply_msg, reply_text_);
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900706 Send(reply_msg);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900707 Done();
708 }
709
710 private:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900711 std::string reply_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900712};
713
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900714// The QueuedReplyClient class provides functionality to test the case where
715// multiple sync channels are in use on the same thread and they make nested
716// sync calls, i.e. while the first channel waits for a response it makes a
717// sync call on another channel.
718// The callstack should unwind correctly, i.e. the outermost call should
719// complete first, and so on.
720class QueuedReplyClient : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900721 public:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900722 QueuedReplyClient(base::Thread* listener_thread,
723 const std::string& channel_name,
724 const std::string& expected_text,
725 bool pump_during_send)
726 : Worker(channel_name, Channel::MODE_CLIENT),
thomasvl@google.com9a242072010-07-23 23:18:59 +0900727 pump_during_send_(pump_during_send),
728 expected_text_(expected_text) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900729 Worker::OverrideThread(listener_thread);
730 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900731
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900732 virtual void Run() {
733 std::string response;
734 SyncMessage* msg = new SyncChannelNestedTestMsg_String(&response);
735 if (pump_during_send_)
736 msg->EnableMessagePumping();
737 bool result = Send(msg);
738 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900739 DCHECK_EQ(response, expected_text_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900740
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900741 VLOG(1) << __FUNCTION__ << " Received reply: " << response;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900742 Done();
743 }
744
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900745 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900746 bool pump_during_send_;
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900747 std::string expected_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900748};
749
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900750void QueuedReply(bool client_pump) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900751 std::vector<Worker*> workers;
752
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900753 // A shared worker thread for servers
754 base::Thread server_worker_thread("QueuedReply_ServerListener");
755 ASSERT_TRUE(server_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900756
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900757 base::Thread client_worker_thread("QueuedReply_ClientListener");
758 ASSERT_TRUE(client_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900759
760 Worker* worker;
761
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900762 worker = new QueuedReplyServer(&server_worker_thread,
763 "QueuedReply_Server1",
764 "Got first message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900765 workers.push_back(worker);
766
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900767 worker = new QueuedReplyServer(&server_worker_thread,
768 "QueuedReply_Server2",
769 "Got second 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 QueuedReplyClient(&client_worker_thread,
773 "QueuedReply_Server1",
774 "Got first message",
775 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900776 workers.push_back(worker);
777
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900778 worker = new QueuedReplyClient(&client_worker_thread,
779 "QueuedReply_Server2",
780 "Got second message",
781 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900782 workers.push_back(worker);
783
784 RunTest(workers);
785}
786
787} // namespace
788
789// While a blocking send is in progress, the listener thread might answer other
790// synchronous messages. This tests that if during the response to another
791// message the reply to the original messages comes, it is queued up correctly
792// and the original Send is unblocked later.
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900793// We also test that the send call stacks unwind correctly when the channel
794// pumps messages while waiting for a response.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900795TEST_F(IPCSyncChannelTest, QueuedReply) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900796 QueuedReply(false);
797 QueuedReply(true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900798}
799
800//-----------------------------------------------------------------------------
801
802namespace {
803
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900804void DropAssert(const std::string&) {}
805
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900806class BadServer : public Worker {
807 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900808 explicit BadServer(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900809 : Worker(Channel::MODE_SERVER, "simpler_server"),
810 pump_during_send_(pump_during_send) { }
811 void Run() {
812 int answer = 0;
813
814 SyncMessage* msg = new SyncMessage(
815 MSG_ROUTING_CONTROL, SyncChannelTestMsg_Double::ID,
816 Message::PRIORITY_NORMAL, NULL);
817 if (pump_during_send_)
818 msg->EnableMessagePumping();
819
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900820 // Temporarily ignore asserts so that the assertion in
821 // ipc_message_utils doesn't cause termination.
822 logging::SetLogAssertHandler(&DropAssert);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900823 bool result = Send(msg);
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900824 logging::SetLogAssertHandler(NULL);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900825 DCHECK(!result);
826
827 // Need to send another message to get the client to call Done().
828 result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
829 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900830 DCHECK_EQ(answer, 42);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900831
832 Done();
833 }
834
835 bool pump_during_send_;
836};
837
838void BadMessage(bool pump_during_send) {
839 std::vector<Worker*> workers;
840 workers.push_back(new BadServer(pump_during_send));
841 workers.push_back(new SimpleClient());
842 RunTest(workers);
843}
844
845} // namespace
846
847// Tests that if a message is not serialized correctly, the Send() will fail.
848TEST_F(IPCSyncChannelTest, BadMessage) {
849 BadMessage(false);
850 BadMessage(true);
851}
852
853//-----------------------------------------------------------------------------
854
855namespace {
856
857class ChattyClient : public Worker {
858 public:
859 ChattyClient() :
860 Worker(Channel::MODE_CLIENT, "chatty_client") { }
861
862 void OnAnswer(int* answer) {
863 // The PostMessage limit is 10k. Send 20% more than that.
864 const int kMessageLimit = 10000;
865 const int kMessagesToSend = kMessageLimit * 120 / 100;
866 for (int i = 0; i < kMessagesToSend; ++i) {
867 if (!SendDouble(false, true))
868 break;
869 }
870 *answer = 42;
871 Done();
872 }
873};
874
875void ChattyServer(bool pump_during_send) {
876 std::vector<Worker*> workers;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900877 workers.push_back(new UnblockServer(pump_during_send, false));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900878 workers.push_back(new ChattyClient());
879 RunTest(workers);
880}
881
882} // namespace
883
884// Tests http://b/1093251 - that sending lots of sync messages while
885// the receiver is waiting for a sync reply does not overflow the PostMessage
886// queue.
887TEST_F(IPCSyncChannelTest, ChattyServer) {
888 ChattyServer(false);
889 ChattyServer(true);
890}
891
892//------------------------------------------------------------------------------
893
894namespace {
895
896class TimeoutServer : public Worker {
897 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900898 TimeoutServer(int timeout_ms,
899 std::vector<bool> timeout_seq,
900 bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900901 : Worker(Channel::MODE_SERVER, "timeout_server"),
902 timeout_ms_(timeout_ms),
903 timeout_seq_(timeout_seq),
904 pump_during_send_(pump_during_send) {
905 }
906
907 void Run() {
908 for (std::vector<bool>::const_iterator iter = timeout_seq_.begin();
909 iter != timeout_seq_.end(); ++iter) {
910 SendAnswerToLife(pump_during_send_, timeout_ms_, !*iter);
911 }
912 Done();
913 }
914
915 private:
916 int timeout_ms_;
917 std::vector<bool> timeout_seq_;
918 bool pump_during_send_;
919};
920
921class UnresponsiveClient : public Worker {
922 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900923 explicit UnresponsiveClient(std::vector<bool> timeout_seq)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900924 : Worker(Channel::MODE_CLIENT, "unresponsive_client"),
925 timeout_seq_(timeout_seq) {
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900926 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900927
928 void OnAnswerDelay(Message* reply_msg) {
929 DCHECK(!timeout_seq_.empty());
930 if (!timeout_seq_[0]) {
931 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
932 Send(reply_msg);
933 } else {
934 // Don't reply.
935 delete reply_msg;
936 }
937 timeout_seq_.erase(timeout_seq_.begin());
938 if (timeout_seq_.empty())
939 Done();
940 }
941
942 private:
943 // Whether we should time-out or respond to the various messages we receive.
944 std::vector<bool> timeout_seq_;
945};
946
947void SendWithTimeoutOK(bool pump_during_send) {
948 std::vector<Worker*> workers;
949 std::vector<bool> timeout_seq;
950 timeout_seq.push_back(false);
951 timeout_seq.push_back(false);
952 timeout_seq.push_back(false);
953 workers.push_back(new TimeoutServer(5000, timeout_seq, pump_during_send));
954 workers.push_back(new SimpleClient());
955 RunTest(workers);
956}
957
958void SendWithTimeoutTimeout(bool pump_during_send) {
959 std::vector<Worker*> workers;
960 std::vector<bool> timeout_seq;
961 timeout_seq.push_back(true);
962 timeout_seq.push_back(false);
963 timeout_seq.push_back(false);
964 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
965 workers.push_back(new UnresponsiveClient(timeout_seq));
966 RunTest(workers);
967}
968
969void SendWithTimeoutMixedOKAndTimeout(bool pump_during_send) {
970 std::vector<Worker*> workers;
971 std::vector<bool> timeout_seq;
972 timeout_seq.push_back(true);
973 timeout_seq.push_back(false);
974 timeout_seq.push_back(false);
975 timeout_seq.push_back(true);
976 timeout_seq.push_back(false);
977 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
978 workers.push_back(new UnresponsiveClient(timeout_seq));
979 RunTest(workers);
980}
981
982} // namespace
983
984// Tests that SendWithTimeout does not time-out if the response comes back fast
985// enough.
986TEST_F(IPCSyncChannelTest, SendWithTimeoutOK) {
987 SendWithTimeoutOK(false);
988 SendWithTimeoutOK(true);
989}
990
991// Tests that SendWithTimeout does time-out.
992TEST_F(IPCSyncChannelTest, SendWithTimeoutTimeout) {
993 SendWithTimeoutTimeout(false);
994 SendWithTimeoutTimeout(true);
995}
996
997// Sends some message that time-out and some that succeed.
998TEST_F(IPCSyncChannelTest, SendWithTimeoutMixedOKAndTimeout) {
999 SendWithTimeoutMixedOKAndTimeout(false);
1000 SendWithTimeoutMixedOKAndTimeout(true);
1001}
1002
1003//------------------------------------------------------------------------------
1004
1005namespace {
1006
1007class NestedTask : public Task {
1008 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +09001009 explicit NestedTask(Worker* server) : server_(server) { }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001010 void Run() {
1011 // Sleep a bit so that we wake up after the reply has been received.
1012 PlatformThread::Sleep(250);
1013 server_->SendAnswerToLife(true, base::kNoTimeout, true);
1014 }
1015
1016 Worker* server_;
1017};
1018
1019static bool timeout_occured = false;
1020
1021class TimeoutTask : public Task {
1022 public:
1023 void Run() {
1024 timeout_occured = true;
1025 }
1026};
1027
1028class DoneEventRaceServer : public Worker {
1029 public:
1030 DoneEventRaceServer()
1031 : Worker(Channel::MODE_SERVER, "done_event_race_server") { }
1032
1033 void Run() {
1034 MessageLoop::current()->PostTask(FROM_HERE, new NestedTask(this));
1035 MessageLoop::current()->PostDelayedTask(FROM_HERE, new TimeoutTask(), 9000);
1036 // Even though we have a timeout on the Send, it will succeed since for this
1037 // bug, the reply message comes back and is deserialized, however the done
1038 // event wasn't set. So we indirectly use the timeout task to notice if a
1039 // timeout occurred.
1040 SendAnswerToLife(true, 10000, true);
1041 DCHECK(!timeout_occured);
1042 Done();
1043 }
1044};
1045
1046} // namespace
1047
1048// Tests http://b/1474092 - that if after the done_event is set but before
1049// OnObjectSignaled is called another message is sent out, then after its
1050// reply comes back OnObjectSignaled will be called for the first message.
1051TEST_F(IPCSyncChannelTest, DoneEventRace) {
1052 std::vector<Worker*> workers;
1053 workers.push_back(new DoneEventRaceServer());
1054 workers.push_back(new SimpleClient());
1055 RunTest(workers);
1056}
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001057
1058//-----------------------------------------------------------------------------
1059
1060namespace {
1061
1062class TestSyncMessageFilter : public IPC::SyncMessageFilter {
1063 public:
1064 TestSyncMessageFilter(base::WaitableEvent* shutdown_event, Worker* worker)
1065 : SyncMessageFilter(shutdown_event),
1066 worker_(worker),
1067 thread_("helper_thread") {
1068 base::Thread::Options options;
1069 options.message_loop_type = MessageLoop::TYPE_DEFAULT;
1070 thread_.StartWithOptions(options);
1071 }
1072
1073 virtual void OnFilterAdded(Channel* channel) {
1074 SyncMessageFilter::OnFilterAdded(channel);
1075 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
1076 this, &TestSyncMessageFilter::SendMessageOnHelperThread));
1077 }
1078
1079 void SendMessageOnHelperThread() {
1080 int answer = 0;
1081 bool result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
1082 DCHECK(result);
1083 DCHECK_EQ(answer, 42);
1084
1085 worker_->Done();
1086 }
1087
1088 Worker* worker_;
1089 base::Thread thread_;
1090};
1091
1092class SyncMessageFilterServer : public Worker {
1093 public:
1094 SyncMessageFilterServer()
1095 : Worker(Channel::MODE_SERVER, "sync_message_filter_server") {
1096 filter_ = new TestSyncMessageFilter(shutdown_event(), this);
1097 }
1098
1099 void Run() {
1100 channel()->AddFilter(filter_.get());
1101 }
1102
1103 scoped_refptr<TestSyncMessageFilter> filter_;
1104};
1105
ananta@chromium.org999f2972010-09-03 06:45:50 +09001106// This class provides functionality to test the case that a Send on the sync
1107// channel does not crash after the channel has been closed.
1108class ServerSendAfterClose : public Worker {
1109 public:
1110 ServerSendAfterClose()
1111 : Worker(Channel::MODE_SERVER, "simpler_server"),
1112 send_result_(true) {
1113 }
1114
1115 bool SendDummy() {
1116 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
1117 this, &ServerSendAfterClose::Send, new SyncChannelTestMsg_NoArgs));
1118 return true;
1119 }
1120
1121 bool send_result() const {
1122 return send_result_;
1123 }
1124
1125 private:
1126 virtual void Run() {
1127 CloseChannel();
1128 Done();
1129 }
1130
1131 bool Send(Message* msg) {
1132 send_result_ = Worker::Send(msg);
1133 Done();
1134 return send_result_;
1135 }
1136
1137 bool send_result_;
1138};
1139
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001140} // namespace
1141
1142// Tests basic synchronous call
1143TEST_F(IPCSyncChannelTest, SyncMessageFilter) {
1144 std::vector<Worker*> workers;
1145 workers.push_back(new SyncMessageFilterServer());
1146 workers.push_back(new SimpleClient());
1147 RunTest(workers);
1148}
ananta@chromium.org999f2972010-09-03 06:45:50 +09001149
1150// Test the case when the channel is closed and a Send is attempted after that.
1151TEST_F(IPCSyncChannelTest, SendAfterClose) {
1152 ServerSendAfterClose server;
1153 server.Start();
1154
1155 server.done_event()->Wait();
1156 server.done_event()->Reset();
1157
1158 server.SendDummy();
1159 server.done_event()->Wait();
1160
1161 EXPECT_FALSE(server.send_result());
1162}
1163
1164