blob: 5d9d8e8e4b0551163d9ae3c6da1af53a594bee41 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
[email protected]61c86c62011-08-02 16:11:162// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]59e69e742013-06-18 20:27:525#include "base/message_loop/message_pump_android.h"
[email protected]61c86c62011-08-02 16:11:166
Michael Thiessend7ae7352018-07-10 00:57:137#include <android/looper.h>
8#include <errno.h>
9#include <fcntl.h>
[email protected]61c86c62011-08-02 16:11:1610#include <jni.h>
Michael Thiessend7ae7352018-07-10 00:57:1311#include <sys/eventfd.h>
Egor Pasko6c9baa332023-04-04 18:08:2212#include <sys/timerfd.h>
Michael Thiessend7ae7352018-07-10 00:57:1313#include <sys/types.h>
14#include <unistd.h>
Sean Maheracb46d72024-05-16 17:22:1515
16#include <atomic>
Ken Rockota2c5d792024-11-28 20:05:2217#include <map>
18#include <memory>
Michael Thiessend7ae7352018-07-10 00:57:1319#include <utility>
[email protected]61c86c62011-08-02 16:11:1620
Egor Pasko16859192024-03-11 12:20:5621#include "base/android/input_hint_checker.h"
[email protected]61c86c62011-08-02 16:11:1622#include "base/android/jni_android.h"
[email protected]449019ca2012-03-14 22:17:0023#include "base/android/scoped_java_ref.h"
Adam Riced47f4982024-09-03 16:18:2324#include "base/check.h"
Hans Wennborgc3cffa62020-04-27 10:09:1225#include "base/check_op.h"
Ken Rockota2c5d792024-11-28 20:05:2226#include "base/message_loop/io_watcher.h"
Peter Boström54119652024-11-14 00:16:3827#include "base/notreached.h"
Peter Kasting2f61c8b2022-07-19 23:43:4628#include "base/numerics/safe_conversions.h"
[email protected]8e937c1e2012-06-28 22:57:3029#include "base/run_loop.h"
Sean Maheracb46d72024-05-16 17:22:1530#include "base/task/task_features.h"
Egor Pasko16859192024-03-11 12:20:5631#include "base/time/time.h"
Michael Thiessen6fd43902018-08-30 23:14:1532#include "build/build_config.h"
Michael Thiessend7ae7352018-07-10 00:57:1333
Egor Paskoac4913e2024-10-22 12:03:0434using base::android::InputHintChecker;
35using base::android::InputHintResult;
36
Michael Thiessen781ddeb2017-11-15 17:07:2337namespace base {
38
Michael Thiessend7ae7352018-07-10 00:57:1339namespace {
Michael Thiessen781ddeb2017-11-15 17:07:2340
Michael Thiessen6fd43902018-08-30 23:14:1541// https://crbug.com/873588. The stack may not be aligned when the ALooper calls
42// into our code due to the inconsistent ABI on older Android OS versions.
Egor Pasko30c67b62024-03-22 17:55:5743//
44// https://crbug.com/330761384#comment3. Calls from libutils.so into
45// NonDelayedLooperCallback() and DelayedLooperCallback() confuse aarch64 builds
46// with orderfile instrumentation causing incorrect value in
47// __builtin_return_address(0). Disable instrumentation for them. TODO(pasko):
48// Add these symbols to the orderfile manually or fix the builtin.
Michael Thiessen6fd43902018-08-30 23:14:1549#if defined(ARCH_CPU_X86)
Egor Pasko30c67b62024-03-22 17:55:5750#define NO_INSTRUMENT_STACK_ALIGN \
51 __attribute__((force_align_arg_pointer, no_instrument_function))
Michael Thiessen6fd43902018-08-30 23:14:1552#else
Egor Pasko30c67b62024-03-22 17:55:5753#define NO_INSTRUMENT_STACK_ALIGN __attribute__((no_instrument_function))
Michael Thiessen6fd43902018-08-30 23:14:1554#endif
55
Egor Pasko30c67b62024-03-22 17:55:5756NO_INSTRUMENT_STACK_ALIGN int NonDelayedLooperCallback(int fd,
57 int events,
58 void* data) {
Peter Kasting134ef9af2024-12-28 02:30:0959 if (events & ALOOPER_EVENT_HANGUP) {
Michael Thiessend7ae7352018-07-10 00:57:1360 return 0;
Peter Kasting134ef9af2024-12-28 02:30:0961 }
Michael Thiessend7ae7352018-07-10 00:57:1362
63 DCHECK(events & ALOOPER_EVENT_INPUT);
Egor Pasko6da5a07c2024-03-11 19:56:2964 MessagePumpAndroid* pump = reinterpret_cast<MessagePumpAndroid*>(data);
Michael Thiessend7ae7352018-07-10 00:57:1365 pump->OnNonDelayedLooperCallback();
66 return 1; // continue listening for events
67}
68
Egor Pasko30c67b62024-03-22 17:55:5769NO_INSTRUMENT_STACK_ALIGN int DelayedLooperCallback(int fd,
70 int events,
71 void* data) {
Peter Kasting134ef9af2024-12-28 02:30:0972 if (events & ALOOPER_EVENT_HANGUP) {
Michael Thiessend7ae7352018-07-10 00:57:1373 return 0;
Peter Kasting134ef9af2024-12-28 02:30:0974 }
Michael Thiessend7ae7352018-07-10 00:57:1375
76 DCHECK(events & ALOOPER_EVENT_INPUT);
Egor Pasko6da5a07c2024-03-11 19:56:2977 MessagePumpAndroid* pump = reinterpret_cast<MessagePumpAndroid*>(data);
Michael Thiessend7ae7352018-07-10 00:57:1378 pump->OnDelayedLooperCallback();
79 return 1; // continue listening for events
80}
81
Aaron Colwell48c4d5072020-11-13 16:45:0382// A bit added to the |non_delayed_fd_| to keep it signaled when we yield to
Gabriel Charette300f16792022-07-06 20:03:3083// native work below.
84constexpr uint64_t kTryNativeWorkBeforeIdleBit = uint64_t(1) << 32;
Sean Maheracb46d72024-05-16 17:22:1585
86std::atomic_bool g_fast_to_sleep = false;
Ken Rockota2c5d792024-11-28 20:05:2287
88// Implements IOWatcher to allow any MessagePumpAndroid thread to watch
89// arbitrary file descriptors for I/O events.
90class IOWatcherImpl : public IOWatcher {
91 public:
92 explicit IOWatcherImpl(ALooper* looper) : looper_(looper) {}
93
94 ~IOWatcherImpl() override {
95 for (auto& [fd, watches] : watched_fds_) {
96 ALooper_removeFd(looper_, fd);
97 if (auto read_watch = std::exchange(watches.read_watch, nullptr)) {
98 read_watch->Detach();
99 }
100 if (auto write_watch = std::exchange(watches.write_watch, nullptr)) {
101 write_watch->Detach();
102 }
103 }
104 }
105
106 // IOWatcher:
107 std::unique_ptr<IOWatcher::FdWatch> WatchFileDescriptorImpl(
108 int fd,
109 FdWatchDuration duration,
110 FdWatchMode mode,
111 IOWatcher::FdWatcher& watcher,
112 const Location& location) override {
113 auto& watches = watched_fds_[fd];
114 auto watch = std::make_unique<FdWatchImpl>(*this, fd, duration, watcher);
115 if (mode == FdWatchMode::kRead || mode == FdWatchMode::kReadWrite) {
116 CHECK(!watches.read_watch) << "Only one watch per FD per condition.";
117 watches.read_watch = watch.get();
118 }
119 if (mode == FdWatchMode::kWrite || mode == FdWatchMode::kReadWrite) {
120 CHECK(!watches.write_watch) << "Only one watch per FD per condition.";
121 watches.write_watch = watch.get();
122 }
123
124 const int events = (watches.read_watch ? ALOOPER_EVENT_INPUT : 0) |
125 (watches.write_watch ? ALOOPER_EVENT_OUTPUT : 0);
126 ALooper_addFd(looper_, fd, 0, events, &OnFdIoEvent, this);
127 return watch;
128 }
129
130 private:
131 // Scopes the maximum lifetime of an FD watch started by WatchFileDescriptor.
132 class FdWatchImpl : public FdWatch {
133 public:
134 FdWatchImpl(IOWatcherImpl& io_watcher,
135 int fd,
136 FdWatchDuration duration,
137 FdWatcher& fd_watcher)
138 : fd_(fd),
139 duration_(duration),
140 fd_watcher_(fd_watcher),
141 io_watcher_(&io_watcher) {}
142
143 ~FdWatchImpl() override {
144 Stop();
145 if (destruction_flag_) {
146 *destruction_flag_ = true;
147 }
148 }
149
150 void set_destruction_flag(bool* flag) { destruction_flag_ = flag; }
151 int fd() const { return fd_; }
152 FdWatcher& fd_watcher() const { return *fd_watcher_; }
153
154 bool is_persistent() const {
155 return duration_ == FdWatchDuration::kPersistent;
156 }
157
158 void Detach() { io_watcher_ = nullptr; }
159
160 void Stop() {
161 if (io_watcher_) {
162 std::exchange(io_watcher_, nullptr)->StopWatching(*this);
163 }
164 }
165
166 private:
167 const int fd_;
168 const FdWatchDuration duration_;
169 raw_ref<FdWatcher> fd_watcher_;
170 raw_ptr<IOWatcherImpl> io_watcher_;
171
172 // If non-null during destruction, the pointee is set to true. Used to
173 // detect reentrant destruction during dispatch.
174 raw_ptr<bool> destruction_flag_ = nullptr;
175 };
176
177 enum class EventResult {
178 kStopWatching,
179 kKeepWatching,
180 };
181
182 static NO_INSTRUMENT_STACK_ALIGN int OnFdIoEvent(int fd,
183 int events,
184 void* data) {
185 switch (static_cast<IOWatcherImpl*>(data)->HandleEvent(fd, events)) {
186 case EventResult::kStopWatching:
187 return 0;
188 case EventResult::kKeepWatching:
189 return 1;
190 }
191 }
192
193 EventResult HandleEvent(int fd, int events) {
194 // NOTE: It is possible for Looper to dispatch one last event for `fd`
195 // *after* we have removed the FD from the Looper - for example if multiple
196 // FDs wake the thread at the same time, and a handler for another FD runs
197 // first and removes the watch for `fd`; this callback will have already
198 // been queued for `fd` and will still run. As such, we must gracefully
199 // tolerate receiving a callback for an FD that is no longer watched.
200 auto it = watched_fds_.find(fd);
201 if (it == watched_fds_.end()) {
202 return EventResult::kStopWatching;
203 }
204
205 auto& watches = it->second;
206 const bool is_readable =
207 events & (ALOOPER_EVENT_INPUT | ALOOPER_EVENT_HANGUP);
208 const bool is_writable =
209 events & (ALOOPER_EVENT_OUTPUT | ALOOPER_EVENT_HANGUP);
210 auto* read_watch = watches.read_watch.get();
211 auto* write_watch = watches.write_watch.get();
212
213 // Any event dispatch can stop any number of watches, so we're careful to
214 // set up destruction observation before dispatching anything.
215 bool read_watch_destroyed = false;
216 bool write_watch_destroyed = false;
217 bool fd_removed = false;
218 if (read_watch) {
219 read_watch->set_destruction_flag(&read_watch_destroyed);
220 }
221 if (write_watch && read_watch != write_watch) {
222 write_watch->set_destruction_flag(&write_watch_destroyed);
223 }
224 watches.removed_flag = &fd_removed;
225
226 bool did_observe_one_shot_read = false;
227 if (read_watch && is_readable) {
228 DCHECK_EQ(read_watch->fd(), fd);
229 did_observe_one_shot_read = !read_watch->is_persistent();
230 read_watch->fd_watcher().OnFdReadable(fd);
231 if (!read_watch_destroyed && did_observe_one_shot_read) {
232 read_watch->Stop();
233 }
234 }
235
236 // If the read and write watches are the same object, it may have been
237 // destroyed; or it may have been a one-shot watch already consumed by a
238 // read above. In either case we inhibit write dispatch.
239 if (read_watch == write_watch &&
240 (read_watch_destroyed || did_observe_one_shot_read)) {
241 write_watch = nullptr;
242 }
243
244 if (write_watch && is_writable && !write_watch_destroyed) {
245 DCHECK_EQ(write_watch->fd(), fd);
246 const bool is_persistent = write_watch->is_persistent();
247 write_watch->fd_watcher().OnFdWritable(fd);
248 if (!write_watch_destroyed && !is_persistent) {
249 write_watch->Stop();
250 }
251 }
252
253 if (read_watch && !read_watch_destroyed) {
254 read_watch->set_destruction_flag(nullptr);
255 }
256 if (write_watch && !write_watch_destroyed) {
257 write_watch->set_destruction_flag(nullptr);
258 }
259
260 if (fd_removed) {
261 return EventResult::kStopWatching;
262 }
263
264 watches.removed_flag = nullptr;
265 return EventResult::kKeepWatching;
266 }
267
268 void StopWatching(FdWatchImpl& watch) {
269 const int fd = watch.fd();
270 auto it = watched_fds_.find(fd);
271 if (it == watched_fds_.end()) {
272 return;
273 }
274
275 WatchPair& watches = it->second;
276 if (watches.read_watch == &watch) {
277 watches.read_watch = nullptr;
278 }
279 if (watches.write_watch == &watch) {
280 watches.write_watch = nullptr;
281 }
282
283 const int remaining_events =
284 (watches.read_watch ? ALOOPER_EVENT_INPUT : 0) |
285 (watches.write_watch ? ALOOPER_EVENT_OUTPUT : 0);
286 if (remaining_events) {
287 ALooper_addFd(looper_, fd, 0, remaining_events, &OnFdIoEvent, this);
288 return;
289 }
290
291 ALooper_removeFd(looper_, fd);
292 if (watches.removed_flag) {
293 *watches.removed_flag = true;
294 }
295 watched_fds_.erase(it);
296 }
297
298 private:
299 const raw_ptr<ALooper> looper_;
300
301 // The set of active FdWatches. Note that each FD may have up to two active
302 // watches only - one for read and one for write. No two FdWatches can watch
303 // the same FD for the same signal. `read_watch` and `write_watch` may point
304 // to the same object.
305 struct WatchPair {
306 raw_ptr<FdWatchImpl> read_watch = nullptr;
307 raw_ptr<FdWatchImpl> write_watch = nullptr;
308
309 // If non-null when this WatchPair is removed, the pointee is set to true.
310 // Used to track reentrant map mutations during dispatch.
311 raw_ptr<bool> removed_flag = nullptr;
312 };
313 std::map<int, WatchPair> watched_fds_;
314};
315
Michael Thiessend7ae7352018-07-10 00:57:13316} // namespace
317
Egor Pasko6da5a07c2024-03-11 19:56:29318MessagePumpAndroid::MessagePumpAndroid()
François Doray253a3062022-10-24 16:45:29319 : env_(base::android::AttachCurrentThread()) {
Michael Thiessend7ae7352018-07-10 00:57:13320 // The Android native ALooper uses epoll to poll our file descriptors and wake
321 // us up. We use a simple level-triggered eventfd to signal that non-delayed
322 // work is available, and a timerfd to signal when delayed work is ready to
323 // be run.
324 non_delayed_fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
325 CHECK_NE(non_delayed_fd_, -1);
326 DCHECK_EQ(TimeTicks::GetClock(), TimeTicks::Clock::LINUX_CLOCK_MONOTONIC);
327
Peter Kasting2f61c8b2022-07-19 23:43:46328 delayed_fd_ = checked_cast<int>(
Egor Pasko47ff68432023-04-05 18:23:57329 timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC));
Michael Thiessend7ae7352018-07-10 00:57:13330 CHECK_NE(delayed_fd_, -1);
331
332 looper_ = ALooper_prepare(0);
333 DCHECK(looper_);
334 // Add a reference to the looper so it isn't deleted on us.
335 ALooper_acquire(looper_);
336 ALooper_addFd(looper_, non_delayed_fd_, 0, ALOOPER_EVENT_INPUT,
337 &NonDelayedLooperCallback, reinterpret_cast<void*>(this));
338 ALooper_addFd(looper_, delayed_fd_, 0, ALOOPER_EVENT_INPUT,
339 &DelayedLooperCallback, reinterpret_cast<void*>(this));
340}
341
Egor Pasko6da5a07c2024-03-11 19:56:29342MessagePumpAndroid::~MessagePumpAndroid() {
Michael Thiessend7ae7352018-07-10 00:57:13343 DCHECK_EQ(ALooper_forThread(), looper_);
Ken Rockota2c5d792024-11-28 20:05:22344 io_watcher_.reset();
Michael Thiessend7ae7352018-07-10 00:57:13345 ALooper_removeFd(looper_, non_delayed_fd_);
346 ALooper_removeFd(looper_, delayed_fd_);
347 ALooper_release(looper_);
348 looper_ = nullptr;
349
350 close(non_delayed_fd_);
351 close(delayed_fd_);
352}
353
Sean Maheracb46d72024-05-16 17:22:15354void MessagePumpAndroid::InitializeFeatures() {
355 g_fast_to_sleep = base::FeatureList::IsEnabled(kPumpFastToSleepAndroid);
356}
357
Egor Pasko6da5a07c2024-03-11 19:56:29358void MessagePumpAndroid::OnDelayedLooperCallback() {
Egor Paskoac4913e2024-10-22 12:03:04359 OnReturnFromLooper();
Torne (Richard Coles)c6993a032020-02-19 13:23:47360 // There may be non-Chromium callbacks on the same ALooper which may have left
361 // a pending exception set, and ALooper does not check for this between
362 // callbacks. Check here, and if there's already an exception, just skip this
363 // iteration without clearing the fd. If the exception ends up being non-fatal
364 // then we'll just get called again on the next polling iteration.
Peter Kasting134ef9af2024-12-28 02:30:09365 if (base::android::HasException(env_)) {
Torne (Richard Coles)c6993a032020-02-19 13:23:47366 return;
Peter Kasting134ef9af2024-12-28 02:30:09367 }
Torne (Richard Coles)c6993a032020-02-19 13:23:47368
Gabriel Charette9d44a9b2019-04-29 16:35:56369 // ALooper_pollOnce may call this after Quit() if OnNonDelayedLooperCallback()
370 // resulted in Quit() in the same round.
Peter Kasting134ef9af2024-12-28 02:30:09371 if (ShouldQuit()) {
Michael Thiessenfc7067fe2017-11-01 22:33:01372 return;
Peter Kasting134ef9af2024-12-28 02:30:09373 }
Michael Thiessenfc7067fe2017-11-01 22:33:01374
François Doray23159042023-03-01 14:14:09375 // Clear the fd.
376 uint64_t value;
377 long ret = read(delayed_fd_, &value, sizeof(value));
Michael Thiessen7c36083d2018-08-10 20:24:54378
François Doray23159042023-03-01 14:14:09379 // TODO(mthiesse): Figure out how it's possible to hit EAGAIN here.
380 // According to http://man7.org/linux/man-pages/man2/timerfd_create.2.html
381 // EAGAIN only happens if no timer has expired. Also according to the man page
382 // poll only returns readable when a timer has expired. So this function will
383 // only be called when a timer has expired, but reading reveals no timer has
384 // expired...
385 // Quit() and ScheduleDelayedWork() are the only other functions that touch
386 // the timerfd, and they both run on the same thread as this callback, so
387 // there are no obvious timing or multi-threading related issues.
388 DPCHECK(ret >= 0 || errno == EAGAIN);
Aaron Colwell48c4d5072020-11-13 16:45:03389 DoDelayedLooperWork();
390}
Michael Thiessen7c36083d2018-08-10 20:24:54391
Egor Pasko6da5a07c2024-03-11 19:56:29392void MessagePumpAndroid::DoDelayedLooperWork() {
Gabriel Charette9d44a9b2019-04-29 16:35:56393 delayed_scheduled_time_.reset();
[email protected]61c86c62011-08-02 16:11:16394
Etienne Pierre-doray2163f3012020-04-02 21:37:14395 Delegate::NextWorkInfo next_work_info = delegate_->DoWork();
Gabriel Charette9d44a9b2019-04-29 16:35:56396
Peter Kasting134ef9af2024-12-28 02:30:09397 if (ShouldQuit()) {
Michael Thiessend7ae7352018-07-10 00:57:13398 return;
Peter Kasting134ef9af2024-12-28 02:30:09399 }
Gabriel Charette9d44a9b2019-04-29 16:35:56400
401 if (next_work_info.is_immediate()) {
402 ScheduleWork();
403 return;
404 }
405
Olivier Lic01b21342024-05-27 16:19:35406 delegate_->DoIdleWork();
Peter Kasting134ef9af2024-12-28 02:30:09407 if (!next_work_info.delayed_run_time.is_max()) {
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33408 ScheduleDelayedWork(next_work_info);
Peter Kasting134ef9af2024-12-28 02:30:09409 }
Michael Thiessend7ae7352018-07-10 00:57:13410}
411
Egor Pasko6da5a07c2024-03-11 19:56:29412void MessagePumpAndroid::OnNonDelayedLooperCallback() {
Egor Paskoac4913e2024-10-22 12:03:04413 OnReturnFromLooper();
Torne (Richard Coles)c6993a032020-02-19 13:23:47414 // There may be non-Chromium callbacks on the same ALooper which may have left
415 // a pending exception set, and ALooper does not check for this between
416 // callbacks. Check here, and if there's already an exception, just skip this
417 // iteration without clearing the fd. If the exception ends up being non-fatal
418 // then we'll just get called again on the next polling iteration.
Peter Kasting134ef9af2024-12-28 02:30:09419 if (base::android::HasException(env_)) {
Torne (Richard Coles)c6993a032020-02-19 13:23:47420 return;
Peter Kasting134ef9af2024-12-28 02:30:09421 }
Torne (Richard Coles)c6993a032020-02-19 13:23:47422
Gabriel Charette9d44a9b2019-04-29 16:35:56423 // ALooper_pollOnce may call this after Quit() if OnDelayedLooperCallback()
424 // resulted in Quit() in the same round.
Peter Kasting134ef9af2024-12-28 02:30:09425 if (ShouldQuit()) {
Michael Thiessend7ae7352018-07-10 00:57:13426 return;
Peter Kasting134ef9af2024-12-28 02:30:09427 }
Michael Thiessend7ae7352018-07-10 00:57:13428
Gabriel Charette9d44a9b2019-04-29 16:35:56429 // We're about to process all the work requested by ScheduleWork().
430 // MessagePump users are expected to do their best not to invoke
Etienne Pierre-doray2163f3012020-04-02 21:37:14431 // ScheduleWork() again before DoWork() returns a non-immediate
Gabriel Charette9d44a9b2019-04-29 16:35:56432 // NextWorkInfo below. Hence, capturing the file descriptor's value now and
433 // resetting its contents to 0 should be okay. The value currently stored
434 // should be greater than 0 since work having been scheduled is the reason
435 // we're here. See http://man7.org/linux/man-pages/man2/eventfd.2.html
Aaron Colwell48c4d5072020-11-13 16:45:03436 uint64_t value = 0;
Peter Kasting2f61c8b2022-07-19 23:43:46437 long ret = read(non_delayed_fd_, &value, sizeof(value));
Gabriel Charette9d44a9b2019-04-29 16:35:56438 DPCHECK(ret >= 0);
Aaron Colwell48c4d5072020-11-13 16:45:03439 DCHECK_GT(value, 0U);
Gabriel Charette300f16792022-07-06 20:03:30440 bool do_idle_work = value == kTryNativeWorkBeforeIdleBit;
Aaron Colwell48c4d5072020-11-13 16:45:03441 DoNonDelayedLooperWork(do_idle_work);
442}
Gabriel Charette9d44a9b2019-04-29 16:35:56443
Egor Pasko6da5a07c2024-03-11 19:56:29444void MessagePumpAndroid::DoNonDelayedLooperWork(bool do_idle_work) {
Aaron Colwell48c4d5072020-11-13 16:45:03445 // Note: We can't skip DoWork() even if |do_idle_work| is true here (i.e. no
446 // additional ScheduleWork() since yielding to native) as delayed tasks might
447 // have come in and we need to re-sample |next_work_info|.
Gabriel Charette9d44a9b2019-04-29 16:35:56448
449 // Runs all application tasks scheduled to run.
450 Delegate::NextWorkInfo next_work_info;
451 do {
Peter Kasting134ef9af2024-12-28 02:30:09452 if (ShouldQuit()) {
Gabriel Charette9d44a9b2019-04-29 16:35:56453 return;
Peter Kasting134ef9af2024-12-28 02:30:09454 }
Gabriel Charette9d44a9b2019-04-29 16:35:56455
Etienne Pierre-doray2163f3012020-04-02 21:37:14456 next_work_info = delegate_->DoWork();
Egor Pasko16859192024-03-11 12:20:56457
Egor Pasko16859192024-03-11 12:20:56458 // As an optimization, yield to the Looper when input events are waiting to
459 // be handled. In some cases input events can remain undetected. Such "input
460 // hint false negatives" happen, for example, during initialization, in
461 // multi-window cases, or when a previous value is cached to throttle
462 // polling the input channel.
Egor Paskod68d0032024-06-27 18:18:56463 if (is_type_ui_ && next_work_info.is_immediate() &&
Egor Paskoac4913e2024-10-22 12:03:04464 InputHintChecker::HasInput()) {
465 InputHintChecker::GetInstance().set_is_after_input_yield(true);
Egor Pasko16859192024-03-11 12:20:56466 ScheduleWork();
467 return;
468 }
Gabriel Charette9d44a9b2019-04-29 16:35:56469 } while (next_work_info.is_immediate());
470
471 // Do not resignal |non_delayed_fd_| if we're quitting (this pump doesn't
472 // allow nesting so needing to resume in an outer loop is not an issue
473 // either).
Peter Kasting134ef9af2024-12-28 02:30:09474 if (ShouldQuit()) {
Gabriel Charette9d44a9b2019-04-29 16:35:56475 return;
Peter Kasting134ef9af2024-12-28 02:30:09476 }
Gabriel Charette9d44a9b2019-04-29 16:35:56477
Sean Maheracb46d72024-05-16 17:22:15478 // Under the fast to sleep feature, `do_idle_work` is ignored, and the pump
479 // will always "sleep" after finishing all its work items.
480 if (!g_fast_to_sleep) {
481 // Before declaring this loop idle, yield to native work items and arrange
482 // to be called again (unless we're already in that second call).
483 if (!do_idle_work) {
484 ScheduleWorkInternal(/*do_idle_work=*/true);
485 return;
486 }
487
488 // We yielded to native work items already and they didn't generate a
489 // ScheduleWork() request so we can declare idleness. It's possible for a
490 // ScheduleWork() request to come in racily while this method unwinds, this
491 // is fine and will merely result in it being re-invoked shortly after it
492 // returns.
493 // TODO(scheduler-dev): this doesn't account for tasks that don't ever call
494 // SchedulerWork() but still keep the system non-idle (e.g., the Java
495 // Handler API). It would be better to add an API to query the presence of
496 // native tasks instead of relying on yielding once +
497 // kTryNativeWorkBeforeIdleBit.
498 DCHECK(do_idle_work);
Michael Thiessend7ae7352018-07-10 00:57:13499 }
Gabriel Charette9d44a9b2019-04-29 16:35:56500
Sean Maheracb46d72024-05-16 17:22:15501 if (ShouldQuit()) {
Gabriel Charette9d44a9b2019-04-29 16:35:56502 return;
Sean Maheracb46d72024-05-16 17:22:15503 }
Gabriel Charette9d44a9b2019-04-29 16:35:56504
Egor Pasko264bacd2024-11-08 15:29:11505 // Do the idle work.
506 //
507 // At this point, the Java Looper might not be idle. It is possible to skip
508 // idle work if !MessageQueue.isIdle(), but this check is not very accurate
509 // because the MessageQueue does not know about the additional tasks
510 // potentially waiting in the Looper.
511 //
512 // Note that this won't cause us to fail to run java tasks using QuitWhenIdle,
513 // as the JavaHandlerThread will finish running all currently scheduled tasks
514 // before it quits. Also note that we can't just add an idle callback to the
515 // java looper, as that will fire even if application tasks are still queued
516 // up.
Olivier Lic01b21342024-05-27 16:19:35517 delegate_->DoIdleWork();
Stephen Nusko408b9a92022-09-15 10:03:57518 if (!next_work_info.delayed_run_time.is_max()) {
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33519 ScheduleDelayedWork(next_work_info);
Stephen Nusko408b9a92022-09-15 10:03:57520 }
Michael Thiessend7ae7352018-07-10 00:57:13521}
522
Egor Pasko6da5a07c2024-03-11 19:56:29523void MessagePumpAndroid::Run(Delegate* delegate) {
Peter Boström54119652024-11-14 00:16:38524 NOTREACHED() << "Unexpected call to Run()";
[email protected]61c86c62011-08-02 16:11:16525}
526
Egor Pasko6da5a07c2024-03-11 19:56:29527void MessagePumpAndroid::Attach(Delegate* delegate) {
Michael Thiessendbeca242017-08-28 21:10:08528 DCHECK(!quit_);
Michael Thiessend7ae7352018-07-10 00:57:13529
530 // Since the Looper is controlled by the UI thread or JavaHandlerThread, we
531 // can't use Run() like we do on other platforms or we would prevent Java
532 // tasks from running. Instead we create and initialize a run loop here, then
533 // return control back to the Looper.
534
535 SetDelegate(delegate);
Michael Thiessen781ddeb2017-11-15 17:07:23536 run_loop_ = std::make_unique<RunLoop>();
[email protected]8e937c1e2012-06-28 22:57:30537 // Since the RunLoop was just created above, BeforeRun should be guaranteed to
538 // return true (it only returns false if the RunLoop has been Quit already).
Adam Riced47f4982024-09-03 16:18:23539 CHECK(run_loop_->BeforeRun());
[email protected]61c86c62011-08-02 16:11:16540}
541
Egor Pasko6da5a07c2024-03-11 19:56:29542void MessagePumpAndroid::Quit() {
Peter Kasting134ef9af2024-12-28 02:30:09543 if (quit_) {
Michael Thiessend7ae7352018-07-10 00:57:13544 return;
Peter Kasting134ef9af2024-12-28 02:30:09545 }
Michael Thiessend7ae7352018-07-10 00:57:13546
Michael Thiessendbeca242017-08-28 21:10:08547 quit_ = true;
Michael Thiessen781ddeb2017-11-15 17:07:23548
Michael Thiessend7ae7352018-07-10 00:57:13549 int64_t value;
550 // Clear any pending timer.
551 read(delayed_fd_, &value, sizeof(value));
552 // Clear the eventfd.
553 read(non_delayed_fd_, &value, sizeof(value));
[email protected]61c86c62011-08-02 16:11:16554
[email protected]8e937c1e2012-06-28 22:57:30555 if (run_loop_) {
556 run_loop_->AfterRun();
Michael Thiessen781ddeb2017-11-15 17:07:23557 run_loop_ = nullptr;
[email protected]61c86c62011-08-02 16:11:16558 }
Michael Thiessend7ae7352018-07-10 00:57:13559 if (on_quit_callback_) {
560 std::move(on_quit_callback_).Run();
561 }
[email protected]61c86c62011-08-02 16:11:16562}
563
Egor Pasko6da5a07c2024-03-11 19:56:29564void MessagePumpAndroid::ScheduleWork() {
Aaron Colwell48c4d5072020-11-13 16:45:03565 ScheduleWorkInternal(/*do_idle_work=*/false);
566}
567
Egor Pasko6da5a07c2024-03-11 19:56:29568void MessagePumpAndroid::ScheduleWorkInternal(bool do_idle_work) {
Aaron Colwell48c4d5072020-11-13 16:45:03569 // Write (add) |value| to the eventfd. This tells the Looper to wake up and
570 // call our callback, allowing us to run tasks. This also allows us to detect,
571 // when we clear the fd, whether additional work was scheduled after we
572 // finished performing work, but before we cleared the fd, as we'll read back
573 // >=2 instead of 1 in that case. See the eventfd man pages
Michael Thiessend7ae7352018-07-10 00:57:13574 // (http://man7.org/linux/man-pages/man2/eventfd.2.html) for details on how
575 // the read and write APIs for this file descriptor work, specifically without
576 // EFD_SEMAPHORE.
Aaron Colwell48c4d5072020-11-13 16:45:03577 // Note: Calls with |do_idle_work| set to true may race with potential calls
François Doray23159042023-03-01 14:14:09578 // where the parameter is false. This is fine as write() is adding |value|,
579 // not overwriting the existing value, and as such racing calls would merely
580 // have their values added together. Since idle work is only executed when the
581 // value read equals kTryNativeWorkBeforeIdleBit, a race would prevent idle
582 // work from being run and trigger another call to this method with
583 // |do_idle_work| set to true.
Gabriel Charette300f16792022-07-06 20:03:30584 uint64_t value = do_idle_work ? kTryNativeWorkBeforeIdleBit : 1;
Peter Kasting2f61c8b2022-07-19 23:43:46585 long ret = write(non_delayed_fd_, &value, sizeof(value));
Michael Thiessen7c36083d2018-08-10 20:24:54586 DPCHECK(ret >= 0);
[email protected]61c86c62011-08-02 16:11:16587}
588
Egor Paskoac4913e2024-10-22 12:03:04589void MessagePumpAndroid::OnReturnFromLooper() {
590 if (!is_type_ui_) {
591 return;
592 }
593 auto& checker = InputHintChecker::GetInstance();
594 if (checker.is_after_input_yield()) {
Egor Pasko9396dfd2025-03-10 16:30:18595 InputHintChecker::GetInstance().RecordInputHintResult(
596 InputHintResult::kBackToNative);
Egor Paskoac4913e2024-10-22 12:03:04597 }
598 checker.set_is_after_input_yield(false);
599}
600
Egor Pasko6da5a07c2024-03-11 19:56:29601void MessagePumpAndroid::ScheduleDelayedWork(
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33602 const Delegate::NextWorkInfo& next_work_info) {
Peter Kasting134ef9af2024-12-28 02:30:09603 if (ShouldQuit()) {
Michael Thiessendbeca242017-08-28 21:10:08604 return;
Peter Kasting134ef9af2024-12-28 02:30:09605 }
Michael Thiessend7ae7352018-07-10 00:57:13606
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33607 if (delayed_scheduled_time_ &&
608 *delayed_scheduled_time_ == next_work_info.delayed_run_time) {
Michael Thiessen781ddeb2017-11-15 17:07:23609 return;
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33610 }
Michael Thiessend7ae7352018-07-10 00:57:13611
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33612 DCHECK(!next_work_info.is_immediate());
613 delayed_scheduled_time_ = next_work_info.delayed_run_time;
François Doray23159042023-03-01 14:14:09614 int64_t nanos =
615 next_work_info.delayed_run_time.since_origin().InNanoseconds();
616 struct itimerspec ts;
617 ts.it_interval.tv_sec = 0; // Don't repeat.
618 ts.it_interval.tv_nsec = 0;
619 ts.it_value.tv_sec =
620 static_cast<time_t>(nanos / TimeTicks::kNanosecondsPerSecond);
621 ts.it_value.tv_nsec = nanos % TimeTicks::kNanosecondsPerSecond;
622
Peter Kasting2f61c8b2022-07-19 23:43:46623 long ret = timerfd_settime(delayed_fd_, TFD_TIMER_ABSTIME, &ts, nullptr);
Michael Thiessen7c36083d2018-08-10 20:24:54624 DPCHECK(ret >= 0);
Michael Thiessend7ae7352018-07-10 00:57:13625}
626
Ken Rockota2c5d792024-11-28 20:05:22627IOWatcher* MessagePumpAndroid::GetIOWatcher() {
628 if (!io_watcher_) {
629 io_watcher_ = std::make_unique<IOWatcherImpl>(looper_);
630 }
631 return io_watcher_.get();
632}
633
Egor Pasko6da5a07c2024-03-11 19:56:29634void MessagePumpAndroid::QuitWhenIdle(base::OnceClosure callback) {
Michael Thiessend7ae7352018-07-10 00:57:13635 DCHECK(!on_quit_callback_);
636 DCHECK(run_loop_);
637 on_quit_callback_ = std::move(callback);
638 run_loop_->QuitWhenIdle();
639 // Pump the loop in case we're already idle.
640 ScheduleWork();
641}
642
Egor Pasko6da5a07c2024-03-11 19:56:29643MessagePump::Delegate* MessagePumpAndroid::SetDelegate(Delegate* delegate) {
Aaron Colwell48c4d5072020-11-13 16:45:03644 return std::exchange(delegate_, delegate);
645}
646
Egor Pasko6da5a07c2024-03-11 19:56:29647bool MessagePumpAndroid::SetQuit(bool quit) {
Aaron Colwell48c4d5072020-11-13 16:45:03648 return std::exchange(quit_, quit);
649}
650
[email protected]61c86c62011-08-02 16:11:16651} // namespace base