• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
20 #include <utils/threads.h>
21 #include <utils/RefBase.h>
22 #include <utils/KeyedVector.h>
23 #include <utils/Timers.h>
24 
25 #include <sys/epoll.h>
26 
27 #include <android-base/unique_fd.h>
28 
29 namespace android {
30 
31 /*
32  * NOTE: Since Looper is used to implement the NDK ALooper, the Looper
33  * enums and the signature of Looper_callbackFunc need to align with
34  * that implementation.
35  */
36 
37 /**
38  * For callback-based event loops, this is the prototype of the function
39  * that is called when a file descriptor event occurs.
40  * It is given the file descriptor it is associated with,
41  * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
42  * and the data pointer that was originally supplied.
43  *
44  * Implementations should return 1 to continue receiving callbacks, or 0
45  * to have this file descriptor and callback unregistered from the looper.
46  */
47 typedef int (*Looper_callbackFunc)(int fd, int events, void* data);
48 
49 /**
50  * A message that can be posted to a Looper.
51  */
52 struct Message {
MessageMessage53     Message() : what(0) { }
MessageMessage54     Message(int w) : what(w) { }
55 
56     /* The message type. (interpretation is left up to the handler) */
57     int what;
58 };
59 
60 
61 /**
62  * Interface for a Looper message handler.
63  *
64  * The Looper holds a strong reference to the message handler whenever it has
65  * a message to deliver to it.  Make sure to call Looper::removeMessages
66  * to remove any pending messages destined for the handler so that the handler
67  * can be destroyed.
68  */
69 class MessageHandler : public virtual RefBase {
70 protected:
71     virtual ~MessageHandler();
72 
73 public:
74     /**
75      * Handles a message.
76      */
77     virtual void handleMessage(const Message& message) = 0;
78 };
79 
80 
81 /**
82  * A simple proxy that holds a weak reference to a message handler.
83  */
84 class WeakMessageHandler : public MessageHandler {
85 protected:
86     virtual ~WeakMessageHandler();
87 
88 public:
89     WeakMessageHandler(const wp<MessageHandler>& handler);
90     virtual void handleMessage(const Message& message);
91 
92 private:
93     wp<MessageHandler> mHandler;
94 };
95 
96 
97 /**
98  * A looper callback.
99  */
100 class LooperCallback : public virtual RefBase {
101 protected:
102     virtual ~LooperCallback();
103 
104 public:
105     /**
106      * Handles a poll event for the given file descriptor.
107      * It is given the file descriptor it is associated with,
108      * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
109      * and the data pointer that was originally supplied.
110      *
111      * Implementations should return 1 to continue receiving callbacks, or 0
112      * to have this file descriptor and callback unregistered from the looper.
113      */
114     virtual int handleEvent(int fd, int events, void* data) = 0;
115 };
116 
117 /**
118  * Wraps a Looper_callbackFunc function pointer.
119  */
120 class SimpleLooperCallback : public LooperCallback {
121 protected:
122     virtual ~SimpleLooperCallback();
123 
124 public:
125     SimpleLooperCallback(Looper_callbackFunc callback);
126     virtual int handleEvent(int fd, int events, void* data);
127 
128 private:
129     Looper_callbackFunc mCallback;
130 };
131 
132 /**
133  * A polling loop that supports monitoring file descriptor events, optionally
134  * using callbacks.  The implementation uses epoll() internally.
135  *
136  * A looper can be associated with a thread although there is no requirement that it must be.
137  */
138 class Looper : public RefBase {
139 protected:
140     virtual ~Looper();
141 
142 public:
143     enum {
144         /**
145          * Result from Looper_pollOnce() and Looper_pollAll():
146          * The poll was awoken using wake() before the timeout expired
147          * and no callbacks were executed and no other file descriptors were ready.
148          */
149         POLL_WAKE = -1,
150 
151         /**
152          * Result from Looper_pollOnce() and Looper_pollAll():
153          * One or more callbacks were executed.
154          */
155         POLL_CALLBACK = -2,
156 
157         /**
158          * Result from Looper_pollOnce() and Looper_pollAll():
159          * The timeout expired.
160          */
161         POLL_TIMEOUT = -3,
162 
163         /**
164          * Result from Looper_pollOnce() and Looper_pollAll():
165          * An error occurred.
166          */
167         POLL_ERROR = -4,
168     };
169 
170     /**
171      * Flags for file descriptor events that a looper can monitor.
172      *
173      * These flag bits can be combined to monitor multiple events at once.
174      */
175     enum {
176         /**
177          * The file descriptor is available for read operations.
178          */
179         EVENT_INPUT = 1 << 0,
180 
181         /**
182          * The file descriptor is available for write operations.
183          */
184         EVENT_OUTPUT = 1 << 1,
185 
186         /**
187          * The file descriptor has encountered an error condition.
188          *
189          * The looper always sends notifications about errors; it is not necessary
190          * to specify this event flag in the requested event set.
191          */
192         EVENT_ERROR = 1 << 2,
193 
194         /**
195          * The file descriptor was hung up.
196          * For example, indicates that the remote end of a pipe or socket was closed.
197          *
198          * The looper always sends notifications about hangups; it is not necessary
199          * to specify this event flag in the requested event set.
200          */
201         EVENT_HANGUP = 1 << 3,
202 
203         /**
204          * The file descriptor is invalid.
205          * For example, the file descriptor was closed prematurely.
206          *
207          * The looper always sends notifications about invalid file descriptors; it is not necessary
208          * to specify this event flag in the requested event set.
209          */
210         EVENT_INVALID = 1 << 4,
211     };
212 
213     enum {
214         /**
215          * Option for Looper_prepare: this looper will accept calls to
216          * Looper_addFd() that do not have a callback (that is provide NULL
217          * for the callback).  In this case the caller of Looper_pollOnce()
218          * or Looper_pollAll() MUST check the return from these functions to
219          * discover when data is available on such fds and process it.
220          */
221         PREPARE_ALLOW_NON_CALLBACKS = 1<<0
222     };
223 
224     /**
225      * Creates a looper.
226      *
227      * If allowNonCallbaks is true, the looper will allow file descriptors to be
228      * registered without associated callbacks.  This assumes that the caller of
229      * pollOnce() is prepared to handle callback-less events itself.
230      */
231     Looper(bool allowNonCallbacks);
232 
233     /**
234      * Returns whether this looper instance allows the registration of file descriptors
235      * using identifiers instead of callbacks.
236      */
237     bool getAllowNonCallbacks() const;
238 
239     /**
240      * Waits for events to be available, with optional timeout in milliseconds.
241      * Invokes callbacks for all file descriptors on which an event occurred.
242      *
243      * If the timeout is zero, returns immediately without blocking.
244      * If the timeout is negative, waits indefinitely until an event appears.
245      *
246      * Returns POLL_WAKE if the poll was awoken using wake() before
247      * the timeout expired and no callbacks were invoked and no other file
248      * descriptors were ready.
249      *
250      * Returns POLL_CALLBACK if one or more callbacks were invoked.
251      *
252      * Returns POLL_TIMEOUT if there was no data before the given
253      * timeout expired.
254      *
255      * Returns POLL_ERROR if an error occurred.
256      *
257      * Returns a value >= 0 containing an identifier if its file descriptor has data
258      * and it has no callback function (requiring the caller here to handle it).
259      * In this (and only this) case outFd, outEvents and outData will contain the poll
260      * events and data associated with the fd, otherwise they will be set to NULL.
261      *
262      * This method does not return until it has finished invoking the appropriate callbacks
263      * for all file descriptors that were signalled.
264      */
265     int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
pollOnce(int timeoutMillis)266     inline int pollOnce(int timeoutMillis) {
267         return pollOnce(timeoutMillis, nullptr, nullptr, nullptr);
268     }
269 
270     /**
271      * Like pollOnce(), but performs all pending callbacks until all
272      * data has been consumed or a file descriptor is available with no callback.
273      * This function will never return POLL_CALLBACK.
274      */
275     int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
pollAll(int timeoutMillis)276     inline int pollAll(int timeoutMillis) {
277         return pollAll(timeoutMillis, nullptr, nullptr, nullptr);
278     }
279 
280     /**
281      * Wakes the poll asynchronously.
282      *
283      * This method can be called on any thread.
284      * This method returns immediately.
285      */
286     void wake();
287 
288     /**
289      * Adds a new file descriptor to be polled by the looper.
290      * If the same file descriptor was previously added, it is replaced.
291      *
292      * "fd" is the file descriptor to be added.
293      * "ident" is an identifier for this event, which is returned from pollOnce().
294      * The identifier must be >= 0, or POLL_CALLBACK if providing a non-NULL callback.
295      * "events" are the poll events to wake up on.  Typically this is EVENT_INPUT.
296      * "callback" is the function to call when there is an event on the file descriptor.
297      * "data" is a private data pointer to supply to the callback.
298      *
299      * There are two main uses of this function:
300      *
301      * (1) If "callback" is non-NULL, then this function will be called when there is
302      * data on the file descriptor.  It should execute any events it has pending,
303      * appropriately reading from the file descriptor.  The 'ident' is ignored in this case.
304      *
305      * (2) If "callback" is NULL, the 'ident' will be returned by Looper_pollOnce
306      * when its file descriptor has data available, requiring the caller to take
307      * care of processing it.
308      *
309      * Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
310      *
311      * This method can be called on any thread.
312      * This method may block briefly if it needs to wake the poll.
313      *
314      * The callback may either be specified as a bare function pointer or as a smart
315      * pointer callback object.  The smart pointer should be preferred because it is
316      * easier to avoid races when the callback is removed from a different thread.
317      * See removeFd() for details.
318      */
319     int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data);
320     int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);
321 
322     /**
323      * Removes a previously added file descriptor from the looper.
324      *
325      * When this method returns, it is safe to close the file descriptor since the looper
326      * will no longer have a reference to it.  However, it is possible for the callback to
327      * already be running or for it to run one last time if the file descriptor was already
328      * signalled.  Calling code is responsible for ensuring that this case is safely handled.
329      * For example, if the callback takes care of removing itself during its own execution either
330      * by returning 0 or by calling this method, then it can be guaranteed to not be invoked
331      * again at any later time unless registered anew.
332      *
333      * A simple way to avoid this problem is to use the version of addFd() that takes
334      * a sp<LooperCallback> instead of a bare function pointer.  The LooperCallback will
335      * be released at the appropriate time by the Looper.
336      *
337      * Returns 1 if the file descriptor was removed, 0 if none was previously registered.
338      *
339      * This method can be called on any thread.
340      * This method may block briefly if it needs to wake the poll.
341      */
342     int removeFd(int fd);
343 
344     /**
345      * Enqueues a message to be processed by the specified handler.
346      *
347      * The handler must not be null.
348      * This method can be called on any thread.
349      */
350     void sendMessage(const sp<MessageHandler>& handler, const Message& message);
351 
352     /**
353      * Enqueues a message to be processed by the specified handler after all pending messages
354      * after the specified delay.
355      *
356      * The time delay is specified in uptime nanoseconds.
357      * The handler must not be null.
358      * This method can be called on any thread.
359      */
360     void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
361             const Message& message);
362 
363     /**
364      * Enqueues a message to be processed by the specified handler after all pending messages
365      * at the specified time.
366      *
367      * The time is specified in uptime nanoseconds.
368      * The handler must not be null.
369      * This method can be called on any thread.
370      */
371     void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
372             const Message& message);
373 
374     /**
375      * Removes all messages for the specified handler from the queue.
376      *
377      * The handler must not be null.
378      * This method can be called on any thread.
379      */
380     void removeMessages(const sp<MessageHandler>& handler);
381 
382     /**
383      * Removes all messages of a particular type for the specified handler from the queue.
384      *
385      * The handler must not be null.
386      * This method can be called on any thread.
387      */
388     void removeMessages(const sp<MessageHandler>& handler, int what);
389 
390     /**
391      * Returns whether this looper's thread is currently polling for more work to do.
392      * This is a good signal that the loop is still alive rather than being stuck
393      * handling a callback.  Note that this method is intrinsically racy, since the
394      * state of the loop can change before you get the result back.
395      */
396     bool isPolling() const;
397 
398     /**
399      * Prepares a looper associated with the calling thread, and returns it.
400      * If the thread already has a looper, it is returned.  Otherwise, a new
401      * one is created, associated with the thread, and returned.
402      *
403      * The opts may be PREPARE_ALLOW_NON_CALLBACKS or 0.
404      */
405     static sp<Looper> prepare(int opts);
406 
407     /**
408      * Sets the given looper to be associated with the calling thread.
409      * If another looper is already associated with the thread, it is replaced.
410      *
411      * If "looper" is NULL, removes the currently associated looper.
412      */
413     static void setForThread(const sp<Looper>& looper);
414 
415     /**
416      * Returns the looper associated with the calling thread, or NULL if
417      * there is not one.
418      */
419     static sp<Looper> getForThread();
420 
421 private:
422     struct Request {
423         int fd;
424         int ident;
425         int events;
426         int seq;
427         sp<LooperCallback> callback;
428         void* data;
429 
430         void initEventItem(struct epoll_event* eventItem) const;
431     };
432 
433     struct Response {
434         int events;
435         Request request;
436     };
437 
438     struct MessageEnvelope {
MessageEnvelopeMessageEnvelope439         MessageEnvelope() : uptime(0) { }
440 
MessageEnvelopeMessageEnvelope441         MessageEnvelope(nsecs_t u, const sp<MessageHandler> h,
442                 const Message& m) : uptime(u), handler(h), message(m) {
443         }
444 
445         nsecs_t uptime;
446         sp<MessageHandler> handler;
447         Message message;
448     };
449 
450     const bool mAllowNonCallbacks; // immutable
451 
452     android::base::unique_fd mWakeEventFd;  // immutable
453     Mutex mLock;
454 
455     Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock
456     bool mSendingMessage; // guarded by mLock
457 
458     // Whether we are currently waiting for work.  Not protected by a lock,
459     // any use of it is racy anyway.
460     volatile bool mPolling;
461 
462     android::base::unique_fd mEpollFd;  // guarded by mLock but only modified on the looper thread
463     bool mEpollRebuildRequired; // guarded by mLock
464 
465     // Locked list of file descriptor monitoring requests.
466     KeyedVector<int, Request> mRequests;  // guarded by mLock
467     int mNextRequestSeq;
468 
469     // This state is only used privately by pollOnce and does not require a lock since
470     // it runs on a single thread.
471     Vector<Response> mResponses;
472     size_t mResponseIndex;
473     nsecs_t mNextMessageUptime; // set to LLONG_MAX when none
474 
475     int pollInner(int timeoutMillis);
476     int removeFd(int fd, int seq);
477     void awoken();
478     void pushResponse(int events, const Request& request);
479     void rebuildEpollLocked();
480     void scheduleEpollRebuildLocked();
481 
482     static void initTLSKey();
483     static void threadDestructor(void *st);
484     static void initEpollEvent(struct epoll_event* eventItem);
485 };
486 
487 } // namespace android
488 
489 #endif // UTILS_LOOPER_H
490