1 // Copyright 2012 The Chromium Authors
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 "base/message_loop/message_pump_android.h"
6
7 #include <android/looper.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <jni.h>
11 #include <sys/eventfd.h>
12 #include <sys/timerfd.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15
16 #include <atomic>
17 #include <map>
18 #include <memory>
19 #include <utility>
20
21 #include "base/android/input_hint_checker.h"
22 #include "base/android/jni_android.h"
23 #include "base/android/scoped_java_ref.h"
24 #include "base/check.h"
25 #include "base/check_op.h"
26 #include "base/message_loop/io_watcher.h"
27 #include "base/notreached.h"
28 #include "base/numerics/safe_conversions.h"
29 #include "base/run_loop.h"
30 #include "base/task/task_features.h"
31 #include "base/time/time.h"
32 #include "build/build_config.h"
33
34 using base::android::InputHintChecker;
35 using base::android::InputHintResult;
36
37 namespace base {
38
39 namespace {
40
41 // 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.
43 //
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.
49 #if defined(ARCH_CPU_X86)
50 #define NO_INSTRUMENT_STACK_ALIGN \
51 __attribute__((force_align_arg_pointer, no_instrument_function))
52 #else
53 #define NO_INSTRUMENT_STACK_ALIGN __attribute__((no_instrument_function))
54 #endif
55
NonDelayedLooperCallback(int fd,int events,void * data)56 NO_INSTRUMENT_STACK_ALIGN int NonDelayedLooperCallback(int fd,
57 int events,
58 void* data) {
59 if (events & ALOOPER_EVENT_HANGUP)
60 return 0;
61
62 DCHECK(events & ALOOPER_EVENT_INPUT);
63 MessagePumpAndroid* pump = reinterpret_cast<MessagePumpAndroid*>(data);
64 pump->OnNonDelayedLooperCallback();
65 return 1; // continue listening for events
66 }
67
DelayedLooperCallback(int fd,int events,void * data)68 NO_INSTRUMENT_STACK_ALIGN int DelayedLooperCallback(int fd,
69 int events,
70 void* data) {
71 if (events & ALOOPER_EVENT_HANGUP)
72 return 0;
73
74 DCHECK(events & ALOOPER_EVENT_INPUT);
75 MessagePumpAndroid* pump = reinterpret_cast<MessagePumpAndroid*>(data);
76 pump->OnDelayedLooperCallback();
77 return 1; // continue listening for events
78 }
79
80 // A bit added to the |non_delayed_fd_| to keep it signaled when we yield to
81 // native work below.
82 constexpr uint64_t kTryNativeWorkBeforeIdleBit = uint64_t(1) << 32;
83
84 std::atomic_bool g_fast_to_sleep = false;
85
86 // Implements IOWatcher to allow any MessagePumpAndroid thread to watch
87 // arbitrary file descriptors for I/O events.
88 class IOWatcherImpl : public IOWatcher {
89 public:
IOWatcherImpl(ALooper * looper)90 explicit IOWatcherImpl(ALooper* looper) : looper_(looper) {}
91
~IOWatcherImpl()92 ~IOWatcherImpl() override {
93 for (auto& [fd, watches] : watched_fds_) {
94 ALooper_removeFd(looper_, fd);
95 if (auto read_watch = std::exchange(watches.read_watch, nullptr)) {
96 read_watch->Detach();
97 }
98 if (auto write_watch = std::exchange(watches.write_watch, nullptr)) {
99 write_watch->Detach();
100 }
101 }
102 }
103
104 // IOWatcher:
WatchFileDescriptorImpl(int fd,FdWatchDuration duration,FdWatchMode mode,IOWatcher::FdWatcher & watcher,const Location & location)105 std::unique_ptr<IOWatcher::FdWatch> WatchFileDescriptorImpl(
106 int fd,
107 FdWatchDuration duration,
108 FdWatchMode mode,
109 IOWatcher::FdWatcher& watcher,
110 const Location& location) override {
111 auto& watches = watched_fds_[fd];
112 auto watch = std::make_unique<FdWatchImpl>(*this, fd, duration, watcher);
113 if (mode == FdWatchMode::kRead || mode == FdWatchMode::kReadWrite) {
114 CHECK(!watches.read_watch) << "Only one watch per FD per condition.";
115 watches.read_watch = watch.get();
116 }
117 if (mode == FdWatchMode::kWrite || mode == FdWatchMode::kReadWrite) {
118 CHECK(!watches.write_watch) << "Only one watch per FD per condition.";
119 watches.write_watch = watch.get();
120 }
121
122 const int events = (watches.read_watch ? ALOOPER_EVENT_INPUT : 0) |
123 (watches.write_watch ? ALOOPER_EVENT_OUTPUT : 0);
124 ALooper_addFd(looper_, fd, 0, events, &OnFdIoEvent, this);
125 return watch;
126 }
127
128 private:
129 // Scopes the maximum lifetime of an FD watch started by WatchFileDescriptor.
130 class FdWatchImpl : public FdWatch {
131 public:
FdWatchImpl(IOWatcherImpl & io_watcher,int fd,FdWatchDuration duration,FdWatcher & fd_watcher)132 FdWatchImpl(IOWatcherImpl& io_watcher,
133 int fd,
134 FdWatchDuration duration,
135 FdWatcher& fd_watcher)
136 : fd_(fd),
137 duration_(duration),
138 fd_watcher_(fd_watcher),
139 io_watcher_(&io_watcher) {}
140
~FdWatchImpl()141 ~FdWatchImpl() override {
142 Stop();
143 if (destruction_flag_) {
144 *destruction_flag_ = true;
145 }
146 }
147
set_destruction_flag(bool * flag)148 void set_destruction_flag(bool* flag) { destruction_flag_ = flag; }
fd() const149 int fd() const { return fd_; }
fd_watcher() const150 FdWatcher& fd_watcher() const { return *fd_watcher_; }
151
is_persistent() const152 bool is_persistent() const {
153 return duration_ == FdWatchDuration::kPersistent;
154 }
155
Detach()156 void Detach() { io_watcher_ = nullptr; }
157
Stop()158 void Stop() {
159 if (io_watcher_) {
160 std::exchange(io_watcher_, nullptr)->StopWatching(*this);
161 }
162 }
163
164 private:
165 const int fd_;
166 const FdWatchDuration duration_;
167 raw_ref<FdWatcher> fd_watcher_;
168 raw_ptr<IOWatcherImpl> io_watcher_;
169
170 // If non-null during destruction, the pointee is set to true. Used to
171 // detect reentrant destruction during dispatch.
172 raw_ptr<bool> destruction_flag_ = nullptr;
173 };
174
175 enum class EventResult {
176 kStopWatching,
177 kKeepWatching,
178 };
179
OnFdIoEvent(int fd,int events,void * data)180 static NO_INSTRUMENT_STACK_ALIGN int OnFdIoEvent(int fd,
181 int events,
182 void* data) {
183 switch (static_cast<IOWatcherImpl*>(data)->HandleEvent(fd, events)) {
184 case EventResult::kStopWatching:
185 return 0;
186 case EventResult::kKeepWatching:
187 return 1;
188 }
189 }
190
HandleEvent(int fd,int events)191 EventResult HandleEvent(int fd, int events) {
192 // NOTE: It is possible for Looper to dispatch one last event for `fd`
193 // *after* we have removed the FD from the Looper - for example if multiple
194 // FDs wake the thread at the same time, and a handler for another FD runs
195 // first and removes the watch for `fd`; this callback will have already
196 // been queued for `fd` and will still run. As such, we must gracefully
197 // tolerate receiving a callback for an FD that is no longer watched.
198 auto it = watched_fds_.find(fd);
199 if (it == watched_fds_.end()) {
200 return EventResult::kStopWatching;
201 }
202
203 auto& watches = it->second;
204 const bool is_readable =
205 events & (ALOOPER_EVENT_INPUT | ALOOPER_EVENT_HANGUP);
206 const bool is_writable =
207 events & (ALOOPER_EVENT_OUTPUT | ALOOPER_EVENT_HANGUP);
208 auto* read_watch = watches.read_watch.get();
209 auto* write_watch = watches.write_watch.get();
210
211 // Any event dispatch can stop any number of watches, so we're careful to
212 // set up destruction observation before dispatching anything.
213 bool read_watch_destroyed = false;
214 bool write_watch_destroyed = false;
215 bool fd_removed = false;
216 if (read_watch) {
217 read_watch->set_destruction_flag(&read_watch_destroyed);
218 }
219 if (write_watch && read_watch != write_watch) {
220 write_watch->set_destruction_flag(&write_watch_destroyed);
221 }
222 watches.removed_flag = &fd_removed;
223
224 bool did_observe_one_shot_read = false;
225 if (read_watch && is_readable) {
226 DCHECK_EQ(read_watch->fd(), fd);
227 did_observe_one_shot_read = !read_watch->is_persistent();
228 read_watch->fd_watcher().OnFdReadable(fd);
229 if (!read_watch_destroyed && did_observe_one_shot_read) {
230 read_watch->Stop();
231 }
232 }
233
234 // If the read and write watches are the same object, it may have been
235 // destroyed; or it may have been a one-shot watch already consumed by a
236 // read above. In either case we inhibit write dispatch.
237 if (read_watch == write_watch &&
238 (read_watch_destroyed || did_observe_one_shot_read)) {
239 write_watch = nullptr;
240 }
241
242 if (write_watch && is_writable && !write_watch_destroyed) {
243 DCHECK_EQ(write_watch->fd(), fd);
244 const bool is_persistent = write_watch->is_persistent();
245 write_watch->fd_watcher().OnFdWritable(fd);
246 if (!write_watch_destroyed && !is_persistent) {
247 write_watch->Stop();
248 }
249 }
250
251 if (read_watch && !read_watch_destroyed) {
252 read_watch->set_destruction_flag(nullptr);
253 }
254 if (write_watch && !write_watch_destroyed) {
255 write_watch->set_destruction_flag(nullptr);
256 }
257
258 if (fd_removed) {
259 return EventResult::kStopWatching;
260 }
261
262 watches.removed_flag = nullptr;
263 return EventResult::kKeepWatching;
264 }
265
StopWatching(FdWatchImpl & watch)266 void StopWatching(FdWatchImpl& watch) {
267 const int fd = watch.fd();
268 auto it = watched_fds_.find(fd);
269 if (it == watched_fds_.end()) {
270 return;
271 }
272
273 WatchPair& watches = it->second;
274 if (watches.read_watch == &watch) {
275 watches.read_watch = nullptr;
276 }
277 if (watches.write_watch == &watch) {
278 watches.write_watch = nullptr;
279 }
280
281 const int remaining_events =
282 (watches.read_watch ? ALOOPER_EVENT_INPUT : 0) |
283 (watches.write_watch ? ALOOPER_EVENT_OUTPUT : 0);
284 if (remaining_events) {
285 ALooper_addFd(looper_, fd, 0, remaining_events, &OnFdIoEvent, this);
286 return;
287 }
288
289 ALooper_removeFd(looper_, fd);
290 if (watches.removed_flag) {
291 *watches.removed_flag = true;
292 }
293 watched_fds_.erase(it);
294 }
295
296 private:
297 const raw_ptr<ALooper> looper_;
298
299 // The set of active FdWatches. Note that each FD may have up to two active
300 // watches only - one for read and one for write. No two FdWatches can watch
301 // the same FD for the same signal. `read_watch` and `write_watch` may point
302 // to the same object.
303 struct WatchPair {
304 raw_ptr<FdWatchImpl> read_watch = nullptr;
305 raw_ptr<FdWatchImpl> write_watch = nullptr;
306
307 // If non-null when this WatchPair is removed, the pointee is set to true.
308 // Used to track reentrant map mutations during dispatch.
309 raw_ptr<bool> removed_flag = nullptr;
310 };
311 std::map<int, WatchPair> watched_fds_;
312 };
313
314 } // namespace
315
MessagePumpAndroid()316 MessagePumpAndroid::MessagePumpAndroid()
317 : env_(base::android::AttachCurrentThread()) {
318 // The Android native ALooper uses epoll to poll our file descriptors and wake
319 // us up. We use a simple level-triggered eventfd to signal that non-delayed
320 // work is available, and a timerfd to signal when delayed work is ready to
321 // be run.
322 non_delayed_fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
323 CHECK_NE(non_delayed_fd_, -1);
324 DCHECK_EQ(TimeTicks::GetClock(), TimeTicks::Clock::LINUX_CLOCK_MONOTONIC);
325
326 delayed_fd_ = checked_cast<int>(
327 timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC));
328 CHECK_NE(delayed_fd_, -1);
329
330 looper_ = ALooper_prepare(0);
331 DCHECK(looper_);
332 // Add a reference to the looper so it isn't deleted on us.
333 ALooper_acquire(looper_);
334 ALooper_addFd(looper_, non_delayed_fd_, 0, ALOOPER_EVENT_INPUT,
335 &NonDelayedLooperCallback, reinterpret_cast<void*>(this));
336 ALooper_addFd(looper_, delayed_fd_, 0, ALOOPER_EVENT_INPUT,
337 &DelayedLooperCallback, reinterpret_cast<void*>(this));
338 }
339
~MessagePumpAndroid()340 MessagePumpAndroid::~MessagePumpAndroid() {
341 DCHECK_EQ(ALooper_forThread(), looper_);
342 io_watcher_.reset();
343 ALooper_removeFd(looper_, non_delayed_fd_);
344 ALooper_removeFd(looper_, delayed_fd_);
345 ALooper_release(looper_);
346 looper_ = nullptr;
347
348 close(non_delayed_fd_);
349 close(delayed_fd_);
350 }
351
InitializeFeatures()352 void MessagePumpAndroid::InitializeFeatures() {
353 g_fast_to_sleep = base::FeatureList::IsEnabled(kPumpFastToSleepAndroid);
354 }
355
OnDelayedLooperCallback()356 void MessagePumpAndroid::OnDelayedLooperCallback() {
357 OnReturnFromLooper();
358 // There may be non-Chromium callbacks on the same ALooper which may have left
359 // a pending exception set, and ALooper does not check for this between
360 // callbacks. Check here, and if there's already an exception, just skip this
361 // iteration without clearing the fd. If the exception ends up being non-fatal
362 // then we'll just get called again on the next polling iteration.
363 if (base::android::HasException(env_))
364 return;
365
366 // ALooper_pollOnce may call this after Quit() if OnNonDelayedLooperCallback()
367 // resulted in Quit() in the same round.
368 if (ShouldQuit())
369 return;
370
371 // Clear the fd.
372 uint64_t value;
373 long ret = read(delayed_fd_, &value, sizeof(value));
374
375 // TODO(mthiesse): Figure out how it's possible to hit EAGAIN here.
376 // According to http://man7.org/linux/man-pages/man2/timerfd_create.2.html
377 // EAGAIN only happens if no timer has expired. Also according to the man page
378 // poll only returns readable when a timer has expired. So this function will
379 // only be called when a timer has expired, but reading reveals no timer has
380 // expired...
381 // Quit() and ScheduleDelayedWork() are the only other functions that touch
382 // the timerfd, and they both run on the same thread as this callback, so
383 // there are no obvious timing or multi-threading related issues.
384 DPCHECK(ret >= 0 || errno == EAGAIN);
385 DoDelayedLooperWork();
386 }
387
DoDelayedLooperWork()388 void MessagePumpAndroid::DoDelayedLooperWork() {
389 delayed_scheduled_time_.reset();
390
391 Delegate::NextWorkInfo next_work_info = delegate_->DoWork();
392
393 if (ShouldQuit())
394 return;
395
396 if (next_work_info.is_immediate()) {
397 ScheduleWork();
398 return;
399 }
400
401 delegate_->DoIdleWork();
402 if (!next_work_info.delayed_run_time.is_max())
403 ScheduleDelayedWork(next_work_info);
404 }
405
OnNonDelayedLooperCallback()406 void MessagePumpAndroid::OnNonDelayedLooperCallback() {
407 OnReturnFromLooper();
408 // There may be non-Chromium callbacks on the same ALooper which may have left
409 // a pending exception set, and ALooper does not check for this between
410 // callbacks. Check here, and if there's already an exception, just skip this
411 // iteration without clearing the fd. If the exception ends up being non-fatal
412 // then we'll just get called again on the next polling iteration.
413 if (base::android::HasException(env_))
414 return;
415
416 // ALooper_pollOnce may call this after Quit() if OnDelayedLooperCallback()
417 // resulted in Quit() in the same round.
418 if (ShouldQuit())
419 return;
420
421 // We're about to process all the work requested by ScheduleWork().
422 // MessagePump users are expected to do their best not to invoke
423 // ScheduleWork() again before DoWork() returns a non-immediate
424 // NextWorkInfo below. Hence, capturing the file descriptor's value now and
425 // resetting its contents to 0 should be okay. The value currently stored
426 // should be greater than 0 since work having been scheduled is the reason
427 // we're here. See http://man7.org/linux/man-pages/man2/eventfd.2.html
428 uint64_t value = 0;
429 long ret = read(non_delayed_fd_, &value, sizeof(value));
430 DPCHECK(ret >= 0);
431 DCHECK_GT(value, 0U);
432 bool do_idle_work = value == kTryNativeWorkBeforeIdleBit;
433 DoNonDelayedLooperWork(do_idle_work);
434 }
435
DoNonDelayedLooperWork(bool do_idle_work)436 void MessagePumpAndroid::DoNonDelayedLooperWork(bool do_idle_work) {
437 // Note: We can't skip DoWork() even if |do_idle_work| is true here (i.e. no
438 // additional ScheduleWork() since yielding to native) as delayed tasks might
439 // have come in and we need to re-sample |next_work_info|.
440
441 // Runs all application tasks scheduled to run.
442 Delegate::NextWorkInfo next_work_info;
443 do {
444 if (ShouldQuit())
445 return;
446
447 next_work_info = delegate_->DoWork();
448
449 // If we are prioritizing native, and the next work would normally run
450 // immediately, skip the next work and let the native work items have a
451 // chance to run. This is useful when user input is waiting for native to
452 // have a chance to run.
453 if (next_work_info.is_immediate() && next_work_info.yield_to_native) {
454 ScheduleWork();
455 return;
456 }
457
458 // 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.
463 if (is_type_ui_ && next_work_info.is_immediate() &&
464 InputHintChecker::HasInput()) {
465 InputHintChecker::GetInstance().set_is_after_input_yield(true);
466 ScheduleWork();
467 return;
468 }
469 } 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).
474 if (ShouldQuit())
475 return;
476
477 // Under the fast to sleep feature, `do_idle_work` is ignored, and the pump
478 // will always "sleep" after finishing all its work items.
479 if (!g_fast_to_sleep) {
480 // Before declaring this loop idle, yield to native work items and arrange
481 // to be called again (unless we're already in that second call).
482 if (!do_idle_work) {
483 ScheduleWorkInternal(/*do_idle_work=*/true);
484 return;
485 }
486
487 // We yielded to native work items already and they didn't generate a
488 // ScheduleWork() request so we can declare idleness. It's possible for a
489 // ScheduleWork() request to come in racily while this method unwinds, this
490 // is fine and will merely result in it being re-invoked shortly after it
491 // returns.
492 // TODO(scheduler-dev): this doesn't account for tasks that don't ever call
493 // SchedulerWork() but still keep the system non-idle (e.g., the Java
494 // Handler API). It would be better to add an API to query the presence of
495 // native tasks instead of relying on yielding once +
496 // kTryNativeWorkBeforeIdleBit.
497 DCHECK(do_idle_work);
498 }
499
500 if (ShouldQuit()) {
501 return;
502 }
503
504 // Do the idle work.
505 //
506 // At this point, the Java Looper might not be idle. It is possible to skip
507 // idle work if !MessageQueue.isIdle(), but this check is not very accurate
508 // because the MessageQueue does not know about the additional tasks
509 // potentially waiting in the Looper.
510 //
511 // Note that this won't cause us to fail to run java tasks using QuitWhenIdle,
512 // as the JavaHandlerThread will finish running all currently scheduled tasks
513 // before it quits. Also note that we can't just add an idle callback to the
514 // java looper, as that will fire even if application tasks are still queued
515 // up.
516 delegate_->DoIdleWork();
517 if (!next_work_info.delayed_run_time.is_max()) {
518 ScheduleDelayedWork(next_work_info);
519 }
520 }
521
Run(Delegate * delegate)522 void MessagePumpAndroid::Run(Delegate* delegate) {
523 NOTREACHED() << "Unexpected call to Run()";
524 }
525
Attach(Delegate * delegate)526 void MessagePumpAndroid::Attach(Delegate* delegate) {
527 DCHECK(!quit_);
528
529 // Since the Looper is controlled by the UI thread or JavaHandlerThread, we
530 // can't use Run() like we do on other platforms or we would prevent Java
531 // tasks from running. Instead we create and initialize a run loop here, then
532 // return control back to the Looper.
533
534 SetDelegate(delegate);
535 run_loop_ = std::make_unique<RunLoop>();
536 // Since the RunLoop was just created above, BeforeRun should be guaranteed to
537 // return true (it only returns false if the RunLoop has been Quit already).
538 CHECK(run_loop_->BeforeRun());
539 }
540
Quit()541 void MessagePumpAndroid::Quit() {
542 if (quit_)
543 return;
544
545 quit_ = true;
546
547 int64_t value;
548 // Clear any pending timer.
549 read(delayed_fd_, &value, sizeof(value));
550 // Clear the eventfd.
551 read(non_delayed_fd_, &value, sizeof(value));
552
553 if (run_loop_) {
554 run_loop_->AfterRun();
555 run_loop_ = nullptr;
556 }
557 if (on_quit_callback_) {
558 std::move(on_quit_callback_).Run();
559 }
560 }
561
ScheduleWork()562 void MessagePumpAndroid::ScheduleWork() {
563 ScheduleWorkInternal(/*do_idle_work=*/false);
564 }
565
ScheduleWorkInternal(bool do_idle_work)566 void MessagePumpAndroid::ScheduleWorkInternal(bool do_idle_work) {
567 // Write (add) |value| to the eventfd. This tells the Looper to wake up and
568 // call our callback, allowing us to run tasks. This also allows us to detect,
569 // when we clear the fd, whether additional work was scheduled after we
570 // finished performing work, but before we cleared the fd, as we'll read back
571 // >=2 instead of 1 in that case. See the eventfd man pages
572 // (http://man7.org/linux/man-pages/man2/eventfd.2.html) for details on how
573 // the read and write APIs for this file descriptor work, specifically without
574 // EFD_SEMAPHORE.
575 // Note: Calls with |do_idle_work| set to true may race with potential calls
576 // where the parameter is false. This is fine as write() is adding |value|,
577 // not overwriting the existing value, and as such racing calls would merely
578 // have their values added together. Since idle work is only executed when the
579 // value read equals kTryNativeWorkBeforeIdleBit, a race would prevent idle
580 // work from being run and trigger another call to this method with
581 // |do_idle_work| set to true.
582 uint64_t value = do_idle_work ? kTryNativeWorkBeforeIdleBit : 1;
583 long ret = write(non_delayed_fd_, &value, sizeof(value));
584 DPCHECK(ret >= 0);
585 }
586
OnReturnFromLooper()587 void MessagePumpAndroid::OnReturnFromLooper() {
588 if (!is_type_ui_) {
589 return;
590 }
591 auto& checker = InputHintChecker::GetInstance();
592 if (checker.is_after_input_yield()) {
593 InputHintChecker::RecordInputHintResult(InputHintResult::kBackToNative);
594 }
595 checker.set_is_after_input_yield(false);
596 }
597
ScheduleDelayedWork(const Delegate::NextWorkInfo & next_work_info)598 void MessagePumpAndroid::ScheduleDelayedWork(
599 const Delegate::NextWorkInfo& next_work_info) {
600 if (ShouldQuit())
601 return;
602
603 if (delayed_scheduled_time_ &&
604 *delayed_scheduled_time_ == next_work_info.delayed_run_time) {
605 return;
606 }
607
608 DCHECK(!next_work_info.is_immediate());
609 delayed_scheduled_time_ = next_work_info.delayed_run_time;
610 int64_t nanos =
611 next_work_info.delayed_run_time.since_origin().InNanoseconds();
612 struct itimerspec ts;
613 ts.it_interval.tv_sec = 0; // Don't repeat.
614 ts.it_interval.tv_nsec = 0;
615 ts.it_value.tv_sec =
616 static_cast<time_t>(nanos / TimeTicks::kNanosecondsPerSecond);
617 ts.it_value.tv_nsec = nanos % TimeTicks::kNanosecondsPerSecond;
618
619 long ret = timerfd_settime(delayed_fd_, TFD_TIMER_ABSTIME, &ts, nullptr);
620 DPCHECK(ret >= 0);
621 }
622
GetIOWatcher()623 IOWatcher* MessagePumpAndroid::GetIOWatcher() {
624 if (!io_watcher_) {
625 io_watcher_ = std::make_unique<IOWatcherImpl>(looper_);
626 }
627 return io_watcher_.get();
628 }
629
QuitWhenIdle(base::OnceClosure callback)630 void MessagePumpAndroid::QuitWhenIdle(base::OnceClosure callback) {
631 DCHECK(!on_quit_callback_);
632 DCHECK(run_loop_);
633 on_quit_callback_ = std::move(callback);
634 run_loop_->QuitWhenIdle();
635 // Pump the loop in case we're already idle.
636 ScheduleWork();
637 }
638
SetDelegate(Delegate * delegate)639 MessagePump::Delegate* MessagePumpAndroid::SetDelegate(Delegate* delegate) {
640 return std::exchange(delegate_, delegate);
641 }
642
SetQuit(bool quit)643 bool MessagePumpAndroid::SetQuit(bool quit) {
644 return std::exchange(quit_, quit);
645 }
646
647 } // namespace base
648