blob: 81ca5609e56b227c23193eea615658b1839f0406 [file] [log] [blame]
jhorwich@chromium.org3c3a8132012-01-12 07:39:54 +09001// Copyright (c) 2012 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"
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +090013#include "base/bind.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090014#include "base/logging.h"
levin@chromium.org5c528682011-03-28 10:54:15 +090015#include "base/memory/scoped_ptr.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090016#include "base/message_loop.h"
dilmah@chromium.orgdc4b9702011-07-20 07:13:24 +090017#include "base/stl_util.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090018#include "base/string_util.h"
timurrrr@chromium.orgf39c3ff2010-05-14 17:24:42 +090019#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
brettw@google.com7c5cc672011-01-01 11:17:08 +090020#include "base/threading/platform_thread.h"
brettw@chromium.org5b5f5e02011-01-01 10:01:06 +090021#include "base/threading/thread.h"
brettw@chromium.org5238c7d2011-01-02 15:05:39 +090022#include "base/synchronization/waitable_event.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090023#include "ipc/ipc_message.h"
jabdelmalek@google.comeb921652010-04-07 05:33:36 +090024#include "ipc/ipc_sync_message_filter.h"
jam@chromium.org86a8de12010-12-09 08:34:16 +090025#include "ipc/ipc_sync_message_unittest.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090026#include "testing/gtest/include/gtest/gtest.h"
27
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090028using base::WaitableEvent;
29
kushi.p@gmail.com5948bf42011-05-14 07:42:41 +090030namespace IPC {
31
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090032namespace {
33
34// Base class for a "process" with listener and IPC threads.
35class Worker : public Channel::Listener, public Message::Sender {
36 public:
37 // Will create a channel without a name.
38 Worker(Channel::Mode mode, const std::string& thread_name)
39 : done_(new WaitableEvent(false, false)),
40 channel_created_(new WaitableEvent(false, false)),
41 mode_(mode),
42 ipc_thread_((thread_name + "_ipc").c_str()),
43 listener_thread_((thread_name + "_listener").c_str()),
44 overrided_thread_(NULL),
timurrrr@chromium.org03100a82009-10-27 20:28:58 +090045 shutdown_event_(true, false) {
46 // The data race on vfptr is real but is very hard
47 // to suppress using standard Valgrind mechanism (suppressions).
48 // We have to use ANNOTATE_BENIGN_RACE to hide the reports and
49 // make ThreadSanitizer bots green.
50 ANNOTATE_BENIGN_RACE(this, "Race on vfptr, http://crbug.com/25841");
51 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090052
53 // Will create a named channel and use this name for the threads' name.
54 Worker(const std::string& channel_name, Channel::Mode mode)
55 : done_(new WaitableEvent(false, false)),
56 channel_created_(new WaitableEvent(false, false)),
57 channel_name_(channel_name),
58 mode_(mode),
59 ipc_thread_((channel_name + "_ipc").c_str()),
60 listener_thread_((channel_name + "_listener").c_str()),
61 overrided_thread_(NULL),
timurrrr@chromium.org03100a82009-10-27 20:28:58 +090062 shutdown_event_(true, false) {
63 // The data race on vfptr is real but is very hard
64 // to suppress using standard Valgrind mechanism (suppressions).
65 // We have to use ANNOTATE_BENIGN_RACE to hide the reports and
66 // make ThreadSanitizer bots green.
67 ANNOTATE_BENIGN_RACE(this, "Race on vfptr, http://crbug.com/25841");
68 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090069
70 // The IPC thread needs to outlive SyncChannel, so force the correct order of
71 // destruction.
72 virtual ~Worker() {
73 WaitableEvent listener_done(false, false), ipc_done(false, false);
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +090074 ListenerThread()->message_loop()->PostTask(
75 FROM_HERE, base::Bind(&Worker::OnListenerThreadShutdown1, this,
76 &listener_done, &ipc_done));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090077 listener_done.Wait();
78 ipc_done.Wait();
79 ipc_thread_.Stop();
80 listener_thread_.Stop();
81 }
82 void AddRef() { }
83 void Release() { }
darin@chromium.org5cb996e2009-09-30 13:29:20 +090084 static bool ImplementsThreadSafeReferenceCounting() { return true; }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090085 bool Send(Message* msg) { return channel_->Send(msg); }
86 bool SendWithTimeout(Message* msg, int timeout_ms) {
87 return channel_->SendWithTimeout(msg, timeout_ms);
88 }
89 void WaitForChannelCreation() { channel_created_->Wait(); }
90 void CloseChannel() {
91 DCHECK(MessageLoop::current() == ListenerThread()->message_loop());
92 channel_->Close();
93 }
94 void Start() {
95 StartThread(&listener_thread_, MessageLoop::TYPE_DEFAULT);
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +090096 ListenerThread()->message_loop()->PostTask(
97 FROM_HERE, base::Bind(&Worker::OnStart, this));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090098 }
99 void OverrideThread(base::Thread* overrided_thread) {
100 DCHECK(overrided_thread_ == NULL);
101 overrided_thread_ = overrided_thread;
102 }
103 bool SendAnswerToLife(bool pump, int timeout, bool succeed) {
104 int answer = 0;
105 SyncMessage* msg = new SyncChannelTestMsg_AnswerToLife(&answer);
106 if (pump)
107 msg->EnableMessagePumping();
108 bool result = SendWithTimeout(msg, timeout);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900109 DCHECK_EQ(result, succeed);
110 DCHECK_EQ(answer, (succeed ? 42 : 0));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900111 return result;
112 }
113 bool SendDouble(bool pump, bool succeed) {
114 int answer = 0;
115 SyncMessage* msg = new SyncChannelTestMsg_Double(5, &answer);
116 if (pump)
117 msg->EnableMessagePumping();
118 bool result = Send(msg);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900119 DCHECK_EQ(result, succeed);
120 DCHECK_EQ(answer, (succeed ? 10 : 0));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900121 return result;
122 }
kkania@chromium.org9ccb4692011-11-16 10:06:46 +0900123 const std::string& channel_name() { return channel_name_; }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900124 Channel::Mode mode() { return mode_; }
125 WaitableEvent* done_event() { return done_.get(); }
jabdelmalek@google.comeb921652010-04-07 05:33:36 +0900126 WaitableEvent* shutdown_event() { return &shutdown_event_; }
jam@chromium.orgebd07182009-12-01 11:34:18 +0900127 void ResetChannel() { channel_.reset(); }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900128 // Derived classes need to call this when they've completed their part of
129 // the test.
130 void Done() { done_->Signal(); }
jabdelmalek@google.comeb921652010-04-07 05:33:36 +0900131
132 protected:
kushi.p@gmail.com5948bf42011-05-14 07:42:41 +0900133 SyncChannel* channel() { return channel_.get(); }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900134 // Functions for dervied classes to implement if they wish.
135 virtual void Run() { }
136 virtual void OnAnswer(int* answer) { NOTREACHED(); }
137 virtual void OnAnswerDelay(Message* reply_msg) {
138 // The message handler map below can only take one entry for
139 // SyncChannelTestMsg_AnswerToLife, so since some classes want
140 // the normal version while other want the delayed reply, we
141 // call the normal version if the derived class didn't override
142 // this function.
143 int answer;
144 OnAnswer(&answer);
145 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, answer);
146 Send(reply_msg);
147 }
148 virtual void OnDouble(int in, int* out) { NOTREACHED(); }
149 virtual void OnDoubleDelay(int in, Message* reply_msg) {
150 int result;
151 OnDouble(in, &result);
152 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, result);
153 Send(reply_msg);
154 }
155
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900156 virtual void OnNestedTestMsg(Message* reply_msg) {
157 NOTREACHED();
158 }
159
kkania@chromium.org9ccb4692011-11-16 10:06:46 +0900160 virtual SyncChannel* CreateChannel() {
161 return new SyncChannel(
162 channel_name_, mode_, this, ipc_thread_.message_loop_proxy(), true,
163 &shutdown_event_);
164 }
165
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900166 base::Thread* ListenerThread() {
167 return overrided_thread_ ? overrided_thread_ : &listener_thread_;
168 }
ananta@chromium.org999f2972010-09-03 06:45:50 +0900169
piman@google.com0cbefaa2011-04-08 12:38:21 +0900170 const base::Thread& ipc_thread() const { return ipc_thread_; }
171
ananta@chromium.org999f2972010-09-03 06:45:50 +0900172 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900173 // Called on the listener thread to create the sync channel.
174 void OnStart() {
175 // Link ipc_thread_, listener_thread_ and channel_ altogether.
176 StartThread(&ipc_thread_, MessageLoop::TYPE_IO);
kkania@chromium.org9ccb4692011-11-16 10:06:46 +0900177 channel_.reset(CreateChannel());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900178 channel_created_->Signal();
179 Run();
180 }
181
182 void OnListenerThreadShutdown1(WaitableEvent* listener_event,
183 WaitableEvent* ipc_event) {
184 // SyncChannel needs to be destructed on the thread that it was created on.
185 channel_.reset();
186
187 MessageLoop::current()->RunAllPending();
188
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +0900189 ipc_thread_.message_loop()->PostTask(
190 FROM_HERE, base::Bind(&Worker::OnIPCThreadShutdown, this,
191 listener_event, ipc_event));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900192 }
193
194 void OnIPCThreadShutdown(WaitableEvent* listener_event,
195 WaitableEvent* ipc_event) {
196 MessageLoop::current()->RunAllPending();
197 ipc_event->Signal();
198
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +0900199 listener_thread_.message_loop()->PostTask(
200 FROM_HERE, base::Bind(&Worker::OnListenerThreadShutdown2, this,
201 listener_event));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900202 }
203
204 void OnListenerThreadShutdown2(WaitableEvent* listener_event) {
205 MessageLoop::current()->RunAllPending();
206 listener_event->Signal();
207 }
208
jam@chromium.org8a2c7842010-12-24 15:19:28 +0900209 bool OnMessageReceived(const Message& message) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900210 IPC_BEGIN_MESSAGE_MAP(Worker, message)
211 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_Double, OnDoubleDelay)
212 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelTestMsg_AnswerToLife,
213 OnAnswerDelay)
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900214 IPC_MESSAGE_HANDLER_DELAY_REPLY(SyncChannelNestedTestMsg_String,
215 OnNestedTestMsg)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900216 IPC_END_MESSAGE_MAP()
jam@chromium.org8a2c7842010-12-24 15:19:28 +0900217 return true;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900218 }
219
220 void StartThread(base::Thread* thread, MessageLoop::Type type) {
221 base::Thread::Options options;
222 options.message_loop_type = type;
223 thread->StartWithOptions(options);
224 }
225
226 scoped_ptr<WaitableEvent> done_;
227 scoped_ptr<WaitableEvent> channel_created_;
228 std::string channel_name_;
229 Channel::Mode mode_;
230 scoped_ptr<SyncChannel> channel_;
231 base::Thread ipc_thread_;
232 base::Thread listener_thread_;
233 base::Thread* overrided_thread_;
234
235 base::WaitableEvent shutdown_event_;
236
tfarina@chromium.orgb73eaee2010-06-07 11:10:18 +0900237 DISALLOW_COPY_AND_ASSIGN(Worker);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900238};
239
240
241// Starts the test with the given workers. This function deletes the workers
242// when it's done.
243void RunTest(std::vector<Worker*> workers) {
244 // First we create the workers that are channel servers, or else the other
245 // workers' channel initialization might fail because the pipe isn't created..
246 for (size_t i = 0; i < workers.size(); ++i) {
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900247 if (workers[i]->mode() & Channel::MODE_SERVER_FLAG) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900248 workers[i]->Start();
249 workers[i]->WaitForChannelCreation();
250 }
251 }
252
253 // now create the clients
254 for (size_t i = 0; i < workers.size(); ++i) {
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900255 if (workers[i]->mode() & Channel::MODE_CLIENT_FLAG)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900256 workers[i]->Start();
257 }
258
259 // wait for all the workers to finish
260 for (size_t i = 0; i < workers.size(); ++i)
261 workers[i]->done_event()->Wait();
262
263 STLDeleteContainerPointers(workers.begin(), workers.end());
264}
265
266} // namespace
267
268class IPCSyncChannelTest : public testing::Test {
269 private:
270 MessageLoop message_loop_;
271};
272
273//-----------------------------------------------------------------------------
274
275namespace {
276
277class SimpleServer : public Worker {
278 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900279 explicit SimpleServer(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900280 : Worker(Channel::MODE_SERVER, "simpler_server"),
281 pump_during_send_(pump_during_send) { }
282 void Run() {
283 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
284 Done();
285 }
286
287 bool pump_during_send_;
288};
289
290class SimpleClient : public Worker {
291 public:
292 SimpleClient() : Worker(Channel::MODE_CLIENT, "simple_client") { }
293
294 void OnAnswer(int* answer) {
295 *answer = 42;
296 Done();
297 }
298};
299
300void Simple(bool pump_during_send) {
301 std::vector<Worker*> workers;
302 workers.push_back(new SimpleServer(pump_during_send));
303 workers.push_back(new SimpleClient());
304 RunTest(workers);
305}
306
307} // namespace
308
309// Tests basic synchronous call
310TEST_F(IPCSyncChannelTest, Simple) {
311 Simple(false);
312 Simple(true);
313}
314
315//-----------------------------------------------------------------------------
316
317namespace {
318
kkania@chromium.org9ccb4692011-11-16 10:06:46 +0900319// Worker classes which override how the sync channel is created to use the
320// two-step initialization (calling the lightweight constructor and then
321// ChannelProxy::Init separately) process.
322class TwoStepServer : public Worker {
323 public:
324 explicit TwoStepServer(bool create_pipe_now)
325 : Worker(Channel::MODE_SERVER, "simpler_server"),
326 create_pipe_now_(create_pipe_now) { }
327
328 void Run() {
329 SendAnswerToLife(false, base::kNoTimeout, true);
330 Done();
331 }
332
333 virtual SyncChannel* CreateChannel() {
334 SyncChannel* channel = new SyncChannel(
335 this, ipc_thread().message_loop_proxy(), shutdown_event());
336 channel->Init(channel_name(), mode(), create_pipe_now_);
337 return channel;
338 }
339
340 bool create_pipe_now_;
341};
342
343class TwoStepClient : public Worker {
344 public:
345 TwoStepClient(bool create_pipe_now)
346 : Worker(Channel::MODE_CLIENT, "simple_client"),
347 create_pipe_now_(create_pipe_now) { }
348
349 void OnAnswer(int* answer) {
350 *answer = 42;
351 Done();
352 }
353
354 virtual SyncChannel* CreateChannel() {
355 SyncChannel* channel = new SyncChannel(
356 this, ipc_thread().message_loop_proxy(), shutdown_event());
357 channel->Init(channel_name(), mode(), create_pipe_now_);
358 return channel;
359 }
360
361 bool create_pipe_now_;
362};
363
364void TwoStep(bool create_server_pipe_now, bool create_client_pipe_now) {
365 std::vector<Worker*> workers;
366 workers.push_back(new TwoStepServer(create_server_pipe_now));
367 workers.push_back(new TwoStepClient(create_client_pipe_now));
368 RunTest(workers);
369}
370
371} // namespace
372
373// Tests basic two-step initialization, where you call the lightweight
374// constructor then Init.
375TEST_F(IPCSyncChannelTest, TwoStepInitialization) {
376 TwoStep(false, false);
377 TwoStep(false, true);
378 TwoStep(true, false);
379 TwoStep(true, true);
380}
381
382
383//-----------------------------------------------------------------------------
384
385namespace {
386
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900387class DelayClient : public Worker {
388 public:
389 DelayClient() : Worker(Channel::MODE_CLIENT, "delay_client") { }
390
391 void OnAnswerDelay(Message* reply_msg) {
392 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
393 Send(reply_msg);
394 Done();
395 }
396};
397
398void DelayReply(bool pump_during_send) {
399 std::vector<Worker*> workers;
400 workers.push_back(new SimpleServer(pump_during_send));
401 workers.push_back(new DelayClient());
402 RunTest(workers);
403}
404
405} // namespace
406
407// Tests that asynchronous replies work
408TEST_F(IPCSyncChannelTest, DelayReply) {
409 DelayReply(false);
410 DelayReply(true);
411}
412
413//-----------------------------------------------------------------------------
414
415namespace {
416
417class NoHangServer : public Worker {
418 public:
dilmah@chromium.org92b4c8e2011-07-27 02:25:25 +0900419 NoHangServer(WaitableEvent* got_first_reply, bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900420 : Worker(Channel::MODE_SERVER, "no_hang_server"),
421 got_first_reply_(got_first_reply),
422 pump_during_send_(pump_during_send) { }
423 void Run() {
424 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
425 got_first_reply_->Signal();
426
427 SendAnswerToLife(pump_during_send_, base::kNoTimeout, false);
428 Done();
429 }
430
431 WaitableEvent* got_first_reply_;
432 bool pump_during_send_;
433};
434
435class NoHangClient : public Worker {
436 public:
437 explicit NoHangClient(WaitableEvent* got_first_reply)
438 : Worker(Channel::MODE_CLIENT, "no_hang_client"),
439 got_first_reply_(got_first_reply) { }
440
441 virtual void OnAnswerDelay(Message* reply_msg) {
442 // Use the DELAY_REPLY macro so that we can force the reply to be sent
443 // before this function returns (when the channel will be reset).
444 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
445 Send(reply_msg);
446 got_first_reply_->Wait();
447 CloseChannel();
448 Done();
449 }
450
451 WaitableEvent* got_first_reply_;
452};
453
454void NoHang(bool pump_during_send) {
455 WaitableEvent got_first_reply(false, false);
456 std::vector<Worker*> workers;
457 workers.push_back(new NoHangServer(&got_first_reply, pump_during_send));
458 workers.push_back(new NoHangClient(&got_first_reply));
459 RunTest(workers);
460}
461
462} // namespace
463
464// Tests that caller doesn't hang if receiver dies
465TEST_F(IPCSyncChannelTest, NoHang) {
466 NoHang(false);
467 NoHang(true);
468}
469
470//-----------------------------------------------------------------------------
471
472namespace {
473
474class UnblockServer : public Worker {
475 public:
jam@chromium.orgebd07182009-12-01 11:34:18 +0900476 UnblockServer(bool pump_during_send, bool delete_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900477 : Worker(Channel::MODE_SERVER, "unblock_server"),
jam@chromium.orgebd07182009-12-01 11:34:18 +0900478 pump_during_send_(pump_during_send),
479 delete_during_send_(delete_during_send) { }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900480 void Run() {
jam@chromium.orgebd07182009-12-01 11:34:18 +0900481 if (delete_during_send_) {
482 // Use custom code since race conditions mean the answer may or may not be
483 // available.
484 int answer = 0;
485 SyncMessage* msg = new SyncChannelTestMsg_AnswerToLife(&answer);
486 if (pump_during_send_)
487 msg->EnableMessagePumping();
488 Send(msg);
489 } else {
490 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
491 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900492 Done();
493 }
494
jam@chromium.orgebd07182009-12-01 11:34:18 +0900495 void OnDoubleDelay(int in, Message* reply_msg) {
496 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, in * 2);
497 Send(reply_msg);
498 if (delete_during_send_)
499 ResetChannel();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900500 }
501
502 bool pump_during_send_;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900503 bool delete_during_send_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900504};
505
506class UnblockClient : public Worker {
507 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900508 explicit UnblockClient(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900509 : Worker(Channel::MODE_CLIENT, "unblock_client"),
510 pump_during_send_(pump_during_send) { }
511
512 void OnAnswer(int* answer) {
513 SendDouble(pump_during_send_, true);
514 *answer = 42;
515 Done();
516 }
517
518 bool pump_during_send_;
519};
520
jam@chromium.orgebd07182009-12-01 11:34:18 +0900521void Unblock(bool server_pump, bool client_pump, bool delete_during_send) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900522 std::vector<Worker*> workers;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900523 workers.push_back(new UnblockServer(server_pump, delete_during_send));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900524 workers.push_back(new UnblockClient(client_pump));
525 RunTest(workers);
526}
527
528} // namespace
529
530// Tests that the caller unblocks to answer a sync message from the receiver.
531TEST_F(IPCSyncChannelTest, Unblock) {
jam@chromium.orgebd07182009-12-01 11:34:18 +0900532 Unblock(false, false, false);
533 Unblock(false, true, false);
534 Unblock(true, false, false);
535 Unblock(true, true, false);
536}
537
538//-----------------------------------------------------------------------------
539
kushi.p@gmail.com5948bf42011-05-14 07:42:41 +0900540// Tests that the the SyncChannel object can be deleted during a Send.
jam@chromium.orgebd07182009-12-01 11:34:18 +0900541TEST_F(IPCSyncChannelTest, ChannelDeleteDuringSend) {
542 Unblock(false, false, true);
543 Unblock(false, true, true);
544 Unblock(true, false, true);
545 Unblock(true, true, true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900546}
547
548//-----------------------------------------------------------------------------
549
550namespace {
551
552class RecursiveServer : public Worker {
553 public:
dilmah@chromium.org92b4c8e2011-07-27 02:25:25 +0900554 RecursiveServer(bool expected_send_result, bool pump_first, bool pump_second)
555 : Worker(Channel::MODE_SERVER, "recursive_server"),
556 expected_send_result_(expected_send_result),
557 pump_first_(pump_first), pump_second_(pump_second) {}
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900558 void Run() {
559 SendDouble(pump_first_, expected_send_result_);
560 Done();
561 }
562
563 void OnDouble(int in, int* out) {
564 *out = in * 2;
565 SendAnswerToLife(pump_second_, base::kNoTimeout, expected_send_result_);
566 }
567
568 bool expected_send_result_, pump_first_, pump_second_;
569};
570
571class RecursiveClient : public Worker {
572 public:
dilmah@chromium.org92b4c8e2011-07-27 02:25:25 +0900573 RecursiveClient(bool pump_during_send, bool close_channel)
574 : Worker(Channel::MODE_CLIENT, "recursive_client"),
575 pump_during_send_(pump_during_send), close_channel_(close_channel) {}
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900576
577 void OnDoubleDelay(int in, Message* reply_msg) {
578 SendDouble(pump_during_send_, !close_channel_);
579 if (close_channel_) {
580 delete reply_msg;
581 } else {
582 SyncChannelTestMsg_Double::WriteReplyParams(reply_msg, in * 2);
583 Send(reply_msg);
584 }
585 Done();
586 }
587
588 void OnAnswerDelay(Message* reply_msg) {
589 if (close_channel_) {
590 delete reply_msg;
591 CloseChannel();
592 } else {
593 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
594 Send(reply_msg);
595 }
596 }
597
598 bool pump_during_send_, close_channel_;
599};
600
601void Recursive(
602 bool server_pump_first, bool server_pump_second, bool client_pump) {
603 std::vector<Worker*> workers;
604 workers.push_back(
605 new RecursiveServer(true, server_pump_first, server_pump_second));
606 workers.push_back(new RecursiveClient(client_pump, false));
607 RunTest(workers);
608}
609
610} // namespace
611
612// Tests a server calling Send while another Send is pending.
613TEST_F(IPCSyncChannelTest, Recursive) {
614 Recursive(false, false, false);
615 Recursive(false, false, true);
616 Recursive(false, true, false);
617 Recursive(false, true, true);
618 Recursive(true, false, false);
619 Recursive(true, false, true);
620 Recursive(true, true, false);
621 Recursive(true, true, true);
622}
623
624//-----------------------------------------------------------------------------
625
626namespace {
627
628void RecursiveNoHang(
629 bool server_pump_first, bool server_pump_second, bool client_pump) {
630 std::vector<Worker*> workers;
631 workers.push_back(
632 new RecursiveServer(false, server_pump_first, server_pump_second));
633 workers.push_back(new RecursiveClient(client_pump, true));
634 RunTest(workers);
635}
636
637} // namespace
638
639// Tests that if a caller makes a sync call during an existing sync call and
640// the receiver dies, neither of the Send() calls hang.
641TEST_F(IPCSyncChannelTest, RecursiveNoHang) {
642 RecursiveNoHang(false, false, false);
643 RecursiveNoHang(false, false, true);
644 RecursiveNoHang(false, true, false);
645 RecursiveNoHang(false, true, true);
646 RecursiveNoHang(true, false, false);
647 RecursiveNoHang(true, false, true);
648 RecursiveNoHang(true, true, false);
649 RecursiveNoHang(true, true, true);
650}
651
652//-----------------------------------------------------------------------------
653
654namespace {
655
656class MultipleServer1 : public Worker {
657 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900658 explicit MultipleServer1(bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900659 : Worker("test_channel1", Channel::MODE_SERVER),
660 pump_during_send_(pump_during_send) { }
661
662 void Run() {
663 SendDouble(pump_during_send_, true);
664 Done();
665 }
666
667 bool pump_during_send_;
668};
669
670class MultipleClient1 : public Worker {
671 public:
672 MultipleClient1(WaitableEvent* client1_msg_received,
673 WaitableEvent* client1_can_reply) :
674 Worker("test_channel1", Channel::MODE_CLIENT),
675 client1_msg_received_(client1_msg_received),
676 client1_can_reply_(client1_can_reply) { }
677
678 void OnDouble(int in, int* out) {
679 client1_msg_received_->Signal();
680 *out = in * 2;
681 client1_can_reply_->Wait();
682 Done();
683 }
684
685 private:
686 WaitableEvent *client1_msg_received_, *client1_can_reply_;
687};
688
689class MultipleServer2 : public Worker {
690 public:
691 MultipleServer2() : Worker("test_channel2", Channel::MODE_SERVER) { }
692
693 void OnAnswer(int* result) {
694 *result = 42;
695 Done();
696 }
697};
698
699class MultipleClient2 : public Worker {
700 public:
701 MultipleClient2(
702 WaitableEvent* client1_msg_received, WaitableEvent* client1_can_reply,
703 bool pump_during_send)
704 : Worker("test_channel2", Channel::MODE_CLIENT),
705 client1_msg_received_(client1_msg_received),
706 client1_can_reply_(client1_can_reply),
707 pump_during_send_(pump_during_send) { }
708
709 void Run() {
710 client1_msg_received_->Wait();
711 SendAnswerToLife(pump_during_send_, base::kNoTimeout, true);
712 client1_can_reply_->Signal();
713 Done();
714 }
715
716 private:
717 WaitableEvent *client1_msg_received_, *client1_can_reply_;
718 bool pump_during_send_;
719};
720
721void Multiple(bool server_pump, bool client_pump) {
722 std::vector<Worker*> workers;
723
724 // A shared worker thread so that server1 and server2 run on one thread.
725 base::Thread worker_thread("Multiple");
726 ASSERT_TRUE(worker_thread.Start());
727
728 // Server1 sends a sync msg to client1, which blocks the reply until
729 // server2 (which runs on the same worker thread as server1) responds
730 // to a sync msg from client2.
731 WaitableEvent client1_msg_received(false, false);
732 WaitableEvent client1_can_reply(false, false);
733
734 Worker* worker;
735
736 worker = new MultipleServer2();
737 worker->OverrideThread(&worker_thread);
738 workers.push_back(worker);
739
740 worker = new MultipleClient2(
741 &client1_msg_received, &client1_can_reply, client_pump);
742 workers.push_back(worker);
743
744 worker = new MultipleServer1(server_pump);
745 worker->OverrideThread(&worker_thread);
746 workers.push_back(worker);
747
748 worker = new MultipleClient1(
749 &client1_msg_received, &client1_can_reply);
750 workers.push_back(worker);
751
752 RunTest(workers);
753}
754
755} // namespace
756
757// Tests that multiple SyncObjects on the same listener thread can unblock each
758// other.
759TEST_F(IPCSyncChannelTest, Multiple) {
760 Multiple(false, false);
761 Multiple(false, true);
762 Multiple(true, false);
763 Multiple(true, true);
764}
765
766//-----------------------------------------------------------------------------
767
768namespace {
769
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900770// This class provides server side functionality to test the case where
771// multiple sync channels are in use on the same thread on the client and
772// nested calls are issued.
773class QueuedReplyServer : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900774 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900775 QueuedReplyServer(base::Thread* listener_thread,
776 const std::string& channel_name,
777 const std::string& reply_text)
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900778 : Worker(channel_name, Channel::MODE_SERVER),
779 reply_text_(reply_text) {
780 Worker::OverrideThread(listener_thread);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900781 }
782
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900783 virtual void OnNestedTestMsg(Message* reply_msg) {
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900784 VLOG(1) << __FUNCTION__ << " Sending reply: " << reply_text_;
785 SyncChannelNestedTestMsg_String::WriteReplyParams(reply_msg, reply_text_);
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900786 Send(reply_msg);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900787 Done();
788 }
789
790 private:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900791 std::string reply_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900792};
793
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900794// The QueuedReplyClient class provides functionality to test the case where
795// multiple sync channels are in use on the same thread and they make nested
796// sync calls, i.e. while the first channel waits for a response it makes a
797// sync call on another channel.
798// The callstack should unwind correctly, i.e. the outermost call should
799// complete first, and so on.
800class QueuedReplyClient : public Worker {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900801 public:
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900802 QueuedReplyClient(base::Thread* listener_thread,
803 const std::string& channel_name,
804 const std::string& expected_text,
805 bool pump_during_send)
806 : Worker(channel_name, Channel::MODE_CLIENT),
thomasvl@google.com9a242072010-07-23 23:18:59 +0900807 pump_during_send_(pump_during_send),
808 expected_text_(expected_text) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900809 Worker::OverrideThread(listener_thread);
810 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900811
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900812 virtual void Run() {
813 std::string response;
814 SyncMessage* msg = new SyncChannelNestedTestMsg_String(&response);
815 if (pump_during_send_)
816 msg->EnableMessagePumping();
817 bool result = Send(msg);
818 DCHECK(result);
jam@chromium.orgebd07182009-12-01 11:34:18 +0900819 DCHECK_EQ(response, expected_text_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900820
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900821 VLOG(1) << __FUNCTION__ << " Received reply: " << response;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900822 Done();
823 }
824
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900825 private:
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900826 bool pump_during_send_;
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900827 std::string expected_text_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900828};
829
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900830void QueuedReply(bool client_pump) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900831 std::vector<Worker*> workers;
832
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900833 // A shared worker thread for servers
834 base::Thread server_worker_thread("QueuedReply_ServerListener");
835 ASSERT_TRUE(server_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900836
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900837 base::Thread client_worker_thread("QueuedReply_ClientListener");
838 ASSERT_TRUE(client_worker_thread.Start());
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900839
840 Worker* worker;
841
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900842 worker = new QueuedReplyServer(&server_worker_thread,
843 "QueuedReply_Server1",
844 "Got first message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900845 workers.push_back(worker);
846
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900847 worker = new QueuedReplyServer(&server_worker_thread,
848 "QueuedReply_Server2",
849 "Got second message");
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900850 workers.push_back(worker);
851
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900852 worker = new QueuedReplyClient(&client_worker_thread,
853 "QueuedReply_Server1",
854 "Got first message",
855 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900856 workers.push_back(worker);
857
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900858 worker = new QueuedReplyClient(&client_worker_thread,
859 "QueuedReply_Server2",
860 "Got second message",
861 client_pump);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900862 workers.push_back(worker);
863
864 RunTest(workers);
865}
866
867} // namespace
868
869// While a blocking send is in progress, the listener thread might answer other
870// synchronous messages. This tests that if during the response to another
871// message the reply to the original messages comes, it is queued up correctly
872// and the original Send is unblocked later.
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900873// We also test that the send call stacks unwind correctly when the channel
874// pumps messages while waiting for a response.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900875TEST_F(IPCSyncChannelTest, QueuedReply) {
ananta@chromium.org31b338f2009-10-15 01:22:02 +0900876 QueuedReply(false);
877 QueuedReply(true);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900878}
879
880//-----------------------------------------------------------------------------
881
882namespace {
883
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900884class ChattyClient : public Worker {
885 public:
886 ChattyClient() :
887 Worker(Channel::MODE_CLIENT, "chatty_client") { }
888
889 void OnAnswer(int* answer) {
890 // The PostMessage limit is 10k. Send 20% more than that.
891 const int kMessageLimit = 10000;
892 const int kMessagesToSend = kMessageLimit * 120 / 100;
893 for (int i = 0; i < kMessagesToSend; ++i) {
894 if (!SendDouble(false, true))
895 break;
896 }
897 *answer = 42;
898 Done();
899 }
900};
901
902void ChattyServer(bool pump_during_send) {
903 std::vector<Worker*> workers;
jam@chromium.orgebd07182009-12-01 11:34:18 +0900904 workers.push_back(new UnblockServer(pump_during_send, false));
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900905 workers.push_back(new ChattyClient());
906 RunTest(workers);
907}
908
909} // namespace
910
911// Tests http://b/1093251 - that sending lots of sync messages while
912// the receiver is waiting for a sync reply does not overflow the PostMessage
913// queue.
914TEST_F(IPCSyncChannelTest, ChattyServer) {
915 ChattyServer(false);
916 ChattyServer(true);
917}
918
919//------------------------------------------------------------------------------
920
921namespace {
922
923class TimeoutServer : public Worker {
924 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900925 TimeoutServer(int timeout_ms,
926 std::vector<bool> timeout_seq,
927 bool pump_during_send)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900928 : Worker(Channel::MODE_SERVER, "timeout_server"),
929 timeout_ms_(timeout_ms),
930 timeout_seq_(timeout_seq),
931 pump_during_send_(pump_during_send) {
932 }
933
934 void Run() {
935 for (std::vector<bool>::const_iterator iter = timeout_seq_.begin();
936 iter != timeout_seq_.end(); ++iter) {
937 SendAnswerToLife(pump_during_send_, timeout_ms_, !*iter);
938 }
939 Done();
940 }
941
942 private:
943 int timeout_ms_;
944 std::vector<bool> timeout_seq_;
945 bool pump_during_send_;
946};
947
948class UnresponsiveClient : public Worker {
949 public:
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900950 explicit UnresponsiveClient(std::vector<bool> timeout_seq)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900951 : Worker(Channel::MODE_CLIENT, "unresponsive_client"),
952 timeout_seq_(timeout_seq) {
thestig@chromium.org60bd7c02010-07-23 14:23:13 +0900953 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900954
955 void OnAnswerDelay(Message* reply_msg) {
956 DCHECK(!timeout_seq_.empty());
957 if (!timeout_seq_[0]) {
958 SyncChannelTestMsg_AnswerToLife::WriteReplyParams(reply_msg, 42);
959 Send(reply_msg);
960 } else {
961 // Don't reply.
962 delete reply_msg;
963 }
964 timeout_seq_.erase(timeout_seq_.begin());
965 if (timeout_seq_.empty())
966 Done();
967 }
968
969 private:
970 // Whether we should time-out or respond to the various messages we receive.
971 std::vector<bool> timeout_seq_;
972};
973
974void SendWithTimeoutOK(bool pump_during_send) {
975 std::vector<Worker*> workers;
976 std::vector<bool> timeout_seq;
977 timeout_seq.push_back(false);
978 timeout_seq.push_back(false);
979 timeout_seq.push_back(false);
980 workers.push_back(new TimeoutServer(5000, timeout_seq, pump_during_send));
981 workers.push_back(new SimpleClient());
982 RunTest(workers);
983}
984
985void SendWithTimeoutTimeout(bool pump_during_send) {
986 std::vector<Worker*> workers;
987 std::vector<bool> timeout_seq;
988 timeout_seq.push_back(true);
989 timeout_seq.push_back(false);
990 timeout_seq.push_back(false);
991 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
992 workers.push_back(new UnresponsiveClient(timeout_seq));
993 RunTest(workers);
994}
995
996void SendWithTimeoutMixedOKAndTimeout(bool pump_during_send) {
997 std::vector<Worker*> workers;
998 std::vector<bool> timeout_seq;
999 timeout_seq.push_back(true);
1000 timeout_seq.push_back(false);
1001 timeout_seq.push_back(false);
1002 timeout_seq.push_back(true);
1003 timeout_seq.push_back(false);
1004 workers.push_back(new TimeoutServer(100, timeout_seq, pump_during_send));
1005 workers.push_back(new UnresponsiveClient(timeout_seq));
1006 RunTest(workers);
1007}
1008
1009} // namespace
1010
1011// Tests that SendWithTimeout does not time-out if the response comes back fast
1012// enough.
1013TEST_F(IPCSyncChannelTest, SendWithTimeoutOK) {
1014 SendWithTimeoutOK(false);
1015 SendWithTimeoutOK(true);
1016}
1017
1018// Tests that SendWithTimeout does time-out.
1019TEST_F(IPCSyncChannelTest, SendWithTimeoutTimeout) {
1020 SendWithTimeoutTimeout(false);
1021 SendWithTimeoutTimeout(true);
1022}
1023
1024// Sends some message that time-out and some that succeed.
phajdan.jr@chromium.orga8e3c092011-01-19 17:11:56 +09001025// Crashes flakily, http://crbug.com/70075.
1026TEST_F(IPCSyncChannelTest, DISABLED_SendWithTimeoutMixedOKAndTimeout) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001027 SendWithTimeoutMixedOKAndTimeout(false);
1028 SendWithTimeoutMixedOKAndTimeout(true);
1029}
1030
1031//------------------------------------------------------------------------------
1032
1033namespace {
1034
jhawkins@chromium.orgdc0f37f2011-11-29 03:35:39 +09001035void NestedCallback(Worker* server) {
1036 // Sleep a bit so that we wake up after the reply has been received.
tedvessenes@gmail.com30dbbaa2012-01-13 09:11:01 +09001037 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(250));
jhawkins@chromium.orgdc0f37f2011-11-29 03:35:39 +09001038 server->SendAnswerToLife(true, base::kNoTimeout, true);
1039}
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001040
jhawkins@chromium.orgdc0f37f2011-11-29 03:35:39 +09001041bool timeout_occurred = false;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001042
jhawkins@chromium.orgdc0f37f2011-11-29 03:35:39 +09001043void TimeoutCallback() {
1044 timeout_occurred = true;
1045}
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001046
1047class DoneEventRaceServer : public Worker {
1048 public:
1049 DoneEventRaceServer()
1050 : Worker(Channel::MODE_SERVER, "done_event_race_server") { }
1051
1052 void Run() {
jhawkins@chromium.orgdc0f37f2011-11-29 03:35:39 +09001053 MessageLoop::current()->PostTask(FROM_HERE,
1054 base::Bind(&NestedCallback, this));
1055 MessageLoop::current()->PostDelayedTask(
1056 FROM_HERE, base::Bind(&TimeoutCallback), 9000);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001057 // Even though we have a timeout on the Send, it will succeed since for this
1058 // bug, the reply message comes back and is deserialized, however the done
1059 // event wasn't set. So we indirectly use the timeout task to notice if a
1060 // timeout occurred.
1061 SendAnswerToLife(true, 10000, true);
jhawkins@chromium.orgdc0f37f2011-11-29 03:35:39 +09001062 DCHECK(!timeout_occurred);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001063 Done();
1064 }
1065};
1066
1067} // namespace
1068
1069// Tests http://b/1474092 - that if after the done_event is set but before
1070// OnObjectSignaled is called another message is sent out, then after its
1071// reply comes back OnObjectSignaled will be called for the first message.
1072TEST_F(IPCSyncChannelTest, DoneEventRace) {
1073 std::vector<Worker*> workers;
1074 workers.push_back(new DoneEventRaceServer());
1075 workers.push_back(new SimpleClient());
1076 RunTest(workers);
1077}
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001078
1079//-----------------------------------------------------------------------------
1080
1081namespace {
1082
kushi.p@gmail.com5948bf42011-05-14 07:42:41 +09001083class TestSyncMessageFilter : public SyncMessageFilter {
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001084 public:
1085 TestSyncMessageFilter(base::WaitableEvent* shutdown_event, Worker* worker)
1086 : SyncMessageFilter(shutdown_event),
1087 worker_(worker),
1088 thread_("helper_thread") {
1089 base::Thread::Options options;
1090 options.message_loop_type = MessageLoop::TYPE_DEFAULT;
1091 thread_.StartWithOptions(options);
1092 }
1093
1094 virtual void OnFilterAdded(Channel* channel) {
1095 SyncMessageFilter::OnFilterAdded(channel);
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +09001096 thread_.message_loop()->PostTask(
1097 FROM_HERE,
1098 base::Bind(&TestSyncMessageFilter::SendMessageOnHelperThread, this));
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001099 }
1100
1101 void SendMessageOnHelperThread() {
1102 int answer = 0;
1103 bool result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
1104 DCHECK(result);
1105 DCHECK_EQ(answer, 42);
1106
1107 worker_->Done();
1108 }
1109
1110 Worker* worker_;
1111 base::Thread thread_;
1112};
1113
1114class SyncMessageFilterServer : public Worker {
1115 public:
1116 SyncMessageFilterServer()
1117 : Worker(Channel::MODE_SERVER, "sync_message_filter_server") {
1118 filter_ = new TestSyncMessageFilter(shutdown_event(), this);
1119 }
1120
1121 void Run() {
1122 channel()->AddFilter(filter_.get());
1123 }
1124
1125 scoped_refptr<TestSyncMessageFilter> filter_;
1126};
1127
ananta@chromium.org999f2972010-09-03 06:45:50 +09001128// This class provides functionality to test the case that a Send on the sync
1129// channel does not crash after the channel has been closed.
1130class ServerSendAfterClose : public Worker {
1131 public:
1132 ServerSendAfterClose()
1133 : Worker(Channel::MODE_SERVER, "simpler_server"),
1134 send_result_(true) {
1135 }
1136
1137 bool SendDummy() {
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +09001138 ListenerThread()->message_loop()->PostTask(
ajwong@chromium.orgc1e632d2012-01-06 11:37:17 +09001139 FROM_HERE, base::Bind(base::IgnoreResult(&ServerSendAfterClose::Send),
1140 this, new SyncChannelTestMsg_NoArgs));
ananta@chromium.org999f2972010-09-03 06:45:50 +09001141 return true;
1142 }
1143
1144 bool send_result() const {
1145 return send_result_;
1146 }
1147
1148 private:
1149 virtual void Run() {
1150 CloseChannel();
1151 Done();
1152 }
1153
1154 bool Send(Message* msg) {
1155 send_result_ = Worker::Send(msg);
1156 Done();
1157 return send_result_;
1158 }
1159
1160 bool send_result_;
1161};
1162
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001163} // namespace
1164
1165// Tests basic synchronous call
1166TEST_F(IPCSyncChannelTest, SyncMessageFilter) {
1167 std::vector<Worker*> workers;
1168 workers.push_back(new SyncMessageFilterServer());
1169 workers.push_back(new SimpleClient());
1170 RunTest(workers);
1171}
ananta@chromium.org999f2972010-09-03 06:45:50 +09001172
1173// Test the case when the channel is closed and a Send is attempted after that.
1174TEST_F(IPCSyncChannelTest, SendAfterClose) {
1175 ServerSendAfterClose server;
1176 server.Start();
1177
1178 server.done_event()->Wait();
1179 server.done_event()->Reset();
1180
1181 server.SendDummy();
1182 server.done_event()->Wait();
1183
1184 EXPECT_FALSE(server.send_result());
1185}
1186
piman@google.com0cbefaa2011-04-08 12:38:21 +09001187//-----------------------------------------------------------------------------
ananta@chromium.org999f2972010-09-03 06:45:50 +09001188
piman@google.com0cbefaa2011-04-08 12:38:21 +09001189namespace {
1190
1191class RestrictedDispatchServer : public Worker {
1192 public:
1193 RestrictedDispatchServer(WaitableEvent* sent_ping_event)
1194 : Worker("restricted_channel", Channel::MODE_SERVER),
1195 sent_ping_event_(sent_ping_event) { }
1196
1197 void OnDoPing(int ping) {
1198 // Send an asynchronous message that unblocks the caller.
kushi.p@gmail.com5948bf42011-05-14 07:42:41 +09001199 Message* msg = new SyncChannelTestMsg_Ping(ping);
piman@google.com0cbefaa2011-04-08 12:38:21 +09001200 msg->set_unblock(true);
1201 Send(msg);
1202 // Signal the event after the message has been sent on the channel, on the
1203 // IPC thread.
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +09001204 ipc_thread().message_loop()->PostTask(
1205 FROM_HERE, base::Bind(&RestrictedDispatchServer::OnPingSent, this));
piman@google.com0cbefaa2011-04-08 12:38:21 +09001206 }
1207
1208 base::Thread* ListenerThread() { return Worker::ListenerThread(); }
1209
1210 private:
1211 bool OnMessageReceived(const Message& message) {
1212 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchServer, message)
1213 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs, OnNoArgs)
1214 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Done, Done)
1215 IPC_END_MESSAGE_MAP()
1216 return true;
1217 }
1218
1219 void OnPingSent() {
1220 sent_ping_event_->Signal();
1221 }
1222
1223 void OnNoArgs() { }
1224 WaitableEvent* sent_ping_event_;
1225};
1226
1227class NonRestrictedDispatchServer : public Worker {
1228 public:
1229 NonRestrictedDispatchServer()
1230 : Worker("non_restricted_channel", Channel::MODE_SERVER) {}
1231
1232 private:
1233 bool OnMessageReceived(const Message& message) {
1234 IPC_BEGIN_MESSAGE_MAP(NonRestrictedDispatchServer, message)
1235 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs, OnNoArgs)
1236 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Done, Done)
1237 IPC_END_MESSAGE_MAP()
1238 return true;
1239 }
1240
1241 void OnNoArgs() { }
1242};
1243
1244class RestrictedDispatchClient : public Worker {
1245 public:
1246 RestrictedDispatchClient(WaitableEvent* sent_ping_event,
1247 RestrictedDispatchServer* server,
1248 int* success)
1249 : Worker("restricted_channel", Channel::MODE_CLIENT),
1250 ping_(0),
1251 server_(server),
1252 success_(success),
1253 sent_ping_event_(sent_ping_event) {}
1254
1255 void Run() {
1256 // Incoming messages from our channel should only be dispatched when we
1257 // send a message on that same channel.
1258 channel()->SetRestrictDispatchToSameChannel(true);
1259
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +09001260 server_->ListenerThread()->message_loop()->PostTask(
1261 FROM_HERE, base::Bind(&RestrictedDispatchServer::OnDoPing, server_, 1));
piman@google.com0cbefaa2011-04-08 12:38:21 +09001262 sent_ping_event_->Wait();
1263 Send(new SyncChannelTestMsg_NoArgs);
1264 if (ping_ == 1)
1265 ++*success_;
1266 else
1267 LOG(ERROR) << "Send failed to dispatch incoming message on same channel";
1268
1269 scoped_ptr<SyncChannel> non_restricted_channel(new SyncChannel(
1270 "non_restricted_channel", Channel::MODE_CLIENT, this,
jam@chromium.org06d18442011-05-03 03:00:49 +09001271 ipc_thread().message_loop_proxy(), true, shutdown_event()));
piman@google.com0cbefaa2011-04-08 12:38:21 +09001272
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +09001273 server_->ListenerThread()->message_loop()->PostTask(
1274 FROM_HERE, base::Bind(&RestrictedDispatchServer::OnDoPing, server_, 2));
piman@google.com0cbefaa2011-04-08 12:38:21 +09001275 sent_ping_event_->Wait();
1276 // Check that the incoming message is *not* dispatched when sending on the
1277 // non restricted channel.
1278 // TODO(piman): there is a possibility of a false positive race condition
1279 // here, if the message that was posted on the server-side end of the pipe
1280 // is not visible yet on the client side, but I don't know how to solve this
1281 // without hooking into the internals of SyncChannel. I haven't seen it in
1282 // practice (i.e. not setting SetRestrictDispatchToSameChannel does cause
1283 // the following to fail).
1284 non_restricted_channel->Send(new SyncChannelTestMsg_NoArgs);
1285 if (ping_ == 1)
1286 ++*success_;
1287 else
1288 LOG(ERROR) << "Send dispatched message from restricted channel";
1289
1290 Send(new SyncChannelTestMsg_NoArgs);
1291 if (ping_ == 2)
1292 ++*success_;
1293 else
1294 LOG(ERROR) << "Send failed to dispatch incoming message on same channel";
1295
1296 non_restricted_channel->Send(new SyncChannelTestMsg_Done);
1297 non_restricted_channel.reset();
1298 Send(new SyncChannelTestMsg_Done);
1299 Done();
1300 }
1301
1302 private:
1303 bool OnMessageReceived(const Message& message) {
1304 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchClient, message)
1305 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Ping, OnPing)
1306 IPC_END_MESSAGE_MAP()
1307 return true;
1308 }
1309
1310 void OnPing(int ping) {
1311 ping_ = ping;
1312 }
1313
1314 int ping_;
1315 RestrictedDispatchServer* server_;
1316 int* success_;
1317 WaitableEvent* sent_ping_event_;
1318};
1319
1320} // namespace
1321
1322TEST_F(IPCSyncChannelTest, RestrictedDispatch) {
1323 WaitableEvent sent_ping_event(false, false);
1324
1325 RestrictedDispatchServer* server =
1326 new RestrictedDispatchServer(&sent_ping_event);
1327 int success = 0;
1328 std::vector<Worker*> workers;
1329 workers.push_back(new NonRestrictedDispatchServer);
1330 workers.push_back(server);
1331 workers.push_back(
1332 new RestrictedDispatchClient(&sent_ping_event, server, &success));
1333 RunTest(workers);
1334 EXPECT_EQ(3, success);
1335}
kushi.p@gmail.com5948bf42011-05-14 07:42:41 +09001336
jhorwich@chromium.org3c3a8132012-01-12 07:39:54 +09001337//-----------------------------------------------------------------------------
1338
1339// This test case inspired by crbug.com/108491
1340// We create two servers that use the same ListenerThread but have
1341// SetRestrictDispatchToSameChannel set to true.
1342// We create clients, then use some specific WaitableEvent wait/signalling to
1343// ensure that messages get dispatched in a way that causes a deadlock due to
1344// a nested dispatch and an eligible message in a higher-level dispatch's
1345// delayed_queue. Specifically, we start with client1 about so send an
1346// unblocking message to server1, while the shared listener thread for the
1347// servers server1 and server2 is about to send a non-unblocking message to
1348// client1. At the same time, client2 will be about to send an unblocking
1349// message to server2. Server1 will handle the client1->server1 message by
1350// telling server2 to send a non-unblocking message to client2.
1351// What should happen is that the send to server2 should find the pending,
1352// same-context client2->server2 message to dispatch, causing client2 to
1353// unblock then handle the server2->client2 message, so that the shared
1354// servers' listener thread can then respond to the client1->server1 message.
1355// Then client1 can handle the non-unblocking server1->client1 message.
1356// The old code would end up in a state where the server2->client2 message is
1357// sent, but the client2->server2 message (which is eligible for dispatch, and
1358// which is what client2 is waiting for) is stashed in a local delayed_queue
1359// that has server1's channel context, causing a deadlock.
1360// WaitableEvents in the events array are used to:
1361// event 0: indicate to client1 that server listener is in OnDoServerTask
1362// event 1: indicate to client1 that client2 listener is in OnDoClient2Task
1363// event 2: indicate to server1 that client2 listener is in OnDoClient2Task
1364// event 3: indicate to client2 that server listener is in OnDoServerTask
1365
1366namespace {
1367
1368class RestrictedDispatchDeadlockServer : public Worker {
1369 public:
1370 RestrictedDispatchDeadlockServer(int server_num,
1371 WaitableEvent* server_ready_event,
1372 WaitableEvent** events,
1373 RestrictedDispatchDeadlockServer* peer)
1374 : Worker(server_num == 1 ? "channel1" : "channel2", Channel::MODE_SERVER),
1375 server_num_(server_num),
1376 server_ready_event_(server_ready_event),
1377 events_(events),
1378 peer_(peer),
1379 client_kicked_(false) { }
1380
1381 void OnDoServerTask() {
1382 events_[3]->Signal();
1383 events_[2]->Wait();
1384 events_[0]->Signal();
1385 SendMessageToClient();
1386 }
1387
1388 void Run() {
1389 channel()->SetRestrictDispatchToSameChannel(true);
1390 server_ready_event_->Signal();
1391 }
1392
1393 base::Thread* ListenerThread() { return Worker::ListenerThread(); }
1394
1395 private:
1396 bool OnMessageReceived(const Message& message) {
1397 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchDeadlockServer, message)
1398 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs, OnNoArgs)
1399 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Done, Done)
1400 IPC_END_MESSAGE_MAP()
1401 return true;
1402 }
1403
1404 void OnNoArgs() {
1405 if (server_num_ == 1) {
1406 DCHECK(peer_ != NULL);
1407 peer_->SendMessageToClient();
1408 }
1409 }
1410
1411 void SendMessageToClient() {
1412 Message* msg = new SyncChannelTestMsg_NoArgs;
1413 msg->set_unblock(false);
1414 DCHECK(!msg->should_unblock());
1415 Send(msg);
1416 }
1417
1418 int server_num_;
1419 WaitableEvent* server_ready_event_;
1420 WaitableEvent** events_;
1421 RestrictedDispatchDeadlockServer* peer_;
1422 bool client_kicked_;
1423};
1424
1425class RestrictedDispatchDeadlockClient2 : public Worker {
1426 public:
1427 RestrictedDispatchDeadlockClient2(RestrictedDispatchDeadlockServer* server,
1428 WaitableEvent* server_ready_event,
1429 WaitableEvent** events)
1430 : Worker("channel2", Channel::MODE_CLIENT),
1431 server_(server),
1432 server_ready_event_(server_ready_event),
1433 events_(events),
1434 received_msg_(false),
1435 received_noarg_reply_(false),
1436 done_issued_(false) {}
1437
1438 void Run() {
1439 server_ready_event_->Wait();
1440 }
1441
1442 void OnDoClient2Task() {
1443 events_[3]->Wait();
1444 events_[1]->Signal();
1445 events_[2]->Signal();
1446 DCHECK(received_msg_ == false);
1447
1448 Message* message = new SyncChannelTestMsg_NoArgs;
1449 message->set_unblock(true);
1450 Send(message);
1451 received_noarg_reply_ = true;
1452 }
1453
1454 base::Thread* ListenerThread() { return Worker::ListenerThread(); }
1455 private:
1456 bool OnMessageReceived(const Message& message) {
1457 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchDeadlockClient2, message)
1458 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs, OnNoArgs)
1459 IPC_END_MESSAGE_MAP()
1460 return true;
1461 }
1462
1463 void OnNoArgs() {
1464 received_msg_ = true;
1465 PossiblyDone();
1466 }
1467
1468 void PossiblyDone() {
1469 if (received_noarg_reply_ && received_msg_) {
1470 DCHECK(done_issued_ == false);
1471 done_issued_ = true;
1472 Send(new SyncChannelTestMsg_Done);
1473 Done();
1474 }
1475 }
1476
1477 RestrictedDispatchDeadlockServer* server_;
1478 WaitableEvent* server_ready_event_;
1479 WaitableEvent** events_;
1480 bool received_msg_;
1481 bool received_noarg_reply_;
1482 bool done_issued_;
1483};
1484
1485class RestrictedDispatchDeadlockClient1 : public Worker {
1486 public:
1487 RestrictedDispatchDeadlockClient1(RestrictedDispatchDeadlockServer* server,
1488 RestrictedDispatchDeadlockClient2* peer,
1489 WaitableEvent* server_ready_event,
1490 WaitableEvent** events)
1491 : Worker("channel1", Channel::MODE_CLIENT),
1492 server_(server),
1493 peer_(peer),
1494 server_ready_event_(server_ready_event),
1495 events_(events),
1496 received_msg_(false),
1497 received_noarg_reply_(false),
1498 done_issued_(false) {}
1499
1500 void Run() {
1501 server_ready_event_->Wait();
1502 server_->ListenerThread()->message_loop()->PostTask(
1503 FROM_HERE,
1504 base::Bind(&RestrictedDispatchDeadlockServer::OnDoServerTask, server_));
1505 peer_->ListenerThread()->message_loop()->PostTask(
1506 FROM_HERE,
1507 base::Bind(&RestrictedDispatchDeadlockClient2::OnDoClient2Task, peer_));
1508 events_[0]->Wait();
1509 events_[1]->Wait();
1510 DCHECK(received_msg_ == false);
1511
1512 Message* message = new SyncChannelTestMsg_NoArgs;
1513 message->set_unblock(true);
1514 Send(message);
1515 received_noarg_reply_ = true;
1516 PossiblyDone();
1517 }
1518
1519 base::Thread* ListenerThread() { return Worker::ListenerThread(); }
1520 private:
1521 bool OnMessageReceived(const Message& message) {
1522 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchDeadlockClient1, message)
1523 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs, OnNoArgs)
1524 IPC_END_MESSAGE_MAP()
1525 return true;
1526 }
1527
1528 void OnNoArgs() {
1529 received_msg_ = true;
1530 PossiblyDone();
1531 }
1532
1533 void PossiblyDone() {
1534 if (received_noarg_reply_ && received_msg_) {
1535 DCHECK(done_issued_ == false);
1536 done_issued_ = true;
1537 Send(new SyncChannelTestMsg_Done);
1538 Done();
1539 }
1540 }
1541
1542 RestrictedDispatchDeadlockServer* server_;
1543 RestrictedDispatchDeadlockClient2* peer_;
1544 WaitableEvent* server_ready_event_;
1545 WaitableEvent** events_;
1546 bool received_msg_;
1547 bool received_noarg_reply_;
1548 bool done_issued_;
1549};
1550
1551} // namespace
1552
1553TEST_F(IPCSyncChannelTest, RestrictedDispatchDeadlock) {
1554 std::vector<Worker*> workers;
1555
1556 // A shared worker thread so that server1 and server2 run on one thread.
1557 base::Thread worker_thread("RestrictedDispatchDeadlock");
1558 ASSERT_TRUE(worker_thread.Start());
1559
1560 WaitableEvent server1_ready(false, false);
1561 WaitableEvent server2_ready(false, false);
1562
1563 WaitableEvent event0(false, false);
1564 WaitableEvent event1(false, false);
1565 WaitableEvent event2(false, false);
1566 WaitableEvent event3(false, false);
1567 WaitableEvent* events[4] = {&event0, &event1, &event2, &event3};
1568
1569 RestrictedDispatchDeadlockServer* server1;
1570 RestrictedDispatchDeadlockServer* server2;
1571 RestrictedDispatchDeadlockClient1* client1;
1572 RestrictedDispatchDeadlockClient2* client2;
1573
1574 server2 = new RestrictedDispatchDeadlockServer(2, &server2_ready, events,
1575 NULL);
1576 server2->OverrideThread(&worker_thread);
1577 workers.push_back(server2);
1578
1579 client2 = new RestrictedDispatchDeadlockClient2(server2, &server2_ready,
1580 events);
1581 workers.push_back(client2);
1582
1583 server1 = new RestrictedDispatchDeadlockServer(1, &server1_ready, events,
1584 server2);
1585 server1->OverrideThread(&worker_thread);
1586 workers.push_back(server1);
1587
1588 client1 = new RestrictedDispatchDeadlockClient1(server1, client2,
1589 &server1_ready, events);
1590 workers.push_back(client1);
1591
1592 RunTest(workers);
1593}
1594
kushi.p@gmail.com5948bf42011-05-14 07:42:41 +09001595} // namespace IPC