blob: b387d68c6152ac65dc51961aec564ca884c75dd8 [file] [log] [blame]
Jeff Brown7901eb22010-09-13 23:17:30 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef UTILS_LOOPER_H
18#define UTILS_LOOPER_H
19
Jeff Brown7901eb22010-09-13 23:17:30 -070020#include <utils/RefBase.h>
Jeff Brown8d15c742010-10-05 15:35:37 -070021#include <utils/Timers.h>
Prabir Pradhan729057a2021-08-12 12:36:31 -070022#include <utils/Vector.h>
23#include <utils/threads.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070024
Jeff Brown8d15c742010-10-05 15:35:37 -070025#include <sys/epoll.h>
Jeff Brown8d15c742010-10-05 15:35:37 -070026
Josh Gao2d08ae52018-07-18 17:26:24 -070027#include <android-base/unique_fd.h>
28
Prabir Pradhan729057a2021-08-12 12:36:31 -070029#include <unordered_map>
Yurii Zubrytskyif8987c32020-04-22 15:37:21 -070030#include <utility>
31
Jeff Brown7901eb22010-09-13 23:17:30 -070032namespace android {
33
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080034/*
35 * NOTE: Since Looper is used to implement the NDK ALooper, the Looper
36 * enums and the signature of Looper_callbackFunc need to align with
37 * that implementation.
38 */
39
40/**
41 * For callback-based event loops, this is the prototype of the function
42 * that is called when a file descriptor event occurs.
43 * It is given the file descriptor it is associated with,
44 * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
45 * and the data pointer that was originally supplied.
46 *
47 * Implementations should return 1 to continue receiving callbacks, or 0
48 * to have this file descriptor and callback unregistered from the looper.
49 */
50typedef int (*Looper_callbackFunc)(int fd, int events, void* data);
51
Jeff Brown7901eb22010-09-13 23:17:30 -070052/**
Jeff Brown3e2e38b2011-03-02 14:41:58 -080053 * A message that can be posted to a Looper.
54 */
55struct Message {
56 Message() : what(0) { }
Colin Cross17b5b822016-09-15 18:15:37 -070057 Message(int w) : what(w) { }
Jeff Brown3e2e38b2011-03-02 14:41:58 -080058
59 /* The message type. (interpretation is left up to the handler) */
60 int what;
61};
62
63
64/**
65 * Interface for a Looper message handler.
66 *
67 * The Looper holds a strong reference to the message handler whenever it has
68 * a message to deliver to it. Make sure to call Looper::removeMessages
69 * to remove any pending messages destined for the handler so that the handler
70 * can be destroyed.
71 */
72class MessageHandler : public virtual RefBase {
73protected:
Colin Cross17b5b822016-09-15 18:15:37 -070074 virtual ~MessageHandler();
Jeff Brown3e2e38b2011-03-02 14:41:58 -080075
76public:
77 /**
78 * Handles a message.
79 */
80 virtual void handleMessage(const Message& message) = 0;
81};
82
83
84/**
85 * A simple proxy that holds a weak reference to a message handler.
86 */
87class WeakMessageHandler : public MessageHandler {
Jeff Browndd1b0372012-05-31 16:15:35 -070088protected:
89 virtual ~WeakMessageHandler();
90
Jeff Brown3e2e38b2011-03-02 14:41:58 -080091public:
92 WeakMessageHandler(const wp<MessageHandler>& handler);
93 virtual void handleMessage(const Message& message);
94
95private:
96 wp<MessageHandler> mHandler;
97};
98
99
100/**
Jeff Browndd1b0372012-05-31 16:15:35 -0700101 * A looper callback.
102 */
103class LooperCallback : public virtual RefBase {
104protected:
Colin Cross17b5b822016-09-15 18:15:37 -0700105 virtual ~LooperCallback();
Jeff Browndd1b0372012-05-31 16:15:35 -0700106
107public:
108 /**
109 * Handles a poll event for the given file descriptor.
110 * It is given the file descriptor it is associated with,
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800111 * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
Jeff Browndd1b0372012-05-31 16:15:35 -0700112 * and the data pointer that was originally supplied.
113 *
114 * Implementations should return 1 to continue receiving callbacks, or 0
115 * to have this file descriptor and callback unregistered from the looper.
116 */
117 virtual int handleEvent(int fd, int events, void* data) = 0;
118};
119
Jeff Browndd1b0372012-05-31 16:15:35 -0700120/**
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800121 * Wraps a Looper_callbackFunc function pointer.
Jeff Browndd1b0372012-05-31 16:15:35 -0700122 */
123class SimpleLooperCallback : public LooperCallback {
124protected:
125 virtual ~SimpleLooperCallback();
126
127public:
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800128 SimpleLooperCallback(Looper_callbackFunc callback);
Jeff Browndd1b0372012-05-31 16:15:35 -0700129 virtual int handleEvent(int fd, int events, void* data);
130
131private:
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800132 Looper_callbackFunc mCallback;
Jeff Browndd1b0372012-05-31 16:15:35 -0700133};
134
Jeff Browndd1b0372012-05-31 16:15:35 -0700135/**
Jeff Brown7901eb22010-09-13 23:17:30 -0700136 * A polling loop that supports monitoring file descriptor events, optionally
137 * using callbacks. The implementation uses epoll() internally.
138 *
139 * A looper can be associated with a thread although there is no requirement that it must be.
140 */
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800141class Looper : public RefBase {
Jeff Brown7901eb22010-09-13 23:17:30 -0700142protected:
143 virtual ~Looper();
144
145public:
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800146 enum {
147 /**
148 * Result from Looper_pollOnce() and Looper_pollAll():
149 * The poll was awoken using wake() before the timeout expired
150 * and no callbacks were executed and no other file descriptors were ready.
151 */
152 POLL_WAKE = -1,
153
154 /**
155 * Result from Looper_pollOnce() and Looper_pollAll():
156 * One or more callbacks were executed.
157 */
158 POLL_CALLBACK = -2,
159
160 /**
161 * Result from Looper_pollOnce() and Looper_pollAll():
162 * The timeout expired.
163 */
164 POLL_TIMEOUT = -3,
165
166 /**
167 * Result from Looper_pollOnce() and Looper_pollAll():
168 * An error occurred.
169 */
170 POLL_ERROR = -4,
171 };
172
173 /**
174 * Flags for file descriptor events that a looper can monitor.
175 *
176 * These flag bits can be combined to monitor multiple events at once.
177 */
178 enum {
179 /**
180 * The file descriptor is available for read operations.
181 */
182 EVENT_INPUT = 1 << 0,
183
184 /**
185 * The file descriptor is available for write operations.
186 */
187 EVENT_OUTPUT = 1 << 1,
188
189 /**
190 * The file descriptor has encountered an error condition.
191 *
192 * The looper always sends notifications about errors; it is not necessary
193 * to specify this event flag in the requested event set.
194 */
195 EVENT_ERROR = 1 << 2,
196
197 /**
198 * The file descriptor was hung up.
199 * For example, indicates that the remote end of a pipe or socket was closed.
200 *
201 * The looper always sends notifications about hangups; it is not necessary
202 * to specify this event flag in the requested event set.
203 */
204 EVENT_HANGUP = 1 << 3,
205
206 /**
207 * The file descriptor is invalid.
208 * For example, the file descriptor was closed prematurely.
209 *
210 * The looper always sends notifications about invalid file descriptors; it is not necessary
211 * to specify this event flag in the requested event set.
212 */
213 EVENT_INVALID = 1 << 4,
214 };
215
216 enum {
217 /**
218 * Option for Looper_prepare: this looper will accept calls to
219 * Looper_addFd() that do not have a callback (that is provide NULL
220 * for the callback). In this case the caller of Looper_pollOnce()
221 * or Looper_pollAll() MUST check the return from these functions to
222 * discover when data is available on such fds and process it.
223 */
224 PREPARE_ALLOW_NON_CALLBACKS = 1<<0
225 };
226
Jeff Brown7901eb22010-09-13 23:17:30 -0700227 /**
228 * Creates a looper.
229 *
230 * If allowNonCallbaks is true, the looper will allow file descriptors to be
231 * registered without associated callbacks. This assumes that the caller of
232 * pollOnce() is prepared to handle callback-less events itself.
233 */
234 Looper(bool allowNonCallbacks);
235
236 /**
237 * Returns whether this looper instance allows the registration of file descriptors
238 * using identifiers instead of callbacks.
239 */
240 bool getAllowNonCallbacks() const;
241
242 /**
243 * Waits for events to be available, with optional timeout in milliseconds.
244 * Invokes callbacks for all file descriptors on which an event occurred.
245 *
246 * If the timeout is zero, returns immediately without blocking.
247 * If the timeout is negative, waits indefinitely until an event appears.
248 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800249 * Returns POLL_WAKE if the poll was awoken using wake() before
Jeff Brown7901eb22010-09-13 23:17:30 -0700250 * the timeout expired and no callbacks were invoked and no other file
251 * descriptors were ready.
252 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800253 * Returns POLL_CALLBACK if one or more callbacks were invoked.
Jeff Brown7901eb22010-09-13 23:17:30 -0700254 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800255 * Returns POLL_TIMEOUT if there was no data before the given
Jeff Brown7901eb22010-09-13 23:17:30 -0700256 * timeout expired.
257 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800258 * Returns POLL_ERROR if an error occurred.
Jeff Brown7901eb22010-09-13 23:17:30 -0700259 *
260 * Returns a value >= 0 containing an identifier if its file descriptor has data
261 * and it has no callback function (requiring the caller here to handle it).
262 * In this (and only this) case outFd, outEvents and outData will contain the poll
263 * events and data associated with the fd, otherwise they will be set to NULL.
264 *
265 * This method does not return until it has finished invoking the appropriate callbacks
266 * for all file descriptors that were signalled.
267 */
Jeff Brown905682a2010-09-16 18:28:12 -0700268 int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
269 inline int pollOnce(int timeoutMillis) {
Yi Kongc1a15622018-07-11 17:37:34 -0700270 return pollOnce(timeoutMillis, nullptr, nullptr, nullptr);
Jeff Brown905682a2010-09-16 18:28:12 -0700271 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700272
273 /**
274 * Like pollOnce(), but performs all pending callbacks until all
275 * data has been consumed or a file descriptor is available with no callback.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800276 * This function will never return POLL_CALLBACK.
Jeff Brown7901eb22010-09-13 23:17:30 -0700277 */
Jeff Brown905682a2010-09-16 18:28:12 -0700278 int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
279 inline int pollAll(int timeoutMillis) {
Yi Kongc1a15622018-07-11 17:37:34 -0700280 return pollAll(timeoutMillis, nullptr, nullptr, nullptr);
Jeff Brown905682a2010-09-16 18:28:12 -0700281 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700282
283 /**
284 * Wakes the poll asynchronously.
285 *
286 * This method can be called on any thread.
287 * This method returns immediately.
288 */
289 void wake();
290
291 /**
292 * Adds a new file descriptor to be polled by the looper.
293 * If the same file descriptor was previously added, it is replaced.
294 *
295 * "fd" is the file descriptor to be added.
Jeff Browndd1b0372012-05-31 16:15:35 -0700296 * "ident" is an identifier for this event, which is returned from pollOnce().
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800297 * The identifier must be >= 0, or POLL_CALLBACK if providing a non-NULL callback.
298 * "events" are the poll events to wake up on. Typically this is EVENT_INPUT.
Jeff Brown7901eb22010-09-13 23:17:30 -0700299 * "callback" is the function to call when there is an event on the file descriptor.
300 * "data" is a private data pointer to supply to the callback.
301 *
302 * There are two main uses of this function:
303 *
304 * (1) If "callback" is non-NULL, then this function will be called when there is
305 * data on the file descriptor. It should execute any events it has pending,
306 * appropriately reading from the file descriptor. The 'ident' is ignored in this case.
307 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800308 * (2) If "callback" is NULL, the 'ident' will be returned by Looper_pollOnce
Jeff Brown7901eb22010-09-13 23:17:30 -0700309 * when its file descriptor has data available, requiring the caller to take
310 * care of processing it.
311 *
312 * Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
313 *
314 * This method can be called on any thread.
315 * This method may block briefly if it needs to wake the poll.
Jeff Browndd1b0372012-05-31 16:15:35 -0700316 *
317 * The callback may either be specified as a bare function pointer or as a smart
318 * pointer callback object. The smart pointer should be preferred because it is
319 * easier to avoid races when the callback is removed from a different thread.
320 * See removeFd() for details.
Jeff Brown7901eb22010-09-13 23:17:30 -0700321 */
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800322 int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data);
Jeff Browndd1b0372012-05-31 16:15:35 -0700323 int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700324
325 /**
326 * Removes a previously added file descriptor from the looper.
327 *
328 * When this method returns, it is safe to close the file descriptor since the looper
329 * will no longer have a reference to it. However, it is possible for the callback to
330 * already be running or for it to run one last time if the file descriptor was already
331 * signalled. Calling code is responsible for ensuring that this case is safely handled.
332 * For example, if the callback takes care of removing itself during its own execution either
333 * by returning 0 or by calling this method, then it can be guaranteed to not be invoked
334 * again at any later time unless registered anew.
335 *
Jeff Browndd1b0372012-05-31 16:15:35 -0700336 * A simple way to avoid this problem is to use the version of addFd() that takes
337 * a sp<LooperCallback> instead of a bare function pointer. The LooperCallback will
338 * be released at the appropriate time by the Looper.
339 *
Jeff Brown7901eb22010-09-13 23:17:30 -0700340 * Returns 1 if the file descriptor was removed, 0 if none was previously registered.
341 *
342 * This method can be called on any thread.
343 * This method may block briefly if it needs to wake the poll.
344 */
345 int removeFd(int fd);
346
347 /**
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800348 * Enqueues a message to be processed by the specified handler.
349 *
350 * The handler must not be null.
351 * This method can be called on any thread.
352 */
353 void sendMessage(const sp<MessageHandler>& handler, const Message& message);
354
355 /**
356 * Enqueues a message to be processed by the specified handler after all pending messages
357 * after the specified delay.
358 *
359 * The time delay is specified in uptime nanoseconds.
360 * The handler must not be null.
361 * This method can be called on any thread.
362 */
363 void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
364 const Message& message);
365
366 /**
367 * Enqueues a message to be processed by the specified handler after all pending messages
368 * at the specified time.
369 *
370 * The time is specified in uptime nanoseconds.
371 * The handler must not be null.
372 * This method can be called on any thread.
373 */
374 void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
375 const Message& message);
376
377 /**
378 * Removes all messages for the specified handler from the queue.
379 *
380 * The handler must not be null.
381 * This method can be called on any thread.
382 */
383 void removeMessages(const sp<MessageHandler>& handler);
384
385 /**
386 * Removes all messages of a particular type for the specified handler from the queue.
387 *
388 * The handler must not be null.
389 * This method can be called on any thread.
390 */
391 void removeMessages(const sp<MessageHandler>& handler, int what);
392
393 /**
Jeff Brown27e57212015-02-26 14:16:30 -0800394 * Returns whether this looper's thread is currently polling for more work to do.
395 * This is a good signal that the loop is still alive rather than being stuck
396 * handling a callback. Note that this method is intrinsically racy, since the
397 * state of the loop can change before you get the result back.
Dianne Hackborn19159f92013-05-06 14:25:20 -0700398 */
Jeff Brown27e57212015-02-26 14:16:30 -0800399 bool isPolling() const;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700400
401 /**
Jeff Brown7901eb22010-09-13 23:17:30 -0700402 * Prepares a looper associated with the calling thread, and returns it.
403 * If the thread already has a looper, it is returned. Otherwise, a new
404 * one is created, associated with the thread, and returned.
405 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800406 * The opts may be PREPARE_ALLOW_NON_CALLBACKS or 0.
Jeff Brown7901eb22010-09-13 23:17:30 -0700407 */
408 static sp<Looper> prepare(int opts);
409
410 /**
411 * Sets the given looper to be associated with the calling thread.
412 * If another looper is already associated with the thread, it is replaced.
413 *
414 * If "looper" is NULL, removes the currently associated looper.
415 */
416 static void setForThread(const sp<Looper>& looper);
417
418 /**
419 * Returns the looper associated with the calling thread, or NULL if
420 * there is not one.
421 */
422 static sp<Looper> getForThread();
423
424private:
Prabir Pradhan729057a2021-08-12 12:36:31 -0700425 using SequenceNumber = uint64_t;
Jeff Browne7d54f82015-03-12 19:32:39 -0700426
Prabir Pradhan729057a2021-08-12 12:36:31 -0700427 struct Request {
428 int fd;
429 int ident;
430 int events;
431 sp<LooperCallback> callback;
432 void* data;
433
434 uint32_t getEpollEvents() const;
435 };
Jeff Brown7901eb22010-09-13 23:17:30 -0700436
437 struct Response {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700438 SequenceNumber seq;
Jeff Brown7901eb22010-09-13 23:17:30 -0700439 int events;
440 Request request;
441 };
442
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800443 struct MessageEnvelope {
444 MessageEnvelope() : uptime(0) { }
445
Yurii Zubrytskyif8987c32020-04-22 15:37:21 -0700446 MessageEnvelope(nsecs_t u, sp<MessageHandler> h, const Message& m)
447 : uptime(u), handler(std::move(h)), message(m) {}
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800448
449 nsecs_t uptime;
450 sp<MessageHandler> handler;
451 Message message;
452 };
453
Jeff Brown7901eb22010-09-13 23:17:30 -0700454 const bool mAllowNonCallbacks; // immutable
455
Josh Gao2d08ae52018-07-18 17:26:24 -0700456 android::base::unique_fd mWakeEventFd; // immutable
Jeff Brown8d15c742010-10-05 15:35:37 -0700457 Mutex mLock;
458
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800459 Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock
460 bool mSendingMessage; // guarded by mLock
461
Dianne Hackborn19159f92013-05-06 14:25:20 -0700462 // Whether we are currently waiting for work. Not protected by a lock,
463 // any use of it is racy anyway.
Jeff Brown27e57212015-02-26 14:16:30 -0800464 volatile bool mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700465
Josh Gao2d08ae52018-07-18 17:26:24 -0700466 android::base::unique_fd mEpollFd; // guarded by mLock but only modified on the looper thread
Jeff Browne7d54f82015-03-12 19:32:39 -0700467 bool mEpollRebuildRequired; // guarded by mLock
Jeff Brown7901eb22010-09-13 23:17:30 -0700468
Prabir Pradhan729057a2021-08-12 12:36:31 -0700469 // Locked maps of fds and sequence numbers monitoring requests.
470 // Both maps must be kept in sync at all times.
471 std::unordered_map<SequenceNumber, Request> mRequests; // guarded by mLock
472 std::unordered_map<int /*fd*/, SequenceNumber> mSequenceNumberByFd; // guarded by mLock
473
474 // The sequence number to use for the next fd that is added to the looper.
475 // The sequence number 0 is reserved for the WakeEventFd.
476 SequenceNumber mNextRequestSeq; // guarded by mLock
Jeff Brown8d15c742010-10-05 15:35:37 -0700477
Jeff Brown7901eb22010-09-13 23:17:30 -0700478 // This state is only used privately by pollOnce and does not require a lock since
479 // it runs on a single thread.
480 Vector<Response> mResponses;
481 size_t mResponseIndex;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800482 nsecs_t mNextMessageUptime; // set to LLONG_MAX when none
Jeff Brown7901eb22010-09-13 23:17:30 -0700483
484 int pollInner(int timeoutMillis);
Prabir Pradhan729057a2021-08-12 12:36:31 -0700485 int removeSequenceNumberLocked(SequenceNumber seq); // requires mLock
Jeff Brown8d15c742010-10-05 15:35:37 -0700486 void awoken();
Jeff Browne7d54f82015-03-12 19:32:39 -0700487 void rebuildEpollLocked();
488 void scheduleEpollRebuildLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -0700489
Jeff Brownd1805182010-09-21 15:11:18 -0700490 static void initTLSKey();
Jeff Brown7901eb22010-09-13 23:17:30 -0700491 static void threadDestructor(void *st);
Jeff Browne7d54f82015-03-12 19:32:39 -0700492 static void initEpollEvent(struct epoll_event* eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700493};
494
495} // namespace android
496
497#endif // UTILS_LOOPER_H