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/RefBase.h> 21 #include <utils/Timers.h> 22 #include <utils/Vector.h> 23 #include <utils/threads.h> 24 25 #include <sys/epoll.h> 26 27 #include <android-base/unique_fd.h> 28 29 #include <unordered_map> 30 #include <utility> 31 32 namespace android { 33 34 /* 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 */ 50 typedef int (*Looper_callbackFunc)(int fd, int events, void* data); 51 52 /** 53 * A message that can be posted to a Looper. 54 */ 55 struct Message { MessageMessage56 Message() : what(0) { } MessageMessage57 Message(int w) : what(w) { } 58 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 */ 72 class MessageHandler : public virtual RefBase { 73 protected: 74 virtual ~MessageHandler(); 75 76 public: 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 */ 87 class WeakMessageHandler : public MessageHandler { 88 protected: 89 virtual ~WeakMessageHandler(); 90 91 public: 92 WeakMessageHandler(const wp<MessageHandler>& handler); 93 virtual void handleMessage(const Message& message); 94 95 private: 96 wp<MessageHandler> mHandler; 97 }; 98 99 100 /** 101 * A looper callback. 102 */ 103 class LooperCallback : public virtual RefBase { 104 protected: 105 virtual ~LooperCallback(); 106 107 public: 108 /** 109 * Handles a poll event for the given file descriptor. 110 * It is given the file descriptor it is associated with, 111 * a bitmask of the poll events that were triggered (typically EVENT_INPUT), 112 * 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 120 /** 121 * Wraps a Looper_callbackFunc function pointer. 122 */ 123 class SimpleLooperCallback : public LooperCallback { 124 protected: 125 virtual ~SimpleLooperCallback(); 126 127 public: 128 SimpleLooperCallback(Looper_callbackFunc callback); 129 virtual int handleEvent(int fd, int events, void* data); 130 131 private: 132 Looper_callbackFunc mCallback; 133 }; 134 135 /** 136 * 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 */ 141 class Looper : public RefBase { 142 protected: 143 virtual ~Looper(); 144 145 public: 146 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 227 /** 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 * 249 * Returns POLL_WAKE if the poll was awoken using wake() before 250 * the timeout expired and no callbacks were invoked and no other file 251 * descriptors were ready. 252 * 253 * Returns POLL_CALLBACK if one or more callbacks were invoked. 254 * 255 * Returns POLL_TIMEOUT if there was no data before the given 256 * timeout expired. 257 * 258 * Returns POLL_ERROR if an error occurred. 259 * 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 */ 268 int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData); pollOnce(int timeoutMillis)269 inline int pollOnce(int timeoutMillis) { 270 return pollOnce(timeoutMillis, nullptr, nullptr, nullptr); 271 } 272 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. 276 * This function will never return POLL_CALLBACK. 277 */ 278 int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData); pollAll(int timeoutMillis)279 inline int pollAll(int timeoutMillis) { 280 return pollAll(timeoutMillis, nullptr, nullptr, nullptr); 281 } 282 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. 296 * "ident" is an identifier for this event, which is returned from pollOnce(). 297 * 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. 299 * "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 * 308 * (2) If "callback" is NULL, the 'ident' will be returned by Looper_pollOnce 309 * 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. 316 * 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. 321 */ 322 int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data); 323 int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data); 324 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 * 336 * 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 * 340 * 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 /** 348 * 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 /** 394 * 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. 398 */ 399 bool isPolling() const; 400 401 /** 402 * 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 * 406 * The opts may be PREPARE_ALLOW_NON_CALLBACKS or 0. 407 */ 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 424 private: 425 using SequenceNumber = uint64_t; 426 427 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 }; 436 437 struct Response { 438 SequenceNumber seq; 439 int events; 440 Request request; 441 }; 442 443 struct MessageEnvelope { MessageEnvelopeMessageEnvelope444 MessageEnvelope() : uptime(0) { } 445 MessageEnvelopeMessageEnvelope446 MessageEnvelope(nsecs_t u, sp<MessageHandler> h, const Message& m) 447 : uptime(u), handler(std::move(h)), message(m) {} 448 449 nsecs_t uptime; 450 sp<MessageHandler> handler; 451 Message message; 452 }; 453 454 const bool mAllowNonCallbacks; // immutable 455 456 android::base::unique_fd mWakeEventFd; // immutable 457 Mutex mLock; 458 459 Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock 460 bool mSendingMessage; // guarded by mLock 461 462 // Whether we are currently waiting for work. Not protected by a lock, 463 // any use of it is racy anyway. 464 volatile bool mPolling; 465 466 android::base::unique_fd mEpollFd; // guarded by mLock but only modified on the looper thread 467 bool mEpollRebuildRequired; // guarded by mLock 468 469 // 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 477 478 // 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; 482 nsecs_t mNextMessageUptime; // set to LLONG_MAX when none 483 484 int pollInner(int timeoutMillis); 485 int removeSequenceNumberLocked(SequenceNumber seq); // requires mLock 486 void awoken(); 487 void rebuildEpollLocked(); 488 void scheduleEpollRebuildLocked(); 489 490 static void initTLSKey(); 491 static void threadDestructor(void *st); 492 static void initEpollEvent(struct epoll_event* eventItem); 493 }; 494 495 } // namespace android 496 497 #endif // UTILS_LOOPER_H 498