• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2010 The Android Open Source Project
3 //
4 // A looper implementation based on epoll().
5 //
6 #define LOG_TAG "Looper"
7 
8 //#define LOG_NDEBUG 0
9 
10 // Debugs poll and wake interactions.
11 #ifndef DEBUG_POLL_AND_WAKE
12 #define DEBUG_POLL_AND_WAKE 0
13 #endif
14 
15 // Debugs callback registration and invocation.
16 #ifndef DEBUG_CALLBACKS
17 #define DEBUG_CALLBACKS 0
18 #endif
19 
20 #include <utils/Looper.h>
21 
22 #include <sys/eventfd.h>
23 #include <cinttypes>
24 
25 namespace android {
26 
27 namespace {
28 
29 constexpr uint64_t WAKE_EVENT_FD_SEQ = 1;
30 
createEpollEvent(uint32_t events,uint64_t seq)31 epoll_event createEpollEvent(uint32_t events, uint64_t seq) {
32     return {.events = events, .data = {.u64 = seq}};
33 }
34 
35 }  // namespace
36 
37 // --- WeakMessageHandler ---
38 
WeakMessageHandler(const wp<MessageHandler> & handler)39 WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
40         mHandler(handler) {
41 }
42 
~WeakMessageHandler()43 WeakMessageHandler::~WeakMessageHandler() {
44 }
45 
handleMessage(const Message & message)46 void WeakMessageHandler::handleMessage(const Message& message) {
47     sp<MessageHandler> handler = mHandler.promote();
48     if (handler != nullptr) {
49         handler->handleMessage(message);
50     }
51 }
52 
53 
54 // --- SimpleLooperCallback ---
55 
SimpleLooperCallback(Looper_callbackFunc callback)56 SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
57         mCallback(callback) {
58 }
59 
~SimpleLooperCallback()60 SimpleLooperCallback::~SimpleLooperCallback() {
61 }
62 
handleEvent(int fd,int events,void * data)63 int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
64     return mCallback(fd, events, data);
65 }
66 
67 
68 // --- Looper ---
69 
70 // Maximum number of file descriptors for which to retrieve poll events each iteration.
71 static const int EPOLL_MAX_EVENTS = 16;
72 
73 static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
74 static pthread_key_t gTLSKey = 0;
75 
Looper(bool allowNonCallbacks)76 Looper::Looper(bool allowNonCallbacks)
77     : mAllowNonCallbacks(allowNonCallbacks),
78       mSendingMessage(false),
79       mPolling(false),
80       mEpollRebuildRequired(false),
81       mNextRequestSeq(WAKE_EVENT_FD_SEQ + 1),
82       mResponseIndex(0),
83       mNextMessageUptime(LLONG_MAX) {
84     mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
85     LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));
86 
87     AutoMutex _l(mLock);
88     rebuildEpollLocked();
89 }
90 
~Looper()91 Looper::~Looper() {
92 }
93 
initTLSKey()94 void Looper::initTLSKey() {
95     int error = pthread_key_create(&gTLSKey, threadDestructor);
96     LOG_ALWAYS_FATAL_IF(error != 0, "Could not allocate TLS key: %s", strerror(error));
97 }
98 
threadDestructor(void * st)99 void Looper::threadDestructor(void *st) {
100     Looper* const self = static_cast<Looper*>(st);
101     if (self != nullptr) {
102         self->decStrong((void*)threadDestructor);
103     }
104 }
105 
setForThread(const sp<Looper> & looper)106 void Looper::setForThread(const sp<Looper>& looper) {
107     sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
108 
109     if (looper != nullptr) {
110         looper->incStrong((void*)threadDestructor);
111     }
112 
113     pthread_setspecific(gTLSKey, looper.get());
114 
115     if (old != nullptr) {
116         old->decStrong((void*)threadDestructor);
117     }
118 }
119 
getForThread()120 sp<Looper> Looper::getForThread() {
121     int result = pthread_once(& gTLSOnce, initTLSKey);
122     LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
123 
124     Looper* looper = (Looper*)pthread_getspecific(gTLSKey);
125     return sp<Looper>::fromExisting(looper);
126 }
127 
prepare(int opts)128 sp<Looper> Looper::prepare(int opts) {
129     bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
130     sp<Looper> looper = Looper::getForThread();
131     if (looper == nullptr) {
132         looper = sp<Looper>::make(allowNonCallbacks);
133         Looper::setForThread(looper);
134     }
135     if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
136         ALOGW("Looper already prepared for this thread with a different value for the "
137                 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
138     }
139     return looper;
140 }
141 
getAllowNonCallbacks() const142 bool Looper::getAllowNonCallbacks() const {
143     return mAllowNonCallbacks;
144 }
145 
rebuildEpollLocked()146 void Looper::rebuildEpollLocked() {
147     // Close old epoll instance if we have one.
148     if (mEpollFd >= 0) {
149 #if DEBUG_CALLBACKS
150         ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
151 #endif
152         mEpollFd.reset();
153     }
154 
155     // Allocate the new epoll instance and register the WakeEventFd.
156     mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));
157     LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
158 
159     epoll_event wakeEvent = createEpollEvent(EPOLLIN, WAKE_EVENT_FD_SEQ);
160     int result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &wakeEvent);
161     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
162                         strerror(errno));
163 
164     for (const auto& [seq, request] : mRequests) {
165         epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
166 
167         int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, request.fd, &eventItem);
168         if (epollResult < 0) {
169             ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
170                   request.fd, strerror(errno));
171         }
172     }
173 }
174 
scheduleEpollRebuildLocked()175 void Looper::scheduleEpollRebuildLocked() {
176     if (!mEpollRebuildRequired) {
177 #if DEBUG_CALLBACKS
178         ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
179 #endif
180         mEpollRebuildRequired = true;
181         wake();
182     }
183 }
184 
pollOnce(int timeoutMillis,int * outFd,int * outEvents,void ** outData)185 int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
186     int result = 0;
187     for (;;) {
188         while (mResponseIndex < mResponses.size()) {
189             const Response& response = mResponses.itemAt(mResponseIndex++);
190             int ident = response.request.ident;
191             if (ident >= 0) {
192                 int fd = response.request.fd;
193                 int events = response.events;
194                 void* data = response.request.data;
195 #if DEBUG_POLL_AND_WAKE
196                 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
197                         "fd=%d, events=0x%x, data=%p",
198                         this, ident, fd, events, data);
199 #endif
200                 if (outFd != nullptr) *outFd = fd;
201                 if (outEvents != nullptr) *outEvents = events;
202                 if (outData != nullptr) *outData = data;
203                 return ident;
204             }
205         }
206 
207         if (result != 0) {
208 #if DEBUG_POLL_AND_WAKE
209             ALOGD("%p ~ pollOnce - returning result %d", this, result);
210 #endif
211             if (outFd != nullptr) *outFd = 0;
212             if (outEvents != nullptr) *outEvents = 0;
213             if (outData != nullptr) *outData = nullptr;
214             return result;
215         }
216 
217         result = pollInner(timeoutMillis);
218     }
219 }
220 
pollInner(int timeoutMillis)221 int Looper::pollInner(int timeoutMillis) {
222 #if DEBUG_POLL_AND_WAKE
223     ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
224 #endif
225 
226     // Adjust the timeout based on when the next message is due.
227     if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
228         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
229         int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
230         if (messageTimeoutMillis >= 0
231                 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
232             timeoutMillis = messageTimeoutMillis;
233         }
234 #if DEBUG_POLL_AND_WAKE
235         ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
236                 this, mNextMessageUptime - now, timeoutMillis);
237 #endif
238     }
239 
240     // Poll.
241     int result = POLL_WAKE;
242     mResponses.clear();
243     mResponseIndex = 0;
244 
245     // We are about to idle.
246     mPolling = true;
247 
248     struct epoll_event eventItems[EPOLL_MAX_EVENTS];
249     int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
250 
251     // No longer idling.
252     mPolling = false;
253 
254     // Acquire lock.
255     mLock.lock();
256 
257     // Rebuild epoll set if needed.
258     if (mEpollRebuildRequired) {
259         mEpollRebuildRequired = false;
260         rebuildEpollLocked();
261         goto Done;
262     }
263 
264     // Check for poll error.
265     if (eventCount < 0) {
266         if (errno == EINTR) {
267             goto Done;
268         }
269         ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
270         result = POLL_ERROR;
271         goto Done;
272     }
273 
274     // Check for poll timeout.
275     if (eventCount == 0) {
276 #if DEBUG_POLL_AND_WAKE
277         ALOGD("%p ~ pollOnce - timeout", this);
278 #endif
279         result = POLL_TIMEOUT;
280         goto Done;
281     }
282 
283     // Handle all events.
284 #if DEBUG_POLL_AND_WAKE
285     ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
286 #endif
287 
288     for (int i = 0; i < eventCount; i++) {
289         const SequenceNumber seq = eventItems[i].data.u64;
290         uint32_t epollEvents = eventItems[i].events;
291         if (seq == WAKE_EVENT_FD_SEQ) {
292             if (epollEvents & EPOLLIN) {
293                 awoken();
294             } else {
295                 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
296             }
297         } else {
298             const auto& request_it = mRequests.find(seq);
299             if (request_it != mRequests.end()) {
300                 const auto& request = request_it->second;
301                 int events = 0;
302                 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
303                 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
304                 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
305                 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
306                 mResponses.push({.seq = seq, .events = events, .request = request});
307             } else {
308                 ALOGW("Ignoring unexpected epoll events 0x%x for sequence number %" PRIu64
309                       " that is no longer registered.",
310                       epollEvents, seq);
311             }
312         }
313     }
314 Done: ;
315 
316     // Invoke pending message callbacks.
317     mNextMessageUptime = LLONG_MAX;
318     while (mMessageEnvelopes.size() != 0) {
319         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
320         const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
321         if (messageEnvelope.uptime <= now) {
322             // Remove the envelope from the list.
323             // We keep a strong reference to the handler until the call to handleMessage
324             // finishes.  Then we drop it so that the handler can be deleted *before*
325             // we reacquire our lock.
326             { // obtain handler
327                 sp<MessageHandler> handler = messageEnvelope.handler;
328                 Message message = messageEnvelope.message;
329                 mMessageEnvelopes.removeAt(0);
330                 mSendingMessage = true;
331                 mLock.unlock();
332 
333 #if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
334                 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
335                         this, handler.get(), message.what);
336 #endif
337                 handler->handleMessage(message);
338             } // release handler
339 
340             mLock.lock();
341             mSendingMessage = false;
342             result = POLL_CALLBACK;
343         } else {
344             // The last message left at the head of the queue determines the next wakeup time.
345             mNextMessageUptime = messageEnvelope.uptime;
346             break;
347         }
348     }
349 
350     // Release lock.
351     mLock.unlock();
352 
353     // Invoke all response callbacks.
354     for (size_t i = 0; i < mResponses.size(); i++) {
355         Response& response = mResponses.editItemAt(i);
356         if (response.request.ident == POLL_CALLBACK) {
357             int fd = response.request.fd;
358             int events = response.events;
359             void* data = response.request.data;
360 #if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
361             ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
362                     this, response.request.callback.get(), fd, events, data);
363 #endif
364             // Invoke the callback.  Note that the file descriptor may be closed by
365             // the callback (and potentially even reused) before the function returns so
366             // we need to be a little careful when removing the file descriptor afterwards.
367             int callbackResult = response.request.callback->handleEvent(fd, events, data);
368             if (callbackResult == 0) {
369                 AutoMutex _l(mLock);
370                 removeSequenceNumberLocked(response.seq);
371             }
372 
373             // Clear the callback reference in the response structure promptly because we
374             // will not clear the response vector itself until the next poll.
375             response.request.callback.clear();
376             result = POLL_CALLBACK;
377         }
378     }
379     return result;
380 }
381 
pollAll(int timeoutMillis,int * outFd,int * outEvents,void ** outData)382 int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
383     if (timeoutMillis <= 0) {
384         int result;
385         do {
386             result = pollOnce(timeoutMillis, outFd, outEvents, outData);
387         } while (result == POLL_CALLBACK);
388         return result;
389     } else {
390         nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
391                 + milliseconds_to_nanoseconds(timeoutMillis);
392 
393         for (;;) {
394             int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
395             if (result != POLL_CALLBACK) {
396                 return result;
397             }
398 
399             nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
400             timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
401             if (timeoutMillis == 0) {
402                 return POLL_TIMEOUT;
403             }
404         }
405     }
406 }
407 
wake()408 void Looper::wake() {
409 #if DEBUG_POLL_AND_WAKE
410     ALOGD("%p ~ wake", this);
411 #endif
412 
413     uint64_t inc = 1;
414     ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
415     if (nWrite != sizeof(uint64_t)) {
416         if (errno != EAGAIN) {
417             LOG_ALWAYS_FATAL("Could not write wake signal to fd %d (returned %zd): %s",
418                              mWakeEventFd.get(), nWrite, strerror(errno));
419         }
420     }
421 }
422 
awoken()423 void Looper::awoken() {
424 #if DEBUG_POLL_AND_WAKE
425     ALOGD("%p ~ awoken", this);
426 #endif
427 
428     uint64_t counter;
429     TEMP_FAILURE_RETRY(read(mWakeEventFd.get(), &counter, sizeof(uint64_t)));
430 }
431 
addFd(int fd,int ident,int events,Looper_callbackFunc callback,void * data)432 int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
433     sp<SimpleLooperCallback> looperCallback;
434     if (callback) {
435         looperCallback = sp<SimpleLooperCallback>::make(callback);
436     }
437     return addFd(fd, ident, events, looperCallback, data);
438 }
439 
addFd(int fd,int ident,int events,const sp<LooperCallback> & callback,void * data)440 int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
441 #if DEBUG_CALLBACKS
442     ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
443             events, callback.get(), data);
444 #endif
445 
446     if (!callback.get()) {
447         if (! mAllowNonCallbacks) {
448             ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
449             return -1;
450         }
451 
452         if (ident < 0) {
453             ALOGE("Invalid attempt to set NULL callback with ident < 0.");
454             return -1;
455         }
456     } else {
457         ident = POLL_CALLBACK;
458     }
459 
460     { // acquire lock
461         AutoMutex _l(mLock);
462         // There is a sequence number reserved for the WakeEventFd.
463         if (mNextRequestSeq == WAKE_EVENT_FD_SEQ) mNextRequestSeq++;
464         const SequenceNumber seq = mNextRequestSeq++;
465 
466         Request request;
467         request.fd = fd;
468         request.ident = ident;
469         request.events = events;
470         request.callback = callback;
471         request.data = data;
472 
473         epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
474         auto seq_it = mSequenceNumberByFd.find(fd);
475         if (seq_it == mSequenceNumberByFd.end()) {
476             int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
477             if (epollResult < 0) {
478                 ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
479                 return -1;
480             }
481             mRequests.emplace(seq, request);
482             mSequenceNumberByFd.emplace(fd, seq);
483         } else {
484             int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);
485             if (epollResult < 0) {
486                 if (errno == ENOENT) {
487                     // Tolerate ENOENT because it means that an older file descriptor was
488                     // closed before its callback was unregistered and meanwhile a new
489                     // file descriptor with the same number has been created and is now
490                     // being registered for the first time.  This error may occur naturally
491                     // when a callback has the side-effect of closing the file descriptor
492                     // before returning and unregistering itself.  Callback sequence number
493                     // checks further ensure that the race is benign.
494                     //
495                     // Unfortunately due to kernel limitations we need to rebuild the epoll
496                     // set from scratch because it may contain an old file handle that we are
497                     // now unable to remove since its file descriptor is no longer valid.
498                     // No such problem would have occurred if we were using the poll system
499                     // call instead, but that approach carries other disadvantages.
500 #if DEBUG_CALLBACKS
501                     ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
502                             "being recycled, falling back on EPOLL_CTL_ADD: %s",
503                             this, strerror(errno));
504 #endif
505                     epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
506                     if (epollResult < 0) {
507                         ALOGE("Error modifying or adding epoll events for fd %d: %s",
508                                 fd, strerror(errno));
509                         return -1;
510                     }
511                     scheduleEpollRebuildLocked();
512                 } else {
513                     ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
514                     return -1;
515                 }
516             }
517             const SequenceNumber oldSeq = seq_it->second;
518             mRequests.erase(oldSeq);
519             mRequests.emplace(seq, request);
520             seq_it->second = seq;
521         }
522     } // release lock
523     return 1;
524 }
525 
removeFd(int fd)526 int Looper::removeFd(int fd) {
527     AutoMutex _l(mLock);
528     const auto& it = mSequenceNumberByFd.find(fd);
529     if (it == mSequenceNumberByFd.end()) {
530         return 0;
531     }
532     return removeSequenceNumberLocked(it->second);
533 }
534 
removeSequenceNumberLocked(SequenceNumber seq)535 int Looper::removeSequenceNumberLocked(SequenceNumber seq) {
536 #if DEBUG_CALLBACKS
537     ALOGD("%p ~ removeFd - fd=%d, seq=%u", this, fd, seq);
538 #endif
539 
540     const auto& request_it = mRequests.find(seq);
541     if (request_it == mRequests.end()) {
542         return 0;
543     }
544     const int fd = request_it->second.fd;
545 
546     // Always remove the FD from the request map even if an error occurs while
547     // updating the epoll set so that we avoid accidentally leaking callbacks.
548     mRequests.erase(request_it);
549     mSequenceNumberByFd.erase(fd);
550 
551     int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_DEL, fd, nullptr);
552     if (epollResult < 0) {
553         if (errno == EBADF || errno == ENOENT) {
554             // Tolerate EBADF or ENOENT because it means that the file descriptor was closed
555             // before its callback was unregistered. This error may occur naturally when a
556             // callback has the side-effect of closing the file descriptor before returning and
557             // unregistering itself.
558             //
559             // Unfortunately due to kernel limitations we need to rebuild the epoll
560             // set from scratch because it may contain an old file handle that we are
561             // now unable to remove since its file descriptor is no longer valid.
562             // No such problem would have occurred if we were using the poll system
563             // call instead, but that approach carries other disadvantages.
564 #if DEBUG_CALLBACKS
565             ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
566                   "being closed: %s",
567                   this, strerror(errno));
568 #endif
569             scheduleEpollRebuildLocked();
570         } else {
571             // Some other error occurred.  This is really weird because it means
572             // our list of callbacks got out of sync with the epoll set somehow.
573             // We defensively rebuild the epoll set to avoid getting spurious
574             // notifications with nowhere to go.
575             ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
576             scheduleEpollRebuildLocked();
577             return -1;
578         }
579     }
580     return 1;
581 }
582 
sendMessage(const sp<MessageHandler> & handler,const Message & message)583 void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
584     nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
585     sendMessageAtTime(now, handler, message);
586 }
587 
sendMessageDelayed(nsecs_t uptimeDelay,const sp<MessageHandler> & handler,const Message & message)588 void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
589         const Message& message) {
590     nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
591     sendMessageAtTime(now + uptimeDelay, handler, message);
592 }
593 
sendMessageAtTime(nsecs_t uptime,const sp<MessageHandler> & handler,const Message & message)594 void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
595         const Message& message) {
596 #if DEBUG_CALLBACKS
597     ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
598             this, uptime, handler.get(), message.what);
599 #endif
600 
601     size_t i = 0;
602     { // acquire lock
603         AutoMutex _l(mLock);
604 
605         size_t messageCount = mMessageEnvelopes.size();
606         while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
607             i += 1;
608         }
609 
610         MessageEnvelope messageEnvelope(uptime, handler, message);
611         mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
612 
613         // Optimization: If the Looper is currently sending a message, then we can skip
614         // the call to wake() because the next thing the Looper will do after processing
615         // messages is to decide when the next wakeup time should be.  In fact, it does
616         // not even matter whether this code is running on the Looper thread.
617         if (mSendingMessage) {
618             return;
619         }
620     } // release lock
621 
622     // Wake the poll loop only when we enqueue a new message at the head.
623     if (i == 0) {
624         wake();
625     }
626 }
627 
removeMessages(const sp<MessageHandler> & handler)628 void Looper::removeMessages(const sp<MessageHandler>& handler) {
629 #if DEBUG_CALLBACKS
630     ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
631 #endif
632 
633     { // acquire lock
634         AutoMutex _l(mLock);
635 
636         for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
637             const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
638             if (messageEnvelope.handler == handler) {
639                 mMessageEnvelopes.removeAt(i);
640             }
641         }
642     } // release lock
643 }
644 
removeMessages(const sp<MessageHandler> & handler,int what)645 void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
646 #if DEBUG_CALLBACKS
647     ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
648 #endif
649 
650     { // acquire lock
651         AutoMutex _l(mLock);
652 
653         for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
654             const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
655             if (messageEnvelope.handler == handler
656                     && messageEnvelope.message.what == what) {
657                 mMessageEnvelopes.removeAt(i);
658             }
659         }
660     } // release lock
661 }
662 
isPolling() const663 bool Looper::isPolling() const {
664     return mPolling;
665 }
666 
getEpollEvents() const667 uint32_t Looper::Request::getEpollEvents() const {
668     uint32_t epollEvents = 0;
669     if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
670     if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
671     return epollEvents;
672 }
673 
~MessageHandler()674 MessageHandler::~MessageHandler() { }
675 
~LooperCallback()676 LooperCallback::~LooperCallback() { }
677 
678 } // namespace android
679