1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "mojo/common/message_pump_mojo.h"
10 #include "base/debug/alias.h"
11 #include "base/logging.h"
12 #include "base/time/time.h"
13 #include "mojo/common/message_pump_mojo_handler.h"
14 #include "mojo/common/time_helper.h"
20 MojoDeadline
TimeTicksToMojoDeadline(base::TimeTicks time_ticks
,
21 base::TimeTicks now
) {
22 // The is_null() check matches that of HandleWatcher as well as how
23 // |delayed_work_time| is used.
24 if (time_ticks
.is_null())
25 return MOJO_DEADLINE_INDEFINITE
;
26 const int64_t delta
= (time_ticks
- now
).InMicroseconds();
27 return delta
< 0 ? static_cast<MojoDeadline
>(0) :
28 static_cast<MojoDeadline
>(delta
);
33 // State needed for one iteration of WaitMany. The first handle and flags
34 // corresponds to that of the control pipe.
35 struct MessagePumpMojo::WaitState
{
36 std::vector
<Handle
> handles
;
37 std::vector
<MojoHandleSignals
> wait_signals
;
40 struct MessagePumpMojo::RunState
{
41 RunState() : should_quit(false) {
42 CreateMessagePipe(NULL
, &read_handle
, &write_handle
);
45 base::TimeTicks delayed_work_time
;
47 // Used to wake up WaitForWork().
48 ScopedMessagePipeHandle read_handle
;
49 ScopedMessagePipeHandle write_handle
;
54 MessagePumpMojo::MessagePumpMojo() : run_state_(NULL
), next_handler_id_(0) {
57 MessagePumpMojo::~MessagePumpMojo() {
61 scoped_ptr
<base::MessagePump
> MessagePumpMojo::Create() {
62 return scoped_ptr
<MessagePump
>(new MessagePumpMojo());
65 void MessagePumpMojo::AddHandler(MessagePumpMojoHandler
* handler
,
67 MojoHandleSignals wait_signals
,
68 base::TimeTicks deadline
) {
70 DCHECK(handle
.is_valid());
71 // Assume it's an error if someone tries to reregister an existing handle.
72 CHECK_EQ(0u, handlers_
.count(handle
));
74 handler_data
.handler
= handler
;
75 handler_data
.wait_signals
= wait_signals
;
76 handler_data
.deadline
= deadline
;
77 handler_data
.id
= next_handler_id_
++;
78 handlers_
[handle
] = handler_data
;
81 void MessagePumpMojo::RemoveHandler(const Handle
& handle
) {
82 handlers_
.erase(handle
);
85 void MessagePumpMojo::Run(Delegate
* delegate
) {
87 // TODO: better deal with error handling.
88 CHECK(run_state
.read_handle
.is_valid());
89 CHECK(run_state
.write_handle
.is_valid());
90 RunState
* old_state
= NULL
;
92 base::AutoLock
auto_lock(run_state_lock_
);
93 old_state
= run_state_
;
94 run_state_
= &run_state
;
96 DoRunLoop(&run_state
, delegate
);
98 base::AutoLock
auto_lock(run_state_lock_
);
99 run_state_
= old_state
;
103 void MessagePumpMojo::Quit() {
104 base::AutoLock
auto_lock(run_state_lock_
);
106 run_state_
->should_quit
= true;
109 void MessagePumpMojo::ScheduleWork() {
110 base::AutoLock
auto_lock(run_state_lock_
);
112 SignalControlPipe(*run_state_
);
115 void MessagePumpMojo::ScheduleDelayedWork(
116 const base::TimeTicks
& delayed_work_time
) {
117 base::AutoLock
auto_lock(run_state_lock_
);
120 run_state_
->delayed_work_time
= delayed_work_time
;
123 void MessagePumpMojo::DoRunLoop(RunState
* run_state
, Delegate
* delegate
) {
124 bool more_work_is_plausible
= true;
126 const bool block
= !more_work_is_plausible
;
127 DoInternalWork(*run_state
, block
);
129 // There isn't a good way to know if there are more handles ready, we assume
131 more_work_is_plausible
= false;
133 if (run_state
->should_quit
)
136 more_work_is_plausible
|= delegate
->DoWork();
137 if (run_state
->should_quit
)
140 more_work_is_plausible
|= delegate
->DoDelayedWork(
141 &run_state
->delayed_work_time
);
142 if (run_state
->should_quit
)
145 if (more_work_is_plausible
)
148 more_work_is_plausible
= delegate
->DoIdleWork();
149 if (run_state
->should_quit
)
154 void MessagePumpMojo::DoInternalWork(const RunState
& run_state
, bool block
) {
155 const MojoDeadline deadline
= block
? GetDeadlineForWait(run_state
) : 0;
156 const WaitState wait_state
= GetWaitState(run_state
);
157 const MojoResult result
=
158 WaitMany(wait_state
.handles
, wait_state
.wait_signals
, deadline
);
160 // Control pipe was written to.
161 uint32_t num_bytes
= 0;
162 ReadMessageRaw(run_state
.read_handle
.get(), NULL
, &num_bytes
, NULL
, NULL
,
163 MOJO_READ_MESSAGE_FLAG_MAY_DISCARD
);
164 } else if (result
> 0) {
165 const size_t index
= static_cast<size_t>(result
);
166 DCHECK(handlers_
.find(wait_state
.handles
[index
]) != handlers_
.end());
167 handlers_
[wait_state
.handles
[index
]].handler
->OnHandleReady(
168 wait_state
.handles
[index
]);
171 case MOJO_RESULT_CANCELLED
:
172 case MOJO_RESULT_FAILED_PRECONDITION
:
173 RemoveFirstInvalidHandle(wait_state
);
175 case MOJO_RESULT_DEADLINE_EXCEEDED
:
178 base::debug::Alias(&result
);
179 // Unexpected result is likely fatal, crash so we can determine cause.
184 // Notify and remove any handlers whose time has expired. Make a copy in case
185 // someone tries to add/remove new handlers from notification.
186 const HandleToHandler
cloned_handlers(handlers_
);
187 const base::TimeTicks
now(internal::NowTicks());
188 for (HandleToHandler::const_iterator i
= cloned_handlers
.begin();
189 i
!= cloned_handlers
.end(); ++i
) {
190 // Since we're iterating over a clone of the handlers, verify the handler is
191 // still valid before notifying.
192 if (!i
->second
.deadline
.is_null() && i
->second
.deadline
< now
&&
193 handlers_
.find(i
->first
) != handlers_
.end() &&
194 handlers_
[i
->first
].id
== i
->second
.id
) {
195 i
->second
.handler
->OnHandleError(i
->first
, MOJO_RESULT_DEADLINE_EXCEEDED
);
200 void MessagePumpMojo::RemoveFirstInvalidHandle(const WaitState
& wait_state
) {
201 // TODO(sky): deal with control pipe going bad.
202 for (size_t i
= 0; i
< wait_state
.handles
.size(); ++i
) {
203 const MojoResult result
=
204 Wait(wait_state
.handles
[i
], wait_state
.wait_signals
[i
], 0);
205 if (result
== MOJO_RESULT_INVALID_ARGUMENT
) {
206 // We should never have an invalid argument. If we do it indicates
207 // RemoveHandler() was not invoked and is likely to cause problems else
208 // where in the stack if we ignore it.
210 } else if (result
== MOJO_RESULT_FAILED_PRECONDITION
||
211 result
== MOJO_RESULT_CANCELLED
) {
212 CHECK_NE(i
, 0u); // Indicates the control pipe went bad.
214 // Remove the handle first, this way if OnHandleError() tries to remove
215 // the handle our iterator isn't invalidated.
216 CHECK(handlers_
.find(wait_state
.handles
[i
]) != handlers_
.end());
217 MessagePumpMojoHandler
* handler
=
218 handlers_
[wait_state
.handles
[i
]].handler
;
219 handlers_
.erase(wait_state
.handles
[i
]);
220 handler
->OnHandleError(wait_state
.handles
[i
], result
);
226 void MessagePumpMojo::SignalControlPipe(const RunState
& run_state
) {
227 const MojoResult result
=
228 WriteMessageRaw(run_state
.write_handle
.get(), NULL
, 0, NULL
, 0,
229 MOJO_WRITE_MESSAGE_FLAG_NONE
);
230 // If we can't write we likely won't wake up the thread and there is a strong
231 // chance we'll deadlock.
232 CHECK_EQ(MOJO_RESULT_OK
, result
);
235 MessagePumpMojo::WaitState
MessagePumpMojo::GetWaitState(
236 const RunState
& run_state
) const {
237 WaitState wait_state
;
238 wait_state
.handles
.push_back(run_state
.read_handle
.get());
239 wait_state
.wait_signals
.push_back(MOJO_HANDLE_SIGNAL_READABLE
);
241 for (HandleToHandler::const_iterator i
= handlers_
.begin();
242 i
!= handlers_
.end(); ++i
) {
243 wait_state
.handles
.push_back(i
->first
);
244 wait_state
.wait_signals
.push_back(i
->second
.wait_signals
);
249 MojoDeadline
MessagePumpMojo::GetDeadlineForWait(
250 const RunState
& run_state
) const {
251 const base::TimeTicks
now(internal::NowTicks());
252 MojoDeadline deadline
= TimeTicksToMojoDeadline(run_state
.delayed_work_time
,
254 for (HandleToHandler::const_iterator i
= handlers_
.begin();
255 i
!= handlers_
.end(); ++i
) {
257 TimeTicksToMojoDeadline(i
->second
.deadline
, now
), deadline
);
262 } // namespace common