blob: 6982b284283ae9fe580a3ef77e5acc8b32a6afe6 [file] [log] [blame]
levin@chromium.org5c528682011-03-28 10:54:15 +09001// Copyright (c) 2011 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
1035class NestedTask : public Task {
1036 public:
dilmah@chromium.org92b4c8e2011-07-27 02:25:25 +09001037 explicit NestedTask(Worker* server) : server_(server) {}
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001038 void Run() {
1039 // Sleep a bit so that we wake up after the reply has been received.
brettw@google.com7c5cc672011-01-01 11:17:08 +09001040 base::PlatformThread::Sleep(250);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001041 server_->SendAnswerToLife(true, base::kNoTimeout, true);
1042 }
1043
1044 Worker* server_;
1045};
1046
1047static bool timeout_occured = false;
1048
1049class TimeoutTask : public Task {
1050 public:
1051 void Run() {
1052 timeout_occured = true;
1053 }
1054};
1055
1056class DoneEventRaceServer : public Worker {
1057 public:
1058 DoneEventRaceServer()
1059 : Worker(Channel::MODE_SERVER, "done_event_race_server") { }
1060
1061 void Run() {
1062 MessageLoop::current()->PostTask(FROM_HERE, new NestedTask(this));
1063 MessageLoop::current()->PostDelayedTask(FROM_HERE, new TimeoutTask(), 9000);
1064 // Even though we have a timeout on the Send, it will succeed since for this
1065 // bug, the reply message comes back and is deserialized, however the done
1066 // event wasn't set. So we indirectly use the timeout task to notice if a
1067 // timeout occurred.
1068 SendAnswerToLife(true, 10000, true);
1069 DCHECK(!timeout_occured);
1070 Done();
1071 }
1072};
1073
1074} // namespace
1075
1076// Tests http://b/1474092 - that if after the done_event is set but before
1077// OnObjectSignaled is called another message is sent out, then after its
1078// reply comes back OnObjectSignaled will be called for the first message.
1079TEST_F(IPCSyncChannelTest, DoneEventRace) {
1080 std::vector<Worker*> workers;
1081 workers.push_back(new DoneEventRaceServer());
1082 workers.push_back(new SimpleClient());
1083 RunTest(workers);
1084}
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001085
1086//-----------------------------------------------------------------------------
1087
1088namespace {
1089
kushi.p@gmail.com5948bf42011-05-14 07:42:41 +09001090class TestSyncMessageFilter : public SyncMessageFilter {
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001091 public:
1092 TestSyncMessageFilter(base::WaitableEvent* shutdown_event, Worker* worker)
1093 : SyncMessageFilter(shutdown_event),
1094 worker_(worker),
1095 thread_("helper_thread") {
1096 base::Thread::Options options;
1097 options.message_loop_type = MessageLoop::TYPE_DEFAULT;
1098 thread_.StartWithOptions(options);
1099 }
1100
1101 virtual void OnFilterAdded(Channel* channel) {
1102 SyncMessageFilter::OnFilterAdded(channel);
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +09001103 thread_.message_loop()->PostTask(
1104 FROM_HERE,
1105 base::Bind(&TestSyncMessageFilter::SendMessageOnHelperThread, this));
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001106 }
1107
1108 void SendMessageOnHelperThread() {
1109 int answer = 0;
1110 bool result = Send(new SyncChannelTestMsg_AnswerToLife(&answer));
1111 DCHECK(result);
1112 DCHECK_EQ(answer, 42);
1113
1114 worker_->Done();
1115 }
1116
1117 Worker* worker_;
1118 base::Thread thread_;
1119};
1120
1121class SyncMessageFilterServer : public Worker {
1122 public:
1123 SyncMessageFilterServer()
1124 : Worker(Channel::MODE_SERVER, "sync_message_filter_server") {
1125 filter_ = new TestSyncMessageFilter(shutdown_event(), this);
1126 }
1127
1128 void Run() {
1129 channel()->AddFilter(filter_.get());
1130 }
1131
1132 scoped_refptr<TestSyncMessageFilter> filter_;
1133};
1134
ananta@chromium.org999f2972010-09-03 06:45:50 +09001135// This class provides functionality to test the case that a Send on the sync
1136// channel does not crash after the channel has been closed.
1137class ServerSendAfterClose : public Worker {
1138 public:
1139 ServerSendAfterClose()
1140 : Worker(Channel::MODE_SERVER, "simpler_server"),
1141 send_result_(true) {
1142 }
1143
1144 bool SendDummy() {
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +09001145 ListenerThread()->message_loop()->PostTask(
1146 FROM_HERE, base::IgnoreReturn<bool>(
1147 base::Bind(&ServerSendAfterClose::Send, this,
1148 new SyncChannelTestMsg_NoArgs)));
ananta@chromium.org999f2972010-09-03 06:45:50 +09001149 return true;
1150 }
1151
1152 bool send_result() const {
1153 return send_result_;
1154 }
1155
1156 private:
1157 virtual void Run() {
1158 CloseChannel();
1159 Done();
1160 }
1161
1162 bool Send(Message* msg) {
1163 send_result_ = Worker::Send(msg);
1164 Done();
1165 return send_result_;
1166 }
1167
1168 bool send_result_;
1169};
1170
jabdelmalek@google.comeb921652010-04-07 05:33:36 +09001171} // namespace
1172
1173// Tests basic synchronous call
1174TEST_F(IPCSyncChannelTest, SyncMessageFilter) {
1175 std::vector<Worker*> workers;
1176 workers.push_back(new SyncMessageFilterServer());
1177 workers.push_back(new SimpleClient());
1178 RunTest(workers);
1179}
ananta@chromium.org999f2972010-09-03 06:45:50 +09001180
1181// Test the case when the channel is closed and a Send is attempted after that.
1182TEST_F(IPCSyncChannelTest, SendAfterClose) {
1183 ServerSendAfterClose server;
1184 server.Start();
1185
1186 server.done_event()->Wait();
1187 server.done_event()->Reset();
1188
1189 server.SendDummy();
1190 server.done_event()->Wait();
1191
1192 EXPECT_FALSE(server.send_result());
1193}
1194
piman@google.com0cbefaa2011-04-08 12:38:21 +09001195//-----------------------------------------------------------------------------
ananta@chromium.org999f2972010-09-03 06:45:50 +09001196
piman@google.com0cbefaa2011-04-08 12:38:21 +09001197namespace {
1198
1199class RestrictedDispatchServer : public Worker {
1200 public:
1201 RestrictedDispatchServer(WaitableEvent* sent_ping_event)
1202 : Worker("restricted_channel", Channel::MODE_SERVER),
1203 sent_ping_event_(sent_ping_event) { }
1204
1205 void OnDoPing(int ping) {
1206 // Send an asynchronous message that unblocks the caller.
kushi.p@gmail.com5948bf42011-05-14 07:42:41 +09001207 Message* msg = new SyncChannelTestMsg_Ping(ping);
piman@google.com0cbefaa2011-04-08 12:38:21 +09001208 msg->set_unblock(true);
1209 Send(msg);
1210 // Signal the event after the message has been sent on the channel, on the
1211 // IPC thread.
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +09001212 ipc_thread().message_loop()->PostTask(
1213 FROM_HERE, base::Bind(&RestrictedDispatchServer::OnPingSent, this));
piman@google.com0cbefaa2011-04-08 12:38:21 +09001214 }
1215
1216 base::Thread* ListenerThread() { return Worker::ListenerThread(); }
1217
1218 private:
1219 bool OnMessageReceived(const Message& message) {
1220 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchServer, message)
1221 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs, OnNoArgs)
1222 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Done, Done)
1223 IPC_END_MESSAGE_MAP()
1224 return true;
1225 }
1226
1227 void OnPingSent() {
1228 sent_ping_event_->Signal();
1229 }
1230
1231 void OnNoArgs() { }
1232 WaitableEvent* sent_ping_event_;
1233};
1234
1235class NonRestrictedDispatchServer : public Worker {
1236 public:
1237 NonRestrictedDispatchServer()
1238 : Worker("non_restricted_channel", Channel::MODE_SERVER) {}
1239
1240 private:
1241 bool OnMessageReceived(const Message& message) {
1242 IPC_BEGIN_MESSAGE_MAP(NonRestrictedDispatchServer, message)
1243 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_NoArgs, OnNoArgs)
1244 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Done, Done)
1245 IPC_END_MESSAGE_MAP()
1246 return true;
1247 }
1248
1249 void OnNoArgs() { }
1250};
1251
1252class RestrictedDispatchClient : public Worker {
1253 public:
1254 RestrictedDispatchClient(WaitableEvent* sent_ping_event,
1255 RestrictedDispatchServer* server,
1256 int* success)
1257 : Worker("restricted_channel", Channel::MODE_CLIENT),
1258 ping_(0),
1259 server_(server),
1260 success_(success),
1261 sent_ping_event_(sent_ping_event) {}
1262
1263 void Run() {
1264 // Incoming messages from our channel should only be dispatched when we
1265 // send a message on that same channel.
1266 channel()->SetRestrictDispatchToSameChannel(true);
1267
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +09001268 server_->ListenerThread()->message_loop()->PostTask(
1269 FROM_HERE, base::Bind(&RestrictedDispatchServer::OnDoPing, server_, 1));
piman@google.com0cbefaa2011-04-08 12:38:21 +09001270 sent_ping_event_->Wait();
1271 Send(new SyncChannelTestMsg_NoArgs);
1272 if (ping_ == 1)
1273 ++*success_;
1274 else
1275 LOG(ERROR) << "Send failed to dispatch incoming message on same channel";
1276
1277 scoped_ptr<SyncChannel> non_restricted_channel(new SyncChannel(
1278 "non_restricted_channel", Channel::MODE_CLIENT, this,
jam@chromium.org06d18442011-05-03 03:00:49 +09001279 ipc_thread().message_loop_proxy(), true, shutdown_event()));
piman@google.com0cbefaa2011-04-08 12:38:21 +09001280
jhawkins@chromium.org9827bd12011-11-13 06:16:41 +09001281 server_->ListenerThread()->message_loop()->PostTask(
1282 FROM_HERE, base::Bind(&RestrictedDispatchServer::OnDoPing, server_, 2));
piman@google.com0cbefaa2011-04-08 12:38:21 +09001283 sent_ping_event_->Wait();
1284 // Check that the incoming message is *not* dispatched when sending on the
1285 // non restricted channel.
1286 // TODO(piman): there is a possibility of a false positive race condition
1287 // here, if the message that was posted on the server-side end of the pipe
1288 // is not visible yet on the client side, but I don't know how to solve this
1289 // without hooking into the internals of SyncChannel. I haven't seen it in
1290 // practice (i.e. not setting SetRestrictDispatchToSameChannel does cause
1291 // the following to fail).
1292 non_restricted_channel->Send(new SyncChannelTestMsg_NoArgs);
1293 if (ping_ == 1)
1294 ++*success_;
1295 else
1296 LOG(ERROR) << "Send dispatched message from restricted channel";
1297
1298 Send(new SyncChannelTestMsg_NoArgs);
1299 if (ping_ == 2)
1300 ++*success_;
1301 else
1302 LOG(ERROR) << "Send failed to dispatch incoming message on same channel";
1303
1304 non_restricted_channel->Send(new SyncChannelTestMsg_Done);
1305 non_restricted_channel.reset();
1306 Send(new SyncChannelTestMsg_Done);
1307 Done();
1308 }
1309
1310 private:
1311 bool OnMessageReceived(const Message& message) {
1312 IPC_BEGIN_MESSAGE_MAP(RestrictedDispatchClient, message)
1313 IPC_MESSAGE_HANDLER(SyncChannelTestMsg_Ping, OnPing)
1314 IPC_END_MESSAGE_MAP()
1315 return true;
1316 }
1317
1318 void OnPing(int ping) {
1319 ping_ = ping;
1320 }
1321
1322 int ping_;
1323 RestrictedDispatchServer* server_;
1324 int* success_;
1325 WaitableEvent* sent_ping_event_;
1326};
1327
1328} // namespace
1329
1330TEST_F(IPCSyncChannelTest, RestrictedDispatch) {
1331 WaitableEvent sent_ping_event(false, false);
1332
1333 RestrictedDispatchServer* server =
1334 new RestrictedDispatchServer(&sent_ping_event);
1335 int success = 0;
1336 std::vector<Worker*> workers;
1337 workers.push_back(new NonRestrictedDispatchServer);
1338 workers.push_back(server);
1339 workers.push_back(
1340 new RestrictedDispatchClient(&sent_ping_event, server, &success));
1341 RunTest(workers);
1342 EXPECT_EQ(3, success);
1343}
kushi.p@gmail.com5948bf42011-05-14 07:42:41 +09001344
1345} // namespace IPC