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