1 // Copyright 2014 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.
4
5 #include "mojo/public/cpp/utility/run_loop.h"
6
7 #include <assert.h>
8
9 #include <algorithm>
10 #include <vector>
11
12 #include "mojo/public/cpp/utility/lib/thread_local.h"
13 #include "mojo/public/cpp/utility/run_loop_handler.h"
14
15 namespace mojo {
16 namespace {
17
18 internal::ThreadLocalPointer<RunLoop> current_run_loop;
19
20 const MojoTimeTicks kInvalidTimeTicks = static_cast<MojoTimeTicks>(0);
21
22 } // namespace
23
24 // State needed for one iteration of WaitMany().
25 struct RunLoop::WaitState {
WaitStatemojo::RunLoop::WaitState26 WaitState() : deadline(MOJO_DEADLINE_INDEFINITE) {}
27
28 std::vector<Handle> handles;
29 std::vector<MojoHandleSignals> handle_signals;
30 MojoDeadline deadline;
31 };
32
33 struct RunLoop::RunState {
RunStatemojo::RunLoop::RunState34 RunState() : should_quit(false) {}
35
36 bool should_quit;
37 };
38
RunLoop()39 RunLoop::RunLoop() : run_state_(NULL), next_handler_id_(0) {
40 assert(!current());
41 current_run_loop.Set(this);
42 }
43
~RunLoop()44 RunLoop::~RunLoop() {
45 assert(current() == this);
46 current_run_loop.Set(NULL);
47 }
48
49 // static
SetUp()50 void RunLoop::SetUp() {
51 current_run_loop.Allocate();
52 }
53
54 // static
TearDown()55 void RunLoop::TearDown() {
56 assert(!current());
57 current_run_loop.Free();
58 }
59
60 // static
current()61 RunLoop* RunLoop::current() {
62 return current_run_loop.Get();
63 }
64
AddHandler(RunLoopHandler * handler,const Handle & handle,MojoHandleSignals handle_signals,MojoDeadline deadline)65 void RunLoop::AddHandler(RunLoopHandler* handler,
66 const Handle& handle,
67 MojoHandleSignals handle_signals,
68 MojoDeadline deadline) {
69 assert(current() == this);
70 assert(handler);
71 assert(handle.is_valid());
72 // Assume it's an error if someone tries to reregister an existing handle.
73 assert(0u == handler_data_.count(handle));
74 HandlerData handler_data;
75 handler_data.handler = handler;
76 handler_data.handle_signals = handle_signals;
77 handler_data.deadline = (deadline == MOJO_DEADLINE_INDEFINITE) ?
78 kInvalidTimeTicks :
79 GetTimeTicksNow() + static_cast<MojoTimeTicks>(deadline);
80 handler_data.id = next_handler_id_++;
81 handler_data_[handle] = handler_data;
82 }
83
RemoveHandler(const Handle & handle)84 void RunLoop::RemoveHandler(const Handle& handle) {
85 assert(current() == this);
86 handler_data_.erase(handle);
87 }
88
HasHandler(const Handle & handle) const89 bool RunLoop::HasHandler(const Handle& handle) const {
90 return handler_data_.find(handle) != handler_data_.end();
91 }
92
Run()93 void RunLoop::Run() {
94 assert(current() == this);
95 RunState* old_state = run_state_;
96 RunState run_state;
97 run_state_ = &run_state;
98 while (!run_state.should_quit)
99 Wait(false);
100 run_state_ = old_state;
101 }
102
RunUntilIdle()103 void RunLoop::RunUntilIdle() {
104 assert(current() == this);
105 RunState* old_state = run_state_;
106 RunState run_state;
107 run_state_ = &run_state;
108 while (!run_state.should_quit) {
109 if (!Wait(true))
110 break;
111 }
112 run_state_ = old_state;
113 }
114
Quit()115 void RunLoop::Quit() {
116 assert(current() == this);
117 if (run_state_)
118 run_state_->should_quit = true;
119 }
120
Wait(bool non_blocking)121 bool RunLoop::Wait(bool non_blocking) {
122 const WaitState wait_state = GetWaitState(non_blocking);
123 if (wait_state.handles.empty()) {
124 Quit();
125 return false;
126 }
127
128 const MojoResult result = WaitMany(wait_state.handles,
129 wait_state.handle_signals,
130 wait_state.deadline);
131 if (result >= 0) {
132 const size_t index = static_cast<size_t>(result);
133 assert(handler_data_.find(wait_state.handles[index]) !=
134 handler_data_.end());
135 handler_data_[wait_state.handles[index]].handler->OnHandleReady(
136 wait_state.handles[index]);
137 return true;
138 }
139
140 switch (result) {
141 case MOJO_RESULT_INVALID_ARGUMENT:
142 case MOJO_RESULT_FAILED_PRECONDITION:
143 return RemoveFirstInvalidHandle(wait_state);
144 case MOJO_RESULT_DEADLINE_EXCEEDED:
145 return NotifyDeadlineExceeded();
146 }
147
148 assert(false);
149 return false;
150 }
151
NotifyDeadlineExceeded()152 bool RunLoop::NotifyDeadlineExceeded() {
153 bool notified = false;
154
155 // Make a copy in case someone tries to add/remove new handlers as part of
156 // notifying.
157 const HandleToHandlerData cloned_handlers(handler_data_);
158 const MojoTimeTicks now(GetTimeTicksNow());
159 for (HandleToHandlerData::const_iterator i = cloned_handlers.begin();
160 i != cloned_handlers.end(); ++i) {
161 // Since we're iterating over a clone of the handlers, verify the handler is
162 // still valid before notifying.
163 if (i->second.deadline != kInvalidTimeTicks &&
164 i->second.deadline < now &&
165 handler_data_.find(i->first) != handler_data_.end() &&
166 handler_data_[i->first].id == i->second.id) {
167 handler_data_.erase(i->first);
168 i->second.handler->OnHandleError(i->first, MOJO_RESULT_DEADLINE_EXCEEDED);
169 notified = true;
170 }
171 }
172
173 return notified;
174 }
175
RemoveFirstInvalidHandle(const WaitState & wait_state)176 bool RunLoop::RemoveFirstInvalidHandle(const WaitState& wait_state) {
177 for (size_t i = 0; i < wait_state.handles.size(); ++i) {
178 const MojoResult result =
179 mojo::Wait(wait_state.handles[i], wait_state.handle_signals[i],
180 static_cast<MojoDeadline>(0));
181 if (result == MOJO_RESULT_INVALID_ARGUMENT ||
182 result == MOJO_RESULT_FAILED_PRECONDITION) {
183 // Remove the handle first, this way if OnHandleError() tries to remove
184 // the handle our iterator isn't invalidated.
185 assert(handler_data_.find(wait_state.handles[i]) != handler_data_.end());
186 RunLoopHandler* handler =
187 handler_data_[wait_state.handles[i]].handler;
188 handler_data_.erase(wait_state.handles[i]);
189 handler->OnHandleError(wait_state.handles[i], result);
190 return true;
191 }
192 assert(MOJO_RESULT_DEADLINE_EXCEEDED == result);
193 }
194 return false;
195 }
196
GetWaitState(bool non_blocking) const197 RunLoop::WaitState RunLoop::GetWaitState(bool non_blocking) const {
198 WaitState wait_state;
199 MojoTimeTicks min_time = kInvalidTimeTicks;
200 for (HandleToHandlerData::const_iterator i = handler_data_.begin();
201 i != handler_data_.end(); ++i) {
202 wait_state.handles.push_back(i->first);
203 wait_state.handle_signals.push_back(i->second.handle_signals);
204 if (!non_blocking && i->second.deadline != kInvalidTimeTicks &&
205 (min_time == kInvalidTimeTicks || i->second.deadline < min_time)) {
206 min_time = i->second.deadline;
207 }
208 }
209 if (non_blocking) {
210 wait_state.deadline = static_cast<MojoDeadline>(0);
211 } else if (min_time != kInvalidTimeTicks) {
212 const MojoTimeTicks now = GetTimeTicksNow();
213 if (min_time < now)
214 wait_state.deadline = static_cast<MojoDeadline>(0);
215 else
216 wait_state.deadline = static_cast<MojoDeadline>(min_time - now);
217 }
218 return wait_state;
219 }
220
221 } // namespace mojo
222