xref: /aosp_15_r20/external/cronet/base/message_loop/message_pump_android.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 #include <utility>
16 
17 #include "base/android/input_hint_checker.h"
18 #include "base/android/jni_android.h"
19 #include "base/android/scoped_java_ref.h"
20 #include "base/check_op.h"
21 #include "base/notreached.h"
22 #include "base/numerics/safe_conversions.h"
23 #include "base/run_loop.h"
24 #include "base/time/time.h"
25 #include "build/build_config.h"
26 
27 namespace base {
28 
29 namespace {
30 
31 // https://crbug.com/873588. The stack may not be aligned when the ALooper calls
32 // into our code due to the inconsistent ABI on older Android OS versions.
33 //
34 // https://crbug.com/330761384#comment3. Calls from libutils.so into
35 // NonDelayedLooperCallback() and DelayedLooperCallback() confuse aarch64 builds
36 // with orderfile instrumentation causing incorrect value in
37 // __builtin_return_address(0). Disable instrumentation for them. TODO(pasko):
38 // Add these symbols to the orderfile manually or fix the builtin.
39 #if defined(ARCH_CPU_X86)
40 #define NO_INSTRUMENT_STACK_ALIGN \
41   __attribute__((force_align_arg_pointer, no_instrument_function))
42 #else
43 #define NO_INSTRUMENT_STACK_ALIGN __attribute__((no_instrument_function))
44 #endif
45 
NonDelayedLooperCallback(int fd,int events,void * data)46 NO_INSTRUMENT_STACK_ALIGN int NonDelayedLooperCallback(int fd,
47                                                        int events,
48                                                        void* data) {
49   if (events & ALOOPER_EVENT_HANGUP)
50     return 0;
51 
52   DCHECK(events & ALOOPER_EVENT_INPUT);
53   MessagePumpAndroid* pump = reinterpret_cast<MessagePumpAndroid*>(data);
54   pump->OnNonDelayedLooperCallback();
55   return 1;  // continue listening for events
56 }
57 
DelayedLooperCallback(int fd,int events,void * data)58 NO_INSTRUMENT_STACK_ALIGN int DelayedLooperCallback(int fd,
59                                                     int events,
60                                                     void* data) {
61   if (events & ALOOPER_EVENT_HANGUP)
62     return 0;
63 
64   DCHECK(events & ALOOPER_EVENT_INPUT);
65   MessagePumpAndroid* pump = reinterpret_cast<MessagePumpAndroid*>(data);
66   pump->OnDelayedLooperCallback();
67   return 1;  // continue listening for events
68 }
69 
70 // A bit added to the |non_delayed_fd_| to keep it signaled when we yield to
71 // native work below.
72 constexpr uint64_t kTryNativeWorkBeforeIdleBit = uint64_t(1) << 32;
73 }  // namespace
74 
MessagePumpAndroid()75 MessagePumpAndroid::MessagePumpAndroid()
76     : env_(base::android::AttachCurrentThread()) {
77   // The Android native ALooper uses epoll to poll our file descriptors and wake
78   // us up. We use a simple level-triggered eventfd to signal that non-delayed
79   // work is available, and a timerfd to signal when delayed work is ready to
80   // be run.
81   non_delayed_fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
82   CHECK_NE(non_delayed_fd_, -1);
83   DCHECK_EQ(TimeTicks::GetClock(), TimeTicks::Clock::LINUX_CLOCK_MONOTONIC);
84 
85   delayed_fd_ = checked_cast<int>(
86       timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC));
87   CHECK_NE(delayed_fd_, -1);
88 
89   looper_ = ALooper_prepare(0);
90   DCHECK(looper_);
91   // Add a reference to the looper so it isn't deleted on us.
92   ALooper_acquire(looper_);
93   ALooper_addFd(looper_, non_delayed_fd_, 0, ALOOPER_EVENT_INPUT,
94                 &NonDelayedLooperCallback, reinterpret_cast<void*>(this));
95   ALooper_addFd(looper_, delayed_fd_, 0, ALOOPER_EVENT_INPUT,
96                 &DelayedLooperCallback, reinterpret_cast<void*>(this));
97 }
98 
~MessagePumpAndroid()99 MessagePumpAndroid::~MessagePumpAndroid() {
100   DCHECK_EQ(ALooper_forThread(), looper_);
101   ALooper_removeFd(looper_, non_delayed_fd_);
102   ALooper_removeFd(looper_, delayed_fd_);
103   ALooper_release(looper_);
104   looper_ = nullptr;
105 
106   close(non_delayed_fd_);
107   close(delayed_fd_);
108 }
109 
OnDelayedLooperCallback()110 void MessagePumpAndroid::OnDelayedLooperCallback() {
111   // There may be non-Chromium callbacks on the same ALooper which may have left
112   // a pending exception set, and ALooper does not check for this between
113   // callbacks. Check here, and if there's already an exception, just skip this
114   // iteration without clearing the fd. If the exception ends up being non-fatal
115   // then we'll just get called again on the next polling iteration.
116   if (base::android::HasException(env_))
117     return;
118 
119   // ALooper_pollOnce may call this after Quit() if OnNonDelayedLooperCallback()
120   // resulted in Quit() in the same round.
121   if (ShouldQuit())
122     return;
123 
124   // Clear the fd.
125   uint64_t value;
126   long ret = read(delayed_fd_, &value, sizeof(value));
127 
128   // TODO(mthiesse): Figure out how it's possible to hit EAGAIN here.
129   // According to http://man7.org/linux/man-pages/man2/timerfd_create.2.html
130   // EAGAIN only happens if no timer has expired. Also according to the man page
131   // poll only returns readable when a timer has expired. So this function will
132   // only be called when a timer has expired, but reading reveals no timer has
133   // expired...
134   // Quit() and ScheduleDelayedWork() are the only other functions that touch
135   // the timerfd, and they both run on the same thread as this callback, so
136   // there are no obvious timing or multi-threading related issues.
137   DPCHECK(ret >= 0 || errno == EAGAIN);
138   DoDelayedLooperWork();
139 }
140 
DoDelayedLooperWork()141 void MessagePumpAndroid::DoDelayedLooperWork() {
142   delayed_scheduled_time_.reset();
143 
144   Delegate::NextWorkInfo next_work_info = delegate_->DoWork();
145 
146   if (ShouldQuit())
147     return;
148 
149   if (next_work_info.is_immediate()) {
150     ScheduleWork();
151     return;
152   }
153 
154   DoIdleWork();
155   if (!next_work_info.delayed_run_time.is_max())
156     ScheduleDelayedWork(next_work_info);
157 }
158 
OnNonDelayedLooperCallback()159 void MessagePumpAndroid::OnNonDelayedLooperCallback() {
160   // There may be non-Chromium callbacks on the same ALooper which may have left
161   // a pending exception set, and ALooper does not check for this between
162   // callbacks. Check here, and if there's already an exception, just skip this
163   // iteration without clearing the fd. If the exception ends up being non-fatal
164   // then we'll just get called again on the next polling iteration.
165   if (base::android::HasException(env_))
166     return;
167 
168   // ALooper_pollOnce may call this after Quit() if OnDelayedLooperCallback()
169   // resulted in Quit() in the same round.
170   if (ShouldQuit())
171     return;
172 
173   // We're about to process all the work requested by ScheduleWork().
174   // MessagePump users are expected to do their best not to invoke
175   // ScheduleWork() again before DoWork() returns a non-immediate
176   // NextWorkInfo below. Hence, capturing the file descriptor's value now and
177   // resetting its contents to 0 should be okay. The value currently stored
178   // should be greater than 0 since work having been scheduled is the reason
179   // we're here. See http://man7.org/linux/man-pages/man2/eventfd.2.html
180   uint64_t value = 0;
181   long ret = read(non_delayed_fd_, &value, sizeof(value));
182   DPCHECK(ret >= 0);
183   DCHECK_GT(value, 0U);
184   bool do_idle_work = value == kTryNativeWorkBeforeIdleBit;
185   DoNonDelayedLooperWork(do_idle_work);
186 }
187 
DoNonDelayedLooperWork(bool do_idle_work)188 void MessagePumpAndroid::DoNonDelayedLooperWork(bool do_idle_work) {
189   // Note: We can't skip DoWork() even if |do_idle_work| is true here (i.e. no
190   // additional ScheduleWork() since yielding to native) as delayed tasks might
191   // have come in and we need to re-sample |next_work_info|.
192 
193   // Runs all application tasks scheduled to run.
194   Delegate::NextWorkInfo next_work_info;
195   do {
196     if (ShouldQuit())
197       return;
198 
199     next_work_info = delegate_->DoWork();
200 
201     // If we are prioritizing native, and the next work would normally run
202     // immediately, skip the next work and let the native work items have a
203     // chance to run. This is useful when user input is waiting for native to
204     // have a chance to run.
205     if (next_work_info.is_immediate() && next_work_info.yield_to_native) {
206       ScheduleWork();
207       return;
208     }
209 
210     // As an optimization, yield to the Looper when input events are waiting to
211     // be handled. In some cases input events can remain undetected. Such "input
212     // hint false negatives" happen, for example, during initialization, in
213     // multi-window cases, or when a previous value is cached to throttle
214     // polling the input channel.
215     if (is_type_ui_ && android::InputHintChecker::HasInput()) {
216       ScheduleWork();
217       return;
218     }
219   } while (next_work_info.is_immediate());
220 
221   // Do not resignal |non_delayed_fd_| if we're quitting (this pump doesn't
222   // allow nesting so needing to resume in an outer loop is not an issue
223   // either).
224   if (ShouldQuit())
225     return;
226 
227   // Before declaring this loop idle, yield to native work items and arrange to
228   // be called again (unless we're already in that second call).
229   if (!do_idle_work) {
230     ScheduleWorkInternal(/*do_idle_work=*/true);
231     return;
232   }
233 
234   // We yielded to native work items already and they didn't generate a
235   // ScheduleWork() request so we can declare idleness. It's possible for a
236   // ScheduleWork() request to come in racily while this method unwinds, this is
237   // fine and will merely result in it being re-invoked shortly after it
238   // returns.
239   // TODO(scheduler-dev): this doesn't account for tasks that don't ever call
240   // SchedulerWork() but still keep the system non-idle (e.g., the Java Handler
241   // API). It would be better to add an API to query the presence of native
242   // tasks instead of relying on yielding once + kTryNativeWorkBeforeIdleBit.
243   DCHECK(do_idle_work);
244 
245   if (ShouldQuit())
246     return;
247 
248   // At this point, the java looper might not be idle - it's impossible to know
249   // pre-Android-M, so we may end up doing Idle work while java tasks are still
250   // queued up. Note that this won't cause us to fail to run java tasks using
251   // QuitWhenIdle, as the JavaHandlerThread will finish running all currently
252   // scheduled tasks before it quits. Also note that we can't just add an idle
253   // callback to the java looper, as that will fire even if application tasks
254   // are still queued up.
255   DoIdleWork();
256   if (!next_work_info.delayed_run_time.is_max()) {
257     ScheduleDelayedWork(next_work_info);
258   }
259 }
260 
DoIdleWork()261 void MessagePumpAndroid::DoIdleWork() {
262   if (delegate_->DoIdleWork()) {
263     // If DoIdleWork() resulted in any work, we're not idle yet. We need to pump
264     // the loop here because we may in fact be idle after doing idle work
265     // without any new tasks being queued.
266     ScheduleWork();
267   }
268 }
269 
Run(Delegate * delegate)270 void MessagePumpAndroid::Run(Delegate* delegate) {
271   CHECK(false) << "Unexpected call to Run()";
272 }
273 
Attach(Delegate * delegate)274 void MessagePumpAndroid::Attach(Delegate* delegate) {
275   DCHECK(!quit_);
276 
277   // Since the Looper is controlled by the UI thread or JavaHandlerThread, we
278   // can't use Run() like we do on other platforms or we would prevent Java
279   // tasks from running. Instead we create and initialize a run loop here, then
280   // return control back to the Looper.
281 
282   SetDelegate(delegate);
283   run_loop_ = std::make_unique<RunLoop>();
284   // Since the RunLoop was just created above, BeforeRun should be guaranteed to
285   // return true (it only returns false if the RunLoop has been Quit already).
286   if (!run_loop_->BeforeRun())
287     NOTREACHED();
288 }
289 
Quit()290 void MessagePumpAndroid::Quit() {
291   if (quit_)
292     return;
293 
294   quit_ = true;
295 
296   int64_t value;
297   // Clear any pending timer.
298   read(delayed_fd_, &value, sizeof(value));
299   // Clear the eventfd.
300   read(non_delayed_fd_, &value, sizeof(value));
301 
302   if (run_loop_) {
303     run_loop_->AfterRun();
304     run_loop_ = nullptr;
305   }
306   if (on_quit_callback_) {
307     std::move(on_quit_callback_).Run();
308   }
309 }
310 
ScheduleWork()311 void MessagePumpAndroid::ScheduleWork() {
312   ScheduleWorkInternal(/*do_idle_work=*/false);
313 }
314 
ScheduleWorkInternal(bool do_idle_work)315 void MessagePumpAndroid::ScheduleWorkInternal(bool do_idle_work) {
316   // Write (add) |value| to the eventfd. This tells the Looper to wake up and
317   // call our callback, allowing us to run tasks. This also allows us to detect,
318   // when we clear the fd, whether additional work was scheduled after we
319   // finished performing work, but before we cleared the fd, as we'll read back
320   // >=2 instead of 1 in that case. See the eventfd man pages
321   // (http://man7.org/linux/man-pages/man2/eventfd.2.html) for details on how
322   // the read and write APIs for this file descriptor work, specifically without
323   // EFD_SEMAPHORE.
324   // Note: Calls with |do_idle_work| set to true may race with potential calls
325   // where the parameter is false. This is fine as write() is adding |value|,
326   // not overwriting the existing value, and as such racing calls would merely
327   // have their values added together. Since idle work is only executed when the
328   // value read equals kTryNativeWorkBeforeIdleBit, a race would prevent idle
329   // work from being run and trigger another call to this method with
330   // |do_idle_work| set to true.
331   uint64_t value = do_idle_work ? kTryNativeWorkBeforeIdleBit : 1;
332   long ret = write(non_delayed_fd_, &value, sizeof(value));
333   DPCHECK(ret >= 0);
334 }
335 
ScheduleDelayedWork(const Delegate::NextWorkInfo & next_work_info)336 void MessagePumpAndroid::ScheduleDelayedWork(
337     const Delegate::NextWorkInfo& next_work_info) {
338   if (ShouldQuit())
339     return;
340 
341   if (delayed_scheduled_time_ &&
342       *delayed_scheduled_time_ == next_work_info.delayed_run_time) {
343     return;
344   }
345 
346   DCHECK(!next_work_info.is_immediate());
347   delayed_scheduled_time_ = next_work_info.delayed_run_time;
348   int64_t nanos =
349       next_work_info.delayed_run_time.since_origin().InNanoseconds();
350   struct itimerspec ts;
351   ts.it_interval.tv_sec = 0;  // Don't repeat.
352   ts.it_interval.tv_nsec = 0;
353   ts.it_value.tv_sec =
354       static_cast<time_t>(nanos / TimeTicks::kNanosecondsPerSecond);
355   ts.it_value.tv_nsec = nanos % TimeTicks::kNanosecondsPerSecond;
356 
357   long ret = timerfd_settime(delayed_fd_, TFD_TIMER_ABSTIME, &ts, nullptr);
358   DPCHECK(ret >= 0);
359 }
360 
QuitWhenIdle(base::OnceClosure callback)361 void MessagePumpAndroid::QuitWhenIdle(base::OnceClosure callback) {
362   DCHECK(!on_quit_callback_);
363   DCHECK(run_loop_);
364   on_quit_callback_ = std::move(callback);
365   run_loop_->QuitWhenIdle();
366   // Pump the loop in case we're already idle.
367   ScheduleWork();
368 }
369 
SetDelegate(Delegate * delegate)370 MessagePump::Delegate* MessagePumpAndroid::SetDelegate(Delegate* delegate) {
371   return std::exchange(delegate_, delegate);
372 }
373 
SetQuit(bool quit)374 bool MessagePumpAndroid::SetQuit(bool quit) {
375   return std::exchange(quit_, quit);
376 }
377 
378 }  // namespace base
379