blob: 2c4f12c76f34ba5e13319920069ba10863819ef0 [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"
Chidera Olibief2c65162025-07-02 21:07:3024#include "base/android/yield_to_looper_checker.h"
Adam Riced47f4982024-09-03 16:18:2325#include "base/check.h"
Hans Wennborgc3cffa62020-04-27 10:09:1226#include "base/check_op.h"
Ken Rockota2c5d792024-11-28 20:05:2227#include "base/message_loop/io_watcher.h"
Peter Boström54119652024-11-14 00:16:3828#include "base/notreached.h"
Peter Kasting2f61c8b2022-07-19 23:43:4629#include "base/numerics/safe_conversions.h"
[email protected]8e937c1e2012-06-28 22:57:3030#include "base/run_loop.h"
Sean Maheracb46d72024-05-16 17:22:1531#include "base/task/task_features.h"
Egor Pasko16859192024-03-11 12:20:5632#include "base/time/time.h"
Michael Thiessen6fd43902018-08-30 23:14:1533#include "build/build_config.h"
Michael Thiessend7ae7352018-07-10 00:57:1334
Egor Paskoac4913e2024-10-22 12:03:0435using base::android::InputHintChecker;
36using base::android::InputHintResult;
Chidera Olibief2c65162025-07-02 21:07:3037using base::android::YieldToLooperChecker;
Egor Paskoac4913e2024-10-22 12:03:0438
Michael Thiessen781ddeb2017-11-15 17:07:2339namespace base {
40
Michael Thiessend7ae7352018-07-10 00:57:1341namespace {
Michael Thiessen781ddeb2017-11-15 17:07:2342
Michael Thiessen6fd43902018-08-30 23:14:1543// https://crbug.com/873588. The stack may not be aligned when the ALooper calls
44// into our code due to the inconsistent ABI on older Android OS versions.
Egor Pasko30c67b62024-03-22 17:55:5745//
46// https://crbug.com/330761384#comment3. Calls from libutils.so into
47// NonDelayedLooperCallback() and DelayedLooperCallback() confuse aarch64 builds
48// with orderfile instrumentation causing incorrect value in
49// __builtin_return_address(0). Disable instrumentation for them. TODO(pasko):
50// Add these symbols to the orderfile manually or fix the builtin.
Michael Thiessen6fd43902018-08-30 23:14:1551#if defined(ARCH_CPU_X86)
Egor Pasko30c67b62024-03-22 17:55:5752#define NO_INSTRUMENT_STACK_ALIGN \
53 __attribute__((force_align_arg_pointer, no_instrument_function))
Michael Thiessen6fd43902018-08-30 23:14:1554#else
Egor Pasko30c67b62024-03-22 17:55:5755#define NO_INSTRUMENT_STACK_ALIGN __attribute__((no_instrument_function))
Michael Thiessen6fd43902018-08-30 23:14:1556#endif
57
Egor Pasko30c67b62024-03-22 17:55:5758NO_INSTRUMENT_STACK_ALIGN int NonDelayedLooperCallback(int fd,
59 int events,
60 void* data) {
Peter Kasting134ef9af2024-12-28 02:30:0961 if (events & ALOOPER_EVENT_HANGUP) {
Michael Thiessend7ae7352018-07-10 00:57:1362 return 0;
Peter Kasting134ef9af2024-12-28 02:30:0963 }
Michael Thiessend7ae7352018-07-10 00:57:1364
65 DCHECK(events & ALOOPER_EVENT_INPUT);
Egor Pasko6da5a07c2024-03-11 19:56:2966 MessagePumpAndroid* pump = reinterpret_cast<MessagePumpAndroid*>(data);
Michael Thiessend7ae7352018-07-10 00:57:1367 pump->OnNonDelayedLooperCallback();
68 return 1; // continue listening for events
69}
70
Egor Pasko30c67b62024-03-22 17:55:5771NO_INSTRUMENT_STACK_ALIGN int DelayedLooperCallback(int fd,
72 int events,
73 void* data) {
Peter Kasting134ef9af2024-12-28 02:30:0974 if (events & ALOOPER_EVENT_HANGUP) {
Michael Thiessend7ae7352018-07-10 00:57:1375 return 0;
Peter Kasting134ef9af2024-12-28 02:30:0976 }
Michael Thiessend7ae7352018-07-10 00:57:1377
78 DCHECK(events & ALOOPER_EVENT_INPUT);
Egor Pasko6da5a07c2024-03-11 19:56:2979 MessagePumpAndroid* pump = reinterpret_cast<MessagePumpAndroid*>(data);
Michael Thiessend7ae7352018-07-10 00:57:1380 pump->OnDelayedLooperCallback();
81 return 1; // continue listening for events
82}
83
Aaron Colwell48c4d5072020-11-13 16:45:0384// A bit added to the |non_delayed_fd_| to keep it signaled when we yield to
Gabriel Charette300f16792022-07-06 20:03:3085// native work below.
86constexpr uint64_t kTryNativeWorkBeforeIdleBit = uint64_t(1) << 32;
Sean Maheracb46d72024-05-16 17:22:1587
88std::atomic_bool g_fast_to_sleep = false;
Ken Rockota2c5d792024-11-28 20:05:2289
90// Implements IOWatcher to allow any MessagePumpAndroid thread to watch
91// arbitrary file descriptors for I/O events.
92class IOWatcherImpl : public IOWatcher {
93 public:
94 explicit IOWatcherImpl(ALooper* looper) : looper_(looper) {}
95
96 ~IOWatcherImpl() override {
97 for (auto& [fd, watches] : watched_fds_) {
98 ALooper_removeFd(looper_, fd);
99 if (auto read_watch = std::exchange(watches.read_watch, nullptr)) {
100 read_watch->Detach();
101 }
102 if (auto write_watch = std::exchange(watches.write_watch, nullptr)) {
103 write_watch->Detach();
104 }
105 }
106 }
107
108 // IOWatcher:
109 std::unique_ptr<IOWatcher::FdWatch> WatchFileDescriptorImpl(
110 int fd,
111 FdWatchDuration duration,
112 FdWatchMode mode,
113 IOWatcher::FdWatcher& watcher,
114 const Location& location) override {
115 auto& watches = watched_fds_[fd];
116 auto watch = std::make_unique<FdWatchImpl>(*this, fd, duration, watcher);
117 if (mode == FdWatchMode::kRead || mode == FdWatchMode::kReadWrite) {
118 CHECK(!watches.read_watch) << "Only one watch per FD per condition.";
119 watches.read_watch = watch.get();
120 }
121 if (mode == FdWatchMode::kWrite || mode == FdWatchMode::kReadWrite) {
122 CHECK(!watches.write_watch) << "Only one watch per FD per condition.";
123 watches.write_watch = watch.get();
124 }
125
126 const int events = (watches.read_watch ? ALOOPER_EVENT_INPUT : 0) |
127 (watches.write_watch ? ALOOPER_EVENT_OUTPUT : 0);
128 ALooper_addFd(looper_, fd, 0, events, &OnFdIoEvent, this);
129 return watch;
130 }
131
132 private:
133 // Scopes the maximum lifetime of an FD watch started by WatchFileDescriptor.
134 class FdWatchImpl : public FdWatch {
135 public:
136 FdWatchImpl(IOWatcherImpl& io_watcher,
137 int fd,
138 FdWatchDuration duration,
139 FdWatcher& fd_watcher)
140 : fd_(fd),
141 duration_(duration),
142 fd_watcher_(fd_watcher),
143 io_watcher_(&io_watcher) {}
144
145 ~FdWatchImpl() override {
146 Stop();
147 if (destruction_flag_) {
148 *destruction_flag_ = true;
149 }
150 }
151
152 void set_destruction_flag(bool* flag) { destruction_flag_ = flag; }
153 int fd() const { return fd_; }
154 FdWatcher& fd_watcher() const { return *fd_watcher_; }
155
156 bool is_persistent() const {
157 return duration_ == FdWatchDuration::kPersistent;
158 }
159
160 void Detach() { io_watcher_ = nullptr; }
161
162 void Stop() {
163 if (io_watcher_) {
164 std::exchange(io_watcher_, nullptr)->StopWatching(*this);
165 }
166 }
167
168 private:
169 const int fd_;
170 const FdWatchDuration duration_;
171 raw_ref<FdWatcher> fd_watcher_;
172 raw_ptr<IOWatcherImpl> io_watcher_;
173
174 // If non-null during destruction, the pointee is set to true. Used to
175 // detect reentrant destruction during dispatch.
176 raw_ptr<bool> destruction_flag_ = nullptr;
177 };
178
179 enum class EventResult {
180 kStopWatching,
181 kKeepWatching,
182 };
183
184 static NO_INSTRUMENT_STACK_ALIGN int OnFdIoEvent(int fd,
185 int events,
186 void* data) {
187 switch (static_cast<IOWatcherImpl*>(data)->HandleEvent(fd, events)) {
188 case EventResult::kStopWatching:
189 return 0;
190 case EventResult::kKeepWatching:
191 return 1;
192 }
193 }
194
195 EventResult HandleEvent(int fd, int events) {
196 // NOTE: It is possible for Looper to dispatch one last event for `fd`
197 // *after* we have removed the FD from the Looper - for example if multiple
198 // FDs wake the thread at the same time, and a handler for another FD runs
199 // first and removes the watch for `fd`; this callback will have already
200 // been queued for `fd` and will still run. As such, we must gracefully
201 // tolerate receiving a callback for an FD that is no longer watched.
202 auto it = watched_fds_.find(fd);
203 if (it == watched_fds_.end()) {
204 return EventResult::kStopWatching;
205 }
206
207 auto& watches = it->second;
208 const bool is_readable =
209 events & (ALOOPER_EVENT_INPUT | ALOOPER_EVENT_HANGUP);
210 const bool is_writable =
211 events & (ALOOPER_EVENT_OUTPUT | ALOOPER_EVENT_HANGUP);
212 auto* read_watch = watches.read_watch.get();
213 auto* write_watch = watches.write_watch.get();
214
215 // Any event dispatch can stop any number of watches, so we're careful to
216 // set up destruction observation before dispatching anything.
217 bool read_watch_destroyed = false;
218 bool write_watch_destroyed = false;
219 bool fd_removed = false;
220 if (read_watch) {
221 read_watch->set_destruction_flag(&read_watch_destroyed);
222 }
223 if (write_watch && read_watch != write_watch) {
224 write_watch->set_destruction_flag(&write_watch_destroyed);
225 }
226 watches.removed_flag = &fd_removed;
227
228 bool did_observe_one_shot_read = false;
229 if (read_watch && is_readable) {
230 DCHECK_EQ(read_watch->fd(), fd);
231 did_observe_one_shot_read = !read_watch->is_persistent();
232 read_watch->fd_watcher().OnFdReadable(fd);
233 if (!read_watch_destroyed && did_observe_one_shot_read) {
234 read_watch->Stop();
235 }
236 }
237
238 // If the read and write watches are the same object, it may have been
239 // destroyed; or it may have been a one-shot watch already consumed by a
240 // read above. In either case we inhibit write dispatch.
241 if (read_watch == write_watch &&
242 (read_watch_destroyed || did_observe_one_shot_read)) {
243 write_watch = nullptr;
244 }
245
246 if (write_watch && is_writable && !write_watch_destroyed) {
247 DCHECK_EQ(write_watch->fd(), fd);
248 const bool is_persistent = write_watch->is_persistent();
249 write_watch->fd_watcher().OnFdWritable(fd);
250 if (!write_watch_destroyed && !is_persistent) {
251 write_watch->Stop();
252 }
253 }
254
255 if (read_watch && !read_watch_destroyed) {
256 read_watch->set_destruction_flag(nullptr);
257 }
258 if (write_watch && !write_watch_destroyed) {
259 write_watch->set_destruction_flag(nullptr);
260 }
261
262 if (fd_removed) {
263 return EventResult::kStopWatching;
264 }
265
266 watches.removed_flag = nullptr;
267 return EventResult::kKeepWatching;
268 }
269
270 void StopWatching(FdWatchImpl& watch) {
271 const int fd = watch.fd();
272 auto it = watched_fds_.find(fd);
273 if (it == watched_fds_.end()) {
274 return;
275 }
276
277 WatchPair& watches = it->second;
278 if (watches.read_watch == &watch) {
279 watches.read_watch = nullptr;
280 }
281 if (watches.write_watch == &watch) {
282 watches.write_watch = nullptr;
283 }
284
285 const int remaining_events =
286 (watches.read_watch ? ALOOPER_EVENT_INPUT : 0) |
287 (watches.write_watch ? ALOOPER_EVENT_OUTPUT : 0);
288 if (remaining_events) {
289 ALooper_addFd(looper_, fd, 0, remaining_events, &OnFdIoEvent, this);
290 return;
291 }
292
293 ALooper_removeFd(looper_, fd);
294 if (watches.removed_flag) {
295 *watches.removed_flag = true;
296 }
297 watched_fds_.erase(it);
298 }
299
300 private:
301 const raw_ptr<ALooper> looper_;
302
303 // The set of active FdWatches. Note that each FD may have up to two active
304 // watches only - one for read and one for write. No two FdWatches can watch
305 // the same FD for the same signal. `read_watch` and `write_watch` may point
306 // to the same object.
307 struct WatchPair {
308 raw_ptr<FdWatchImpl> read_watch = nullptr;
309 raw_ptr<FdWatchImpl> write_watch = nullptr;
310
311 // If non-null when this WatchPair is removed, the pointee is set to true.
312 // Used to track reentrant map mutations during dispatch.
313 raw_ptr<bool> removed_flag = nullptr;
314 };
315 std::map<int, WatchPair> watched_fds_;
316};
317
Michael Thiessend7ae7352018-07-10 00:57:13318} // namespace
319
Egor Pasko6da5a07c2024-03-11 19:56:29320MessagePumpAndroid::MessagePumpAndroid()
François Doray253a3062022-10-24 16:45:29321 : env_(base::android::AttachCurrentThread()) {
Michael Thiessend7ae7352018-07-10 00:57:13322 // The Android native ALooper uses epoll to poll our file descriptors and wake
323 // us up. We use a simple level-triggered eventfd to signal that non-delayed
324 // work is available, and a timerfd to signal when delayed work is ready to
325 // be run.
326 non_delayed_fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
327 CHECK_NE(non_delayed_fd_, -1);
328 DCHECK_EQ(TimeTicks::GetClock(), TimeTicks::Clock::LINUX_CLOCK_MONOTONIC);
329
Peter Kasting2f61c8b2022-07-19 23:43:46330 delayed_fd_ = checked_cast<int>(
Egor Pasko47ff68432023-04-05 18:23:57331 timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC));
Michael Thiessend7ae7352018-07-10 00:57:13332 CHECK_NE(delayed_fd_, -1);
333
334 looper_ = ALooper_prepare(0);
335 DCHECK(looper_);
336 // Add a reference to the looper so it isn't deleted on us.
337 ALooper_acquire(looper_);
338 ALooper_addFd(looper_, non_delayed_fd_, 0, ALOOPER_EVENT_INPUT,
339 &NonDelayedLooperCallback, reinterpret_cast<void*>(this));
340 ALooper_addFd(looper_, delayed_fd_, 0, ALOOPER_EVENT_INPUT,
341 &DelayedLooperCallback, reinterpret_cast<void*>(this));
342}
343
Egor Pasko6da5a07c2024-03-11 19:56:29344MessagePumpAndroid::~MessagePumpAndroid() {
Michael Thiessend7ae7352018-07-10 00:57:13345 DCHECK_EQ(ALooper_forThread(), looper_);
Ken Rockota2c5d792024-11-28 20:05:22346 io_watcher_.reset();
Michael Thiessend7ae7352018-07-10 00:57:13347 ALooper_removeFd(looper_, non_delayed_fd_);
348 ALooper_removeFd(looper_, delayed_fd_);
349 ALooper_release(looper_);
350 looper_ = nullptr;
351
352 close(non_delayed_fd_);
353 close(delayed_fd_);
354}
355
Sean Maheracb46d72024-05-16 17:22:15356void MessagePumpAndroid::InitializeFeatures() {
357 g_fast_to_sleep = base::FeatureList::IsEnabled(kPumpFastToSleepAndroid);
358}
359
Egor Pasko6da5a07c2024-03-11 19:56:29360void MessagePumpAndroid::OnDelayedLooperCallback() {
Egor Paskoac4913e2024-10-22 12:03:04361 OnReturnFromLooper();
Torne (Richard Coles)c6993a032020-02-19 13:23:47362 // There may be non-Chromium callbacks on the same ALooper which may have left
363 // a pending exception set, and ALooper does not check for this between
364 // callbacks. Check here, and if there's already an exception, just skip this
365 // iteration without clearing the fd. If the exception ends up being non-fatal
366 // then we'll just get called again on the next polling iteration.
Peter Kasting134ef9af2024-12-28 02:30:09367 if (base::android::HasException(env_)) {
Torne (Richard Coles)c6993a032020-02-19 13:23:47368 return;
Peter Kasting134ef9af2024-12-28 02:30:09369 }
Torne (Richard Coles)c6993a032020-02-19 13:23:47370
Gabriel Charette9d44a9b2019-04-29 16:35:56371 // ALooper_pollOnce may call this after Quit() if OnNonDelayedLooperCallback()
372 // resulted in Quit() in the same round.
Peter Kasting134ef9af2024-12-28 02:30:09373 if (ShouldQuit()) {
Michael Thiessenfc7067fe2017-11-01 22:33:01374 return;
Peter Kasting134ef9af2024-12-28 02:30:09375 }
Michael Thiessenfc7067fe2017-11-01 22:33:01376
François Doray23159042023-03-01 14:14:09377 // Clear the fd.
378 uint64_t value;
379 long ret = read(delayed_fd_, &value, sizeof(value));
Michael Thiessen7c36083d2018-08-10 20:24:54380
François Doray23159042023-03-01 14:14:09381 // TODO(mthiesse): Figure out how it's possible to hit EAGAIN here.
382 // According to http://man7.org/linux/man-pages/man2/timerfd_create.2.html
383 // EAGAIN only happens if no timer has expired. Also according to the man page
384 // poll only returns readable when a timer has expired. So this function will
385 // only be called when a timer has expired, but reading reveals no timer has
386 // expired...
387 // Quit() and ScheduleDelayedWork() are the only other functions that touch
388 // the timerfd, and they both run on the same thread as this callback, so
389 // there are no obvious timing or multi-threading related issues.
390 DPCHECK(ret >= 0 || errno == EAGAIN);
Aaron Colwell48c4d5072020-11-13 16:45:03391 DoDelayedLooperWork();
392}
Michael Thiessen7c36083d2018-08-10 20:24:54393
Egor Pasko6da5a07c2024-03-11 19:56:29394void MessagePumpAndroid::DoDelayedLooperWork() {
Gabriel Charette9d44a9b2019-04-29 16:35:56395 delayed_scheduled_time_.reset();
[email protected]61c86c62011-08-02 16:11:16396
Etienne Pierre-doray2163f3012020-04-02 21:37:14397 Delegate::NextWorkInfo next_work_info = delegate_->DoWork();
Gabriel Charette9d44a9b2019-04-29 16:35:56398
Peter Kasting134ef9af2024-12-28 02:30:09399 if (ShouldQuit()) {
Michael Thiessend7ae7352018-07-10 00:57:13400 return;
Peter Kasting134ef9af2024-12-28 02:30:09401 }
Gabriel Charette9d44a9b2019-04-29 16:35:56402
403 if (next_work_info.is_immediate()) {
404 ScheduleWork();
405 return;
406 }
407
Olivier Lic01b21342024-05-27 16:19:35408 delegate_->DoIdleWork();
Peter Kasting134ef9af2024-12-28 02:30:09409 if (!next_work_info.delayed_run_time.is_max()) {
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33410 ScheduleDelayedWork(next_work_info);
Peter Kasting134ef9af2024-12-28 02:30:09411 }
Michael Thiessend7ae7352018-07-10 00:57:13412}
413
Egor Pasko6da5a07c2024-03-11 19:56:29414void MessagePumpAndroid::OnNonDelayedLooperCallback() {
Egor Paskoac4913e2024-10-22 12:03:04415 OnReturnFromLooper();
Torne (Richard Coles)c6993a032020-02-19 13:23:47416 // There may be non-Chromium callbacks on the same ALooper which may have left
417 // a pending exception set, and ALooper does not check for this between
418 // callbacks. Check here, and if there's already an exception, just skip this
419 // iteration without clearing the fd. If the exception ends up being non-fatal
420 // then we'll just get called again on the next polling iteration.
Peter Kasting134ef9af2024-12-28 02:30:09421 if (base::android::HasException(env_)) {
Torne (Richard Coles)c6993a032020-02-19 13:23:47422 return;
Peter Kasting134ef9af2024-12-28 02:30:09423 }
Torne (Richard Coles)c6993a032020-02-19 13:23:47424
Gabriel Charette9d44a9b2019-04-29 16:35:56425 // ALooper_pollOnce may call this after Quit() if OnDelayedLooperCallback()
426 // resulted in Quit() in the same round.
Peter Kasting134ef9af2024-12-28 02:30:09427 if (ShouldQuit()) {
Michael Thiessend7ae7352018-07-10 00:57:13428 return;
Peter Kasting134ef9af2024-12-28 02:30:09429 }
Michael Thiessend7ae7352018-07-10 00:57:13430
Gabriel Charette9d44a9b2019-04-29 16:35:56431 // We're about to process all the work requested by ScheduleWork().
432 // MessagePump users are expected to do their best not to invoke
Etienne Pierre-doray2163f3012020-04-02 21:37:14433 // ScheduleWork() again before DoWork() returns a non-immediate
Gabriel Charette9d44a9b2019-04-29 16:35:56434 // NextWorkInfo below. Hence, capturing the file descriptor's value now and
435 // resetting its contents to 0 should be okay. The value currently stored
436 // should be greater than 0 since work having been scheduled is the reason
437 // we're here. See http://man7.org/linux/man-pages/man2/eventfd.2.html
Aaron Colwell48c4d5072020-11-13 16:45:03438 uint64_t value = 0;
Peter Kasting2f61c8b2022-07-19 23:43:46439 long ret = read(non_delayed_fd_, &value, sizeof(value));
Gabriel Charette9d44a9b2019-04-29 16:35:56440 DPCHECK(ret >= 0);
Aaron Colwell48c4d5072020-11-13 16:45:03441 DCHECK_GT(value, 0U);
Gabriel Charette300f16792022-07-06 20:03:30442 bool do_idle_work = value == kTryNativeWorkBeforeIdleBit;
Aaron Colwell48c4d5072020-11-13 16:45:03443 DoNonDelayedLooperWork(do_idle_work);
444}
Gabriel Charette9d44a9b2019-04-29 16:35:56445
Egor Pasko6da5a07c2024-03-11 19:56:29446void MessagePumpAndroid::DoNonDelayedLooperWork(bool do_idle_work) {
Aaron Colwell48c4d5072020-11-13 16:45:03447 // Note: We can't skip DoWork() even if |do_idle_work| is true here (i.e. no
448 // additional ScheduleWork() since yielding to native) as delayed tasks might
449 // have come in and we need to re-sample |next_work_info|.
Gabriel Charette9d44a9b2019-04-29 16:35:56450
451 // Runs all application tasks scheduled to run.
452 Delegate::NextWorkInfo next_work_info;
453 do {
Peter Kasting134ef9af2024-12-28 02:30:09454 if (ShouldQuit()) {
Gabriel Charette9d44a9b2019-04-29 16:35:56455 return;
Peter Kasting134ef9af2024-12-28 02:30:09456 }
Gabriel Charette9d44a9b2019-04-29 16:35:56457
Etienne Pierre-doray2163f3012020-04-02 21:37:14458 next_work_info = delegate_->DoWork();
Egor Pasko16859192024-03-11 12:20:56459
Chidera Olibief2c65162025-07-02 21:07:30460 if (is_type_ui_ && next_work_info.is_immediate()) {
461 // To reduce startup ANRs, yield if an embedder signifies that startup is
462 // currently running.
463 if (YieldToLooperChecker::GetInstance().ShouldYield()) {
464 ScheduleWork();
465 return;
466 }
467
468 // As an optimization, yield to the Looper when input events are waiting
469 // to be handled. In some cases input events can remain undetected. Such
470 // "input hint false negatives" happen, for example, during
471 // initialization, in multi-window cases, or when a previous value is
472 // cached to throttle polling the input channel.
473 if (InputHintChecker::HasInput()) {
474 InputHintChecker::GetInstance().set_is_after_input_yield(true);
475 ScheduleWork();
476 return;
477 }
Egor Pasko16859192024-03-11 12:20:56478 }
Gabriel Charette9d44a9b2019-04-29 16:35:56479 } while (next_work_info.is_immediate());
480
481 // Do not resignal |non_delayed_fd_| if we're quitting (this pump doesn't
482 // allow nesting so needing to resume in an outer loop is not an issue
483 // either).
Peter Kasting134ef9af2024-12-28 02:30:09484 if (ShouldQuit()) {
Gabriel Charette9d44a9b2019-04-29 16:35:56485 return;
Peter Kasting134ef9af2024-12-28 02:30:09486 }
Gabriel Charette9d44a9b2019-04-29 16:35:56487
Sean Maheracb46d72024-05-16 17:22:15488 // Under the fast to sleep feature, `do_idle_work` is ignored, and the pump
489 // will always "sleep" after finishing all its work items.
490 if (!g_fast_to_sleep) {
491 // Before declaring this loop idle, yield to native work items and arrange
492 // to be called again (unless we're already in that second call).
493 if (!do_idle_work) {
494 ScheduleWorkInternal(/*do_idle_work=*/true);
495 return;
496 }
497
498 // We yielded to native work items already and they didn't generate a
499 // ScheduleWork() request so we can declare idleness. It's possible for a
500 // ScheduleWork() request to come in racily while this method unwinds, this
501 // is fine and will merely result in it being re-invoked shortly after it
502 // returns.
503 // TODO(scheduler-dev): this doesn't account for tasks that don't ever call
504 // SchedulerWork() but still keep the system non-idle (e.g., the Java
505 // Handler API). It would be better to add an API to query the presence of
506 // native tasks instead of relying on yielding once +
507 // kTryNativeWorkBeforeIdleBit.
508 DCHECK(do_idle_work);
Michael Thiessend7ae7352018-07-10 00:57:13509 }
Gabriel Charette9d44a9b2019-04-29 16:35:56510
Sean Maheracb46d72024-05-16 17:22:15511 if (ShouldQuit()) {
Gabriel Charette9d44a9b2019-04-29 16:35:56512 return;
Sean Maheracb46d72024-05-16 17:22:15513 }
Gabriel Charette9d44a9b2019-04-29 16:35:56514
Egor Pasko264bacd2024-11-08 15:29:11515 // Do the idle work.
516 //
517 // At this point, the Java Looper might not be idle. It is possible to skip
518 // idle work if !MessageQueue.isIdle(), but this check is not very accurate
519 // because the MessageQueue does not know about the additional tasks
520 // potentially waiting in the Looper.
521 //
522 // Note that this won't cause us to fail to run java tasks using QuitWhenIdle,
523 // as the JavaHandlerThread will finish running all currently scheduled tasks
524 // before it quits. Also note that we can't just add an idle callback to the
525 // java looper, as that will fire even if application tasks are still queued
526 // up.
Olivier Lic01b21342024-05-27 16:19:35527 delegate_->DoIdleWork();
Stephen Nusko408b9a92022-09-15 10:03:57528 if (!next_work_info.delayed_run_time.is_max()) {
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33529 ScheduleDelayedWork(next_work_info);
Stephen Nusko408b9a92022-09-15 10:03:57530 }
Michael Thiessend7ae7352018-07-10 00:57:13531}
532
Egor Pasko6da5a07c2024-03-11 19:56:29533void MessagePumpAndroid::Run(Delegate* delegate) {
Peter Boström54119652024-11-14 00:16:38534 NOTREACHED() << "Unexpected call to Run()";
[email protected]61c86c62011-08-02 16:11:16535}
536
Egor Pasko6da5a07c2024-03-11 19:56:29537void MessagePumpAndroid::Attach(Delegate* delegate) {
Michael Thiessendbeca242017-08-28 21:10:08538 DCHECK(!quit_);
Michael Thiessend7ae7352018-07-10 00:57:13539
540 // Since the Looper is controlled by the UI thread or JavaHandlerThread, we
541 // can't use Run() like we do on other platforms or we would prevent Java
542 // tasks from running. Instead we create and initialize a run loop here, then
543 // return control back to the Looper.
544
545 SetDelegate(delegate);
Michael Thiessen781ddeb2017-11-15 17:07:23546 run_loop_ = std::make_unique<RunLoop>();
[email protected]8e937c1e2012-06-28 22:57:30547 // Since the RunLoop was just created above, BeforeRun should be guaranteed to
548 // return true (it only returns false if the RunLoop has been Quit already).
Adam Riced47f4982024-09-03 16:18:23549 CHECK(run_loop_->BeforeRun());
[email protected]61c86c62011-08-02 16:11:16550}
551
Egor Pasko6da5a07c2024-03-11 19:56:29552void MessagePumpAndroid::Quit() {
Peter Kasting134ef9af2024-12-28 02:30:09553 if (quit_) {
Michael Thiessend7ae7352018-07-10 00:57:13554 return;
Peter Kasting134ef9af2024-12-28 02:30:09555 }
Michael Thiessend7ae7352018-07-10 00:57:13556
Michael Thiessendbeca242017-08-28 21:10:08557 quit_ = true;
Michael Thiessen781ddeb2017-11-15 17:07:23558
Michael Thiessend7ae7352018-07-10 00:57:13559 int64_t value;
560 // Clear any pending timer.
561 read(delayed_fd_, &value, sizeof(value));
562 // Clear the eventfd.
563 read(non_delayed_fd_, &value, sizeof(value));
[email protected]61c86c62011-08-02 16:11:16564
[email protected]8e937c1e2012-06-28 22:57:30565 if (run_loop_) {
566 run_loop_->AfterRun();
Michael Thiessen781ddeb2017-11-15 17:07:23567 run_loop_ = nullptr;
[email protected]61c86c62011-08-02 16:11:16568 }
Michael Thiessend7ae7352018-07-10 00:57:13569 if (on_quit_callback_) {
570 std::move(on_quit_callback_).Run();
571 }
[email protected]61c86c62011-08-02 16:11:16572}
573
Egor Pasko6da5a07c2024-03-11 19:56:29574void MessagePumpAndroid::ScheduleWork() {
Aaron Colwell48c4d5072020-11-13 16:45:03575 ScheduleWorkInternal(/*do_idle_work=*/false);
576}
577
Egor Pasko6da5a07c2024-03-11 19:56:29578void MessagePumpAndroid::ScheduleWorkInternal(bool do_idle_work) {
Aaron Colwell48c4d5072020-11-13 16:45:03579 // Write (add) |value| to the eventfd. This tells the Looper to wake up and
580 // call our callback, allowing us to run tasks. This also allows us to detect,
581 // when we clear the fd, whether additional work was scheduled after we
582 // finished performing work, but before we cleared the fd, as we'll read back
583 // >=2 instead of 1 in that case. See the eventfd man pages
Michael Thiessend7ae7352018-07-10 00:57:13584 // (http://man7.org/linux/man-pages/man2/eventfd.2.html) for details on how
585 // the read and write APIs for this file descriptor work, specifically without
586 // EFD_SEMAPHORE.
Aaron Colwell48c4d5072020-11-13 16:45:03587 // Note: Calls with |do_idle_work| set to true may race with potential calls
François Doray23159042023-03-01 14:14:09588 // where the parameter is false. This is fine as write() is adding |value|,
589 // not overwriting the existing value, and as such racing calls would merely
590 // have their values added together. Since idle work is only executed when the
591 // value read equals kTryNativeWorkBeforeIdleBit, a race would prevent idle
592 // work from being run and trigger another call to this method with
593 // |do_idle_work| set to true.
Gabriel Charette300f16792022-07-06 20:03:30594 uint64_t value = do_idle_work ? kTryNativeWorkBeforeIdleBit : 1;
Peter Kasting2f61c8b2022-07-19 23:43:46595 long ret = write(non_delayed_fd_, &value, sizeof(value));
Michael Thiessen7c36083d2018-08-10 20:24:54596 DPCHECK(ret >= 0);
[email protected]61c86c62011-08-02 16:11:16597}
598
Egor Paskoac4913e2024-10-22 12:03:04599void MessagePumpAndroid::OnReturnFromLooper() {
600 if (!is_type_ui_) {
601 return;
602 }
603 auto& checker = InputHintChecker::GetInstance();
604 if (checker.is_after_input_yield()) {
Egor Pasko9396dfd2025-03-10 16:30:18605 InputHintChecker::GetInstance().RecordInputHintResult(
606 InputHintResult::kBackToNative);
Egor Paskoac4913e2024-10-22 12:03:04607 }
608 checker.set_is_after_input_yield(false);
609}
610
Egor Pasko6da5a07c2024-03-11 19:56:29611void MessagePumpAndroid::ScheduleDelayedWork(
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33612 const Delegate::NextWorkInfo& next_work_info) {
Peter Kasting134ef9af2024-12-28 02:30:09613 if (ShouldQuit()) {
Michael Thiessendbeca242017-08-28 21:10:08614 return;
Peter Kasting134ef9af2024-12-28 02:30:09615 }
Michael Thiessend7ae7352018-07-10 00:57:13616
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33617 if (delayed_scheduled_time_ &&
618 *delayed_scheduled_time_ == next_work_info.delayed_run_time) {
Michael Thiessen781ddeb2017-11-15 17:07:23619 return;
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33620 }
Michael Thiessend7ae7352018-07-10 00:57:13621
Etienne Pierre-dorayf2f8e13b2022-03-10 12:42:33622 DCHECK(!next_work_info.is_immediate());
623 delayed_scheduled_time_ = next_work_info.delayed_run_time;
François Doray23159042023-03-01 14:14:09624 int64_t nanos =
625 next_work_info.delayed_run_time.since_origin().InNanoseconds();
626 struct itimerspec ts;
627 ts.it_interval.tv_sec = 0; // Don't repeat.
628 ts.it_interval.tv_nsec = 0;
629 ts.it_value.tv_sec =
630 static_cast<time_t>(nanos / TimeTicks::kNanosecondsPerSecond);
631 ts.it_value.tv_nsec = nanos % TimeTicks::kNanosecondsPerSecond;
632
Peter Kasting2f61c8b2022-07-19 23:43:46633 long ret = timerfd_settime(delayed_fd_, TFD_TIMER_ABSTIME, &ts, nullptr);
Michael Thiessen7c36083d2018-08-10 20:24:54634 DPCHECK(ret >= 0);
Michael Thiessend7ae7352018-07-10 00:57:13635}
636
Ken Rockota2c5d792024-11-28 20:05:22637IOWatcher* MessagePumpAndroid::GetIOWatcher() {
638 if (!io_watcher_) {
639 io_watcher_ = std::make_unique<IOWatcherImpl>(looper_);
640 }
641 return io_watcher_.get();
642}
643
Egor Pasko6da5a07c2024-03-11 19:56:29644void MessagePumpAndroid::QuitWhenIdle(base::OnceClosure callback) {
Michael Thiessend7ae7352018-07-10 00:57:13645 DCHECK(!on_quit_callback_);
646 DCHECK(run_loop_);
647 on_quit_callback_ = std::move(callback);
648 run_loop_->QuitWhenIdle();
649 // Pump the loop in case we're already idle.
650 ScheduleWork();
651}
652
Egor Pasko6da5a07c2024-03-11 19:56:29653MessagePump::Delegate* MessagePumpAndroid::SetDelegate(Delegate* delegate) {
Aaron Colwell48c4d5072020-11-13 16:45:03654 return std::exchange(delegate_, delegate);
655}
656
Egor Pasko6da5a07c2024-03-11 19:56:29657bool MessagePumpAndroid::SetQuit(bool quit) {
Aaron Colwell48c4d5072020-11-13 16:45:03658 return std::exchange(quit_, quit);
659}
660
[email protected]61c86c62011-08-02 16:11:16661} // namespace base