blob: e01cc585fee5acfc9e1f03ace9ed2264fb4a7e99 [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) {
711 LOG(INFO) << __FUNCTION__ << " Sending reply: "
712 << reply_text_.c_str();
713 SyncChannelNestedTestMsg_String::WriteReplyParams(
714 reply_msg, reply_text_);
715 Send(reply_msg);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900716 Done();
717 }
718
719 private:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900720 std::string reply_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900721};
722
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900723// The QueuedReplyClient class provides functionality to test the case where
724// multiple sync channels are in use on the same thread and they make nested
725// sync calls, i.e. while the first channel waits for a response it makes a
726// sync call on another channel.
727// The callstack should unwind correctly, i.e. the outermost call should
728// complete first, and so on.
729class QueuedReplyClient : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900730 public:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900731 QueuedReplyClient(base::Thread* listener_thread,
732 const std::string& channel_name,
733 const std::string& expected_text,
734 bool pump_during_send)
735 : Worker(channel_name, Channel::MODE_CLIENT),
thomasvl@google.com9a242072010-07-23 23:18:59 +0900736 pump_during_send_(pump_during_send),
737 expected_text_(expected_text) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900738 Worker::OverrideThread(listener_thread);
739 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900740
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900741 virtual void Run() {
742 std::string response;
743 SyncMessage* msg = new SyncChannelNestedTestMsg_String(&response);
744 if (pump_during_send_)
745 msg->EnableMessagePumping();
746 bool result = Send(msg);
747 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900748 DCHECK_EQ(response, expected_text_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900749
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900750 LOG(INFO) << __FUNCTION__ << " Received reply: "
751 << response.c_str();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900752 Done();
753 }
754
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900755 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900756 bool pump_during_send_;
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900757 std::string expected_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900758};
759
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900760void QueuedReply(bool client_pump) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900761 std::vector<Worker*> workers;
762
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900763 // A shared worker thread for servers
764 base::Thread server_worker_thread("QueuedReply_ServerListener");
765 ASSERT_TRUE(server_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900766
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900767 base::Thread client_worker_thread("QueuedReply_ClientListener");
768 ASSERT_TRUE(client_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900769
770 Worker* worker;
771
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900772 worker = new QueuedReplyServer(&server_worker_thread,
773 "QueuedReply_Server1",
774 "Got first message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900775 workers.push_back(worker);
776
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900777 worker = new QueuedReplyServer(&server_worker_thread,
778 "QueuedReply_Server2",
779 "Got second message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900780 workers.push_back(worker);
781
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900782 worker = new QueuedReplyClient(&client_worker_thread,
783 "QueuedReply_Server1",
784 "Got first message",
785 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900786 workers.push_back(worker);
787
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900788 worker = new QueuedReplyClient(&client_worker_thread,
789 "QueuedReply_Server2",
790 "Got second message",
791 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900792 workers.push_back(worker);
793
794 RunTest(workers);
795}
796
797} // namespace
798
799// While a blocking send is in progress, the listener thread might answer other
800// synchronous messages. This tests that if during the response to another
801// message the reply to the original messages comes, it is queued up correctly
802// and the original Send is unblocked later.
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900803// We also test that the send call stacks unwind correctly when the channel
804// pumps messages while waiting for a response.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900805TEST_F(IPCSyncChannelTest, QueuedReply) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900806 QueuedReply(false);
807 QueuedReply(true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900808}
809
810//-----------------------------------------------------------------------------
811
812namespace {
813
814class BadServer : public Worker {
815 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900816 explicit BadServer(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900817 : Worker(Channel::MODE_SERVER, "simpler_server"),
818 pump_during_send_(pump_during_send) { }
819 void Run() {
820 int answer = 0;
821
822 SyncMessage* msg = new SyncMessage(
823 MSG_ROUTING_CONTROL, SyncChannelTestMsg_Double::ID,
824 Message::PRIORITY_NORMAL, NULL);
825 if (pump_during_send_)
826 msg->EnableMessagePumping();
827
828 // Temporarily set the minimum logging very high so that the assertion
829 // in ipc_message_utils doesn't fire.
830 int log_level = logging::GetMinLogLevel();
831 logging::SetMinLogLevel(kint32max);
832 bool result = Send(msg);
833 logging::SetMinLogLevel(log_level);
834 DCHECK(!result);
835
836 // Need to send another message to get the client to call Done().
837 result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
838 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900839 DCHECK_EQ(answer, 42);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900840
841 Done();
842 }
843
844 bool pump_during_send_;
845};
846
847void BadMessage(bool pump_during_send) {
848 std::vector<Worker*> workers;
849 workers.push_back(new BadServer(pump_during_send));
850 workers.push_back(new SimpleClient());
851 RunTest(workers);
852}
853
854} // namespace
855
856// Tests that if a message is not serialized correctly, the Send() will fail.
857TEST_F(IPCSyncChannelTest, BadMessage) {
858 BadMessage(false);
859 BadMessage(true);
860}
861
862//-----------------------------------------------------------------------------
863
864namespace {
865
866class ChattyClient : public Worker {
867 public:
868 ChattyClient() :
869 Worker(Channel::MODE_CLIENT, "chatty_client") { }
870
871 void OnAnswer(int* answer) {
872 // The PostMessage limit is 10k. Send 20% more than that.
873 const int kMessageLimit = 10000;
874 const int kMessagesToSend = kMessageLimit * 120 / 100;
875 for (int i = 0; i < kMessagesToSend; ++i) {
876 if (!SendDouble(false, true))
877 break;
878 }
879 *answer = 42;
880 Done();
881 }
882};
883
884void ChattyServer(bool pump_during_send) {
885 std::vector<Worker*> workers;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900886 workers.push_back(new UnblockServer(pump_during_send, false));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900887 workers.push_back(new ChattyClient());
888 RunTest(workers);
889}
890
891} // namespace
892
893// Tests http://b/1093251 - that sending lots of sync messages while
894// the receiver is waiting for a sync reply does not overflow the PostMessage
895// queue.
896TEST_F(IPCSyncChannelTest, ChattyServer) {
897 ChattyServer(false);
898 ChattyServer(true);
899}
900
901//------------------------------------------------------------------------------
902
903namespace {
904
905class TimeoutServer : public Worker {
906 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900907 TimeoutServer(int timeout_ms,
908 std::vector<bool> timeout_seq,
909 bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900910 : Worker(Channel::MODE_SERVER, "timeout_server"),
911 timeout_ms_(timeout_ms),
912 timeout_seq_(timeout_seq),
913 pump_during_send_(pump_during_send) {
914 }
915
916 void Run() {
917 for (std::vector<bool>::const_iterator iter = timeout_seq_.begin();
918 iter != timeout_seq_.end(); ++iter) {
919 SendAnswerToLife(pump_during_send_, timeout_ms_, !*iter);
920 }
921 Done();
922 }
923
924 private:
925 int timeout_ms_;
926 std::vector<bool> timeout_seq_;
927 bool pump_during_send_;
928};
929
930class UnresponsiveClient : public Worker {
931 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900932 explicit UnresponsiveClient(std::vector<bool> timeout_seq)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900933 : Worker(Channel::MODE_CLIENT, "unresponsive_client"),
934 timeout_seq_(timeout_seq) {
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900935 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900936
937 void OnAnswerDelay(Message* reply_msg) {
938 DCHECK(!timeout_seq_.empty());
939 if (!timeout_seq_[0]) {
940 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
941 Send(reply_msg);
942 } else {
943 // Don't reply.
944 delete reply_msg;
945 }
946 timeout_seq_.erase(timeout_seq_.begin());
947 if (timeout_seq_.empty())
948 Done();
949 }
950
951 private:
952 // Whether we should time-out or respond to the various messages we receive.
953 std::vector<bool> timeout_seq_;
954};
955
956void SendWithTimeoutOK(bool pump_during_send) {
957 std::vector<Worker*> workers;
958 std::vector<bool> timeout_seq;
959 timeout_seq.push_back(false);
960 timeout_seq.push_back(false);
961 timeout_seq.push_back(false);
962 workers.push_back(new TimeoutServer(5000, timeout_seq, pump_during_send));
963 workers.push_back(new SimpleClient());
964 RunTest(workers);
965}
966
967void SendWithTimeoutTimeout(bool pump_during_send) {
968 std::vector<Worker*> workers;
969 std::vector<bool> timeout_seq;
970 timeout_seq.push_back(true);
971 timeout_seq.push_back(false);
972 timeout_seq.push_back(false);
973 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
974 workers.push_back(new UnresponsiveClient(timeout_seq));
975 RunTest(workers);
976}
977
978void SendWithTimeoutMixedOKAndTimeout(bool pump_during_send) {
979 std::vector<Worker*> workers;
980 std::vector<bool> timeout_seq;
981 timeout_seq.push_back(true);
982 timeout_seq.push_back(false);
983 timeout_seq.push_back(false);
984 timeout_seq.push_back(true);
985 timeout_seq.push_back(false);
986 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
987 workers.push_back(new UnresponsiveClient(timeout_seq));
988 RunTest(workers);
989}
990
991} // namespace
992
993// Tests that SendWithTimeout does not time-out if the response comes back fast
994// enough.
995TEST_F(IPCSyncChannelTest, SendWithTimeoutOK) {
996 SendWithTimeoutOK(false);
997 SendWithTimeoutOK(true);
998}
999
1000// Tests that SendWithTimeout does time-out.
1001TEST_F(IPCSyncChannelTest, SendWithTimeoutTimeout) {
1002 SendWithTimeoutTimeout(false);
1003 SendWithTimeoutTimeout(true);
1004}
1005
1006// Sends some message that time-out and some that succeed.
1007TEST_F(IPCSyncChannelTest, SendWithTimeoutMixedOKAndTimeout) {
1008 SendWithTimeoutMixedOKAndTimeout(false);
1009 SendWithTimeoutMixedOKAndTimeout(true);
1010}
1011
1012//------------------------------------------------------------------------------
1013
1014namespace {
1015
1016class NestedTask : public Task {
1017 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +09001018 explicit NestedTask(Worker* server) : server_(server) { }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001019 void Run() {
1020 // Sleep a bit so that we wake up after the reply has been received.
1021 PlatformThread::Sleep(250);
1022 server_->SendAnswerToLife(true, base::kNoTimeout, true);
1023 }
1024
1025 Worker* server_;
1026};
1027
1028static bool timeout_occured = false;
1029
1030class TimeoutTask : public Task {
1031 public:
1032 void Run() {
1033 timeout_occured = true;
1034 }
1035};
1036
1037class DoneEventRaceServer : public Worker {
1038 public:
1039 DoneEventRaceServer()
1040 : Worker(Channel::MODE_SERVER, "done_event_race_server") { }
1041
1042 void Run() {
1043 MessageLoop::current()->PostTask(FROM_HERE, new NestedTask(this));
1044 MessageLoop::current()->PostDelayedTask(FROM_HERE, new TimeoutTask(), 9000);
1045 // Even though we have a timeout on the Send, it will succeed since for this
1046 // bug, the reply message comes back and is deserialized, however the done
1047 // event wasn't set. So we indirectly use the timeout task to notice if a
1048 // timeout occurred.
1049 SendAnswerToLife(true, 10000, true);
1050 DCHECK(!timeout_occured);
1051 Done();
1052 }
1053};
1054
1055} // namespace
1056
1057// Tests http://b/1474092 - that if after the done_event is set but before
1058// OnObjectSignaled is called another message is sent out, then after its
1059// reply comes back OnObjectSignaled will be called for the first message.
1060TEST_F(IPCSyncChannelTest, DoneEventRace) {
1061 std::vector<Worker*> workers;
1062 workers.push_back(new DoneEventRaceServer());
1063 workers.push_back(new SimpleClient());
1064 RunTest(workers);
1065}
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001066
1067//-----------------------------------------------------------------------------
1068
1069namespace {
1070
1071class TestSyncMessageFilter : public IPC::SyncMessageFilter {
1072 public:
1073 TestSyncMessageFilter(base::WaitableEvent* shutdown_event, Worker* worker)
1074 : SyncMessageFilter(shutdown_event),
1075 worker_(worker),
1076 thread_("helper_thread") {
1077 base::Thread::Options options;
1078 options.message_loop_type = MessageLoop::TYPE_DEFAULT;
1079 thread_.StartWithOptions(options);
1080 }
1081
1082 virtual void OnFilterAdded(Channel* channel) {
1083 SyncMessageFilter::OnFilterAdded(channel);
1084 thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
1085 this, &TestSyncMessageFilter::SendMessageOnHelperThread));
1086 }
1087
1088 void SendMessageOnHelperThread() {
1089 int answer = 0;
1090 bool result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
1091 DCHECK(result);
1092 DCHECK_EQ(answer, 42);
1093
1094 worker_->Done();
1095 }
1096
1097 Worker* worker_;
1098 base::Thread thread_;
1099};
1100
1101class SyncMessageFilterServer : public Worker {
1102 public:
1103 SyncMessageFilterServer()
1104 : Worker(Channel::MODE_SERVER, "sync_message_filter_server") {
1105 filter_ = new TestSyncMessageFilter(shutdown_event(), this);
1106 }
1107
1108 void Run() {
1109 channel()->AddFilter(filter_.get());
1110 }
1111
1112 scoped_refptr<TestSyncMessageFilter> filter_;
1113};
1114
ananta@chromium.org999f2972010-09-03 06:45:50 +09001115// This class provides functionality to test the case that a Send on the sync
1116// channel does not crash after the channel has been closed.
1117class ServerSendAfterClose : public Worker {
1118 public:
1119 ServerSendAfterClose()
1120 : Worker(Channel::MODE_SERVER, "simpler_server"),
1121 send_result_(true) {
1122 }
1123
1124 bool SendDummy() {
1125 ListenerThread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
1126 this, &ServerSendAfterClose::Send, new SyncChannelTestMsg_NoArgs));
1127 return true;
1128 }
1129
1130 bool send_result() const {
1131 return send_result_;
1132 }
1133
1134 private:
1135 virtual void Run() {
1136 CloseChannel();
1137 Done();
1138 }
1139
1140 bool Send(Message* msg) {
1141 send_result_ = Worker::Send(msg);
1142 Done();
1143 return send_result_;
1144 }
1145
1146 bool send_result_;
1147};
1148
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001149} // namespace
1150
1151// Tests basic synchronous call
1152TEST_F(IPCSyncChannelTest, SyncMessageFilter) {
1153 std::vector<Worker*> workers;
1154 workers.push_back(new SyncMessageFilterServer());
1155 workers.push_back(new SimpleClient());
1156 RunTest(workers);
1157}
ananta@chromium.org999f2972010-09-03 06:45:50 +09001158
1159// Test the case when the channel is closed and a Send is attempted after that.
1160TEST_F(IPCSyncChannelTest, SendAfterClose) {
1161 ServerSendAfterClose server;
1162 server.Start();
1163
1164 server.done_event()->Wait();
1165 server.done_event()->Reset();
1166
1167 server.SendDummy();
1168 server.done_event()->Wait();
1169
1170 EXPECT_FALSE(server.send_result());
1171}
1172
1173