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 #define LOG_TAG "InputDispatcher"
18 #define ATRACE_TAG ATRACE_TAG_INPUT
19 
20 #define LOG_NDEBUG 0
21 
22 // Log detailed debug messages about each inbound event notification to the dispatcher.
23 #define DEBUG_INBOUND_EVENT_DETAILS 0
24 
25 // Log detailed debug messages about each outbound event processed by the dispatcher.
26 #define DEBUG_OUTBOUND_EVENT_DETAILS 0
27 
28 // Log debug messages about the dispatch cycle.
29 #define DEBUG_DISPATCH_CYCLE 0
30 
31 // Log debug messages about registrations.
32 #define DEBUG_REGISTRATION 0
33 
34 // Log debug messages about input event injection.
35 #define DEBUG_INJECTION 0
36 
37 // Log debug messages about input focus tracking.
38 #define DEBUG_FOCUS 0
39 
40 // Log debug messages about the app switch latency optimization.
41 #define DEBUG_APP_SWITCH 0
42 
43 // Log debug messages about hover events.
44 #define DEBUG_HOVER 0
45 
46 #include "InputDispatcher.h"
47 
48 #include "Connection.h"
49 
50 #include <errno.h>
51 #include <inttypes.h>
52 #include <limits.h>
53 #include <stddef.h>
54 #include <time.h>
55 #include <unistd.h>
56 #include <sstream>
57 
58 #include <android-base/chrono_utils.h>
59 #include <android-base/stringprintf.h>
60 #include <binder/Binder.h>
61 #include <log/log.h>
62 #include <powermanager/PowerManager.h>
63 #include <utils/Trace.h>
64 
65 #define INDENT "  "
66 #define INDENT2 "    "
67 #define INDENT3 "      "
68 #define INDENT4 "        "
69 
70 using android::base::StringPrintf;
71 
72 namespace android::inputdispatcher {
73 
74 // Default input dispatching timeout if there is no focused application or paused window
75 // from which to determine an appropriate dispatching timeout.
76 constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
77 
78 // Amount of time to allow for all pending events to be processed when an app switch
79 // key is on the way.  This is used to preempt input dispatch and drop input events
80 // when an application takes too long to respond and the user has pressed an app switch key.
81 constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
82 
83 // Amount of time to allow for an event to be dispatched (measured since its eventTime)
84 // before considering it stale and dropping it.
85 constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
86 
87 // Amount of time to allow touch events to be streamed out to a connection before requiring
88 // that the first event be finished.  This value extends the ANR timeout by the specified
89 // amount.  For example, if streaming is allowed to get ahead by one second relative to the
90 // queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
91 constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
92 
93 // Log a warning when an event takes longer than this to process, even if an ANR does not occur.
94 constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
95 
96 // Log a warning when an interception call takes longer than this to process.
97 constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
98 
99 // Number of recent events to keep for debugging purposes.
100 constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
101 
now()102 static inline nsecs_t now() {
103     return systemTime(SYSTEM_TIME_MONOTONIC);
104 }
105 
toString(bool value)106 static inline const char* toString(bool value) {
107     return value ? "true" : "false";
108 }
109 
getMotionEventActionPointerIndex(int32_t action)110 static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
111     return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
112             AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
113 }
114 
isValidKeyAction(int32_t action)115 static bool isValidKeyAction(int32_t action) {
116     switch (action) {
117         case AKEY_EVENT_ACTION_DOWN:
118         case AKEY_EVENT_ACTION_UP:
119             return true;
120         default:
121             return false;
122     }
123 }
124 
validateKeyEvent(int32_t action)125 static bool validateKeyEvent(int32_t action) {
126     if (!isValidKeyAction(action)) {
127         ALOGE("Key event has invalid action code 0x%x", action);
128         return false;
129     }
130     return true;
131 }
132 
isValidMotionAction(int32_t action,int32_t actionButton,int32_t pointerCount)133 static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
134     switch (action & AMOTION_EVENT_ACTION_MASK) {
135         case AMOTION_EVENT_ACTION_DOWN:
136         case AMOTION_EVENT_ACTION_UP:
137         case AMOTION_EVENT_ACTION_CANCEL:
138         case AMOTION_EVENT_ACTION_MOVE:
139         case AMOTION_EVENT_ACTION_OUTSIDE:
140         case AMOTION_EVENT_ACTION_HOVER_ENTER:
141         case AMOTION_EVENT_ACTION_HOVER_MOVE:
142         case AMOTION_EVENT_ACTION_HOVER_EXIT:
143         case AMOTION_EVENT_ACTION_SCROLL:
144             return true;
145         case AMOTION_EVENT_ACTION_POINTER_DOWN:
146         case AMOTION_EVENT_ACTION_POINTER_UP: {
147             int32_t index = getMotionEventActionPointerIndex(action);
148             return index >= 0 && index < pointerCount;
149         }
150         case AMOTION_EVENT_ACTION_BUTTON_PRESS:
151         case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
152             return actionButton != 0;
153         default:
154             return false;
155     }
156 }
157 
validateMotionEvent(int32_t action,int32_t actionButton,size_t pointerCount,const PointerProperties * pointerProperties)158 static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
159                                 const PointerProperties* pointerProperties) {
160     if (!isValidMotionAction(action, actionButton, pointerCount)) {
161         ALOGE("Motion event has invalid action code 0x%x", action);
162         return false;
163     }
164     if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
165         ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
166               pointerCount, MAX_POINTERS);
167         return false;
168     }
169     BitSet32 pointerIdBits;
170     for (size_t i = 0; i < pointerCount; i++) {
171         int32_t id = pointerProperties[i].id;
172         if (id < 0 || id > MAX_POINTER_ID) {
173             ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
174                   MAX_POINTER_ID);
175             return false;
176         }
177         if (pointerIdBits.hasBit(id)) {
178             ALOGE("Motion event has duplicate pointer id %d", id);
179             return false;
180         }
181         pointerIdBits.markBit(id);
182     }
183     return true;
184 }
185 
dumpRegion(std::string & dump,const Region & region)186 static void dumpRegion(std::string& dump, const Region& region) {
187     if (region.isEmpty()) {
188         dump += "<empty>";
189         return;
190     }
191 
192     bool first = true;
193     Region::const_iterator cur = region.begin();
194     Region::const_iterator const tail = region.end();
195     while (cur != tail) {
196         if (first) {
197             first = false;
198         } else {
199             dump += "|";
200         }
201         dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
202         cur++;
203     }
204 }
205 
206 template <typename T, typename U>
getValueByKey(std::unordered_map<U,T> & map,U key)207 static T getValueByKey(std::unordered_map<U, T>& map, U key) {
208     typename std::unordered_map<U, T>::const_iterator it = map.find(key);
209     return it != map.end() ? it->second : T{};
210 }
211 
212 // --- InputDispatcher ---
213 
InputDispatcher(const sp<InputDispatcherPolicyInterface> & policy)214 InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
215       : mPolicy(policy),
216         mPendingEvent(nullptr),
217         mLastDropReason(DROP_REASON_NOT_DROPPED),
218         mAppSwitchSawKeyDown(false),
219         mAppSwitchDueTime(LONG_LONG_MAX),
220         mNextUnblockedEvent(nullptr),
221         mDispatchEnabled(false),
222         mDispatchFrozen(false),
223         mInputFilterEnabled(false),
224         mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
225         mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
226     mLooper = new Looper(false);
227     mReporter = createInputReporter();
228 
229     mKeyRepeatState.lastKeyEntry = nullptr;
230 
231     policy->getDispatcherConfiguration(&mConfig);
232 }
233 
~InputDispatcher()234 InputDispatcher::~InputDispatcher() {
235     { // acquire lock
236         std::scoped_lock _l(mLock);
237 
238         resetKeyRepeatLocked();
239         releasePendingEventLocked();
240         drainInboundQueueLocked();
241     }
242 
243     while (mConnectionsByFd.size() != 0) {
244         unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
245     }
246 }
247 
dispatchOnce()248 void InputDispatcher::dispatchOnce() {
249     nsecs_t nextWakeupTime = LONG_LONG_MAX;
250     { // acquire lock
251         std::scoped_lock _l(mLock);
252         mDispatcherIsAlive.notify_all();
253 
254         // Run a dispatch loop if there are no pending commands.
255         // The dispatch loop might enqueue commands to run afterwards.
256         if (!haveCommandsLocked()) {
257             dispatchOnceInnerLocked(&nextWakeupTime);
258         }
259 
260         // Run all pending commands if there are any.
261         // If any commands were run then force the next poll to wake up immediately.
262         if (runCommandsLockedInterruptible()) {
263             nextWakeupTime = LONG_LONG_MIN;
264         }
265     } // release lock
266 
267     // Wait for callback or timeout or wake.  (make sure we round up, not down)
268     nsecs_t currentTime = now();
269     int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
270     mLooper->pollOnce(timeoutMillis);
271 }
272 
dispatchOnceInnerLocked(nsecs_t * nextWakeupTime)273 void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
274     nsecs_t currentTime = now();
275 
276     // Reset the key repeat timer whenever normal dispatch is suspended while the
277     // device is in a non-interactive state.  This is to ensure that we abort a key
278     // repeat if the device is just coming out of sleep.
279     if (!mDispatchEnabled) {
280         resetKeyRepeatLocked();
281     }
282 
283     // If dispatching is frozen, do not process timeouts or try to deliver any new events.
284     if (mDispatchFrozen) {
285 #if DEBUG_FOCUS
286         ALOGD("Dispatch frozen.  Waiting some more.");
287 #endif
288         return;
289     }
290 
291     // Optimize latency of app switches.
292     // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
293     // been pressed.  When it expires, we preempt dispatch and drop all other pending events.
294     bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
295     if (mAppSwitchDueTime < *nextWakeupTime) {
296         *nextWakeupTime = mAppSwitchDueTime;
297     }
298 
299     // Ready to start a new event.
300     // If we don't already have a pending event, go grab one.
301     if (!mPendingEvent) {
302         if (mInboundQueue.isEmpty()) {
303             if (isAppSwitchDue) {
304                 // The inbound queue is empty so the app switch key we were waiting
305                 // for will never arrive.  Stop waiting for it.
306                 resetPendingAppSwitchLocked(false);
307                 isAppSwitchDue = false;
308             }
309 
310             // Synthesize a key repeat if appropriate.
311             if (mKeyRepeatState.lastKeyEntry) {
312                 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
313                     mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
314                 } else {
315                     if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
316                         *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
317                     }
318                 }
319             }
320 
321             // Nothing to do if there is no pending event.
322             if (!mPendingEvent) {
323                 return;
324             }
325         } else {
326             // Inbound queue has at least one entry.
327             mPendingEvent = mInboundQueue.dequeueAtHead();
328             traceInboundQueueLengthLocked();
329         }
330 
331         // Poke user activity for this event.
332         if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
333             pokeUserActivityLocked(mPendingEvent);
334         }
335 
336         // Get ready to dispatch the event.
337         resetANRTimeoutsLocked();
338     }
339 
340     // Now we have an event to dispatch.
341     // All events are eventually dequeued and processed this way, even if we intend to drop them.
342     ALOG_ASSERT(mPendingEvent != nullptr);
343     bool done = false;
344     DropReason dropReason = DROP_REASON_NOT_DROPPED;
345     if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
346         dropReason = DROP_REASON_POLICY;
347     } else if (!mDispatchEnabled) {
348         dropReason = DROP_REASON_DISABLED;
349     }
350 
351     if (mNextUnblockedEvent == mPendingEvent) {
352         mNextUnblockedEvent = nullptr;
353     }
354 
355     switch (mPendingEvent->type) {
356         case EventEntry::TYPE_CONFIGURATION_CHANGED: {
357             ConfigurationChangedEntry* typedEntry =
358                     static_cast<ConfigurationChangedEntry*>(mPendingEvent);
359             done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
360             dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
361             break;
362         }
363 
364         case EventEntry::TYPE_DEVICE_RESET: {
365             DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
366             done = dispatchDeviceResetLocked(currentTime, typedEntry);
367             dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
368             break;
369         }
370 
371         case EventEntry::TYPE_KEY: {
372             KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
373             if (isAppSwitchDue) {
374                 if (isAppSwitchKeyEvent(typedEntry)) {
375                     resetPendingAppSwitchLocked(true);
376                     isAppSwitchDue = false;
377                 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
378                     dropReason = DROP_REASON_APP_SWITCH;
379                 }
380             }
381             if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
382                 dropReason = DROP_REASON_STALE;
383             }
384             if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
385                 dropReason = DROP_REASON_BLOCKED;
386             }
387             done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
388             break;
389         }
390 
391         case EventEntry::TYPE_MOTION: {
392             MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
393             if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
394                 dropReason = DROP_REASON_APP_SWITCH;
395             }
396             if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
397                 dropReason = DROP_REASON_STALE;
398             }
399             if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
400                 dropReason = DROP_REASON_BLOCKED;
401             }
402             done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
403             break;
404         }
405 
406         default:
407             ALOG_ASSERT(false);
408             break;
409     }
410 
411     if (done) {
412         if (dropReason != DROP_REASON_NOT_DROPPED) {
413             dropInboundEventLocked(mPendingEvent, dropReason);
414         }
415         mLastDropReason = dropReason;
416 
417         releasePendingEventLocked();
418         *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
419     }
420 }
421 
enqueueInboundEventLocked(EventEntry * entry)422 bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
423     bool needWake = mInboundQueue.isEmpty();
424     mInboundQueue.enqueueAtTail(entry);
425     traceInboundQueueLengthLocked();
426 
427     switch (entry->type) {
428         case EventEntry::TYPE_KEY: {
429             // Optimize app switch latency.
430             // If the application takes too long to catch up then we drop all events preceding
431             // the app switch key.
432             KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
433             if (isAppSwitchKeyEvent(keyEntry)) {
434                 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
435                     mAppSwitchSawKeyDown = true;
436                 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
437                     if (mAppSwitchSawKeyDown) {
438 #if DEBUG_APP_SWITCH
439                         ALOGD("App switch is pending!");
440 #endif
441                         mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
442                         mAppSwitchSawKeyDown = false;
443                         needWake = true;
444                     }
445                 }
446             }
447             break;
448         }
449 
450         case EventEntry::TYPE_MOTION: {
451             // Optimize case where the current application is unresponsive and the user
452             // decides to touch a window in a different application.
453             // If the application takes too long to catch up then we drop all events preceding
454             // the touch into the other window.
455             MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
456             if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
457                 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
458                 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
459                 mInputTargetWaitApplicationToken != nullptr) {
460                 int32_t displayId = motionEntry->displayId;
461                 int32_t x =
462                         int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
463                 int32_t y =
464                         int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
465                 sp<InputWindowHandle> touchedWindowHandle =
466                         findTouchedWindowAtLocked(displayId, x, y);
467                 if (touchedWindowHandle != nullptr &&
468                     touchedWindowHandle->getApplicationToken() !=
469                             mInputTargetWaitApplicationToken) {
470                     // User touched a different application than the one we are waiting on.
471                     // Flag the event, and start pruning the input queue.
472                     mNextUnblockedEvent = motionEntry;
473                     needWake = true;
474                 }
475             }
476             break;
477         }
478     }
479 
480     return needWake;
481 }
482 
addRecentEventLocked(EventEntry * entry)483 void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
484     entry->refCount += 1;
485     mRecentQueue.enqueueAtTail(entry);
486     if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
487         mRecentQueue.dequeueAtHead()->release();
488     }
489 }
490 
findTouchedWindowAtLocked(int32_t displayId,int32_t x,int32_t y,bool addOutsideTargets,bool addPortalWindows)491 sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
492                                                                  int32_t y, bool addOutsideTargets,
493                                                                  bool addPortalWindows) {
494     // Traverse windows from front to back to find touched window.
495     const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
496     for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
497         const InputWindowInfo* windowInfo = windowHandle->getInfo();
498         if (windowInfo->displayId == displayId) {
499             int32_t flags = windowInfo->layoutParamsFlags;
500 
501             if (windowInfo->visible) {
502                 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
503                     bool isTouchModal = (flags &
504                                          (InputWindowInfo::FLAG_NOT_FOCUSABLE |
505                                           InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
506                     if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
507                         int32_t portalToDisplayId = windowInfo->portalToDisplayId;
508                         if (portalToDisplayId != ADISPLAY_ID_NONE &&
509                             portalToDisplayId != displayId) {
510                             if (addPortalWindows) {
511                                 // For the monitoring channels of the display.
512                                 mTempTouchState.addPortalWindow(windowHandle);
513                             }
514                             return findTouchedWindowAtLocked(portalToDisplayId, x, y,
515                                                              addOutsideTargets, addPortalWindows);
516                         }
517                         // Found window.
518                         return windowHandle;
519                     }
520                 }
521 
522                 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
523                     mTempTouchState.addOrUpdateWindow(windowHandle,
524                                                       InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
525                                                       BitSet32(0));
526                 }
527             }
528         }
529     }
530     return nullptr;
531 }
532 
findTouchedGestureMonitorsLocked(int32_t displayId,const std::vector<sp<InputWindowHandle>> & portalWindows)533 std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
534         int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
535     std::vector<TouchedMonitor> touchedMonitors;
536 
537     std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
538     addGestureMonitors(monitors, touchedMonitors);
539     for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
540         const InputWindowInfo* windowInfo = portalWindow->getInfo();
541         monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
542         addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
543                            -windowInfo->frameTop);
544     }
545     return touchedMonitors;
546 }
547 
addGestureMonitors(const std::vector<Monitor> & monitors,std::vector<TouchedMonitor> & outTouchedMonitors,float xOffset,float yOffset)548 void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
549                                          std::vector<TouchedMonitor>& outTouchedMonitors,
550                                          float xOffset, float yOffset) {
551     if (monitors.empty()) {
552         return;
553     }
554     outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
555     for (const Monitor& monitor : monitors) {
556         outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
557     }
558 }
559 
dropInboundEventLocked(EventEntry * entry,DropReason dropReason)560 void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
561     const char* reason;
562     switch (dropReason) {
563         case DROP_REASON_POLICY:
564 #if DEBUG_INBOUND_EVENT_DETAILS
565             ALOGD("Dropped event because policy consumed it.");
566 #endif
567             reason = "inbound event was dropped because the policy consumed it";
568             break;
569         case DROP_REASON_DISABLED:
570             if (mLastDropReason != DROP_REASON_DISABLED) {
571                 ALOGI("Dropped event because input dispatch is disabled.");
572             }
573             reason = "inbound event was dropped because input dispatch is disabled";
574             break;
575         case DROP_REASON_APP_SWITCH:
576             ALOGI("Dropped event because of pending overdue app switch.");
577             reason = "inbound event was dropped because of pending overdue app switch";
578             break;
579         case DROP_REASON_BLOCKED:
580             ALOGI("Dropped event because the current application is not responding and the user "
581                   "has started interacting with a different application.");
582             reason = "inbound event was dropped because the current application is not responding "
583                      "and the user has started interacting with a different application";
584             break;
585         case DROP_REASON_STALE:
586             ALOGI("Dropped event because it is stale.");
587             reason = "inbound event was dropped because it is stale";
588             break;
589         default:
590             ALOG_ASSERT(false);
591             return;
592     }
593 
594     switch (entry->type) {
595         case EventEntry::TYPE_KEY: {
596             CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
597             synthesizeCancelationEventsForAllConnectionsLocked(options);
598             break;
599         }
600         case EventEntry::TYPE_MOTION: {
601             MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
602             if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
603                 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
604                 synthesizeCancelationEventsForAllConnectionsLocked(options);
605             } else {
606                 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
607                 synthesizeCancelationEventsForAllConnectionsLocked(options);
608             }
609             break;
610         }
611     }
612 }
613 
isAppSwitchKeyCode(int32_t keyCode)614 static bool isAppSwitchKeyCode(int32_t keyCode) {
615     return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
616             keyCode == AKEYCODE_APP_SWITCH;
617 }
618 
isAppSwitchKeyEvent(KeyEntry * keyEntry)619 bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
620     return !(keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry->keyCode) &&
621             (keyEntry->policyFlags & POLICY_FLAG_TRUSTED) &&
622             (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
623 }
624 
isAppSwitchPendingLocked()625 bool InputDispatcher::isAppSwitchPendingLocked() {
626     return mAppSwitchDueTime != LONG_LONG_MAX;
627 }
628 
resetPendingAppSwitchLocked(bool handled)629 void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
630     mAppSwitchDueTime = LONG_LONG_MAX;
631 
632 #if DEBUG_APP_SWITCH
633     if (handled) {
634         ALOGD("App switch has arrived.");
635     } else {
636         ALOGD("App switch was abandoned.");
637     }
638 #endif
639 }
640 
isStaleEvent(nsecs_t currentTime,EventEntry * entry)641 bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
642     return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
643 }
644 
haveCommandsLocked() const645 bool InputDispatcher::haveCommandsLocked() const {
646     return !mCommandQueue.isEmpty();
647 }
648 
runCommandsLockedInterruptible()649 bool InputDispatcher::runCommandsLockedInterruptible() {
650     if (mCommandQueue.isEmpty()) {
651         return false;
652     }
653 
654     do {
655         CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
656 
657         Command command = commandEntry->command;
658         (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
659 
660         commandEntry->connection.clear();
661         delete commandEntry;
662     } while (!mCommandQueue.isEmpty());
663     return true;
664 }
665 
postCommandLocked(Command command)666 CommandEntry* InputDispatcher::postCommandLocked(Command command) {
667     CommandEntry* commandEntry = new CommandEntry(command);
668     mCommandQueue.enqueueAtTail(commandEntry);
669     return commandEntry;
670 }
671 
drainInboundQueueLocked()672 void InputDispatcher::drainInboundQueueLocked() {
673     while (!mInboundQueue.isEmpty()) {
674         EventEntry* entry = mInboundQueue.dequeueAtHead();
675         releaseInboundEventLocked(entry);
676     }
677     traceInboundQueueLengthLocked();
678 }
679 
releasePendingEventLocked()680 void InputDispatcher::releasePendingEventLocked() {
681     if (mPendingEvent) {
682         resetANRTimeoutsLocked();
683         releaseInboundEventLocked(mPendingEvent);
684         mPendingEvent = nullptr;
685     }
686 }
687 
releaseInboundEventLocked(EventEntry * entry)688 void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
689     InjectionState* injectionState = entry->injectionState;
690     if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
691 #if DEBUG_DISPATCH_CYCLE
692         ALOGD("Injected inbound event was dropped.");
693 #endif
694         setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
695     }
696     if (entry == mNextUnblockedEvent) {
697         mNextUnblockedEvent = nullptr;
698     }
699     addRecentEventLocked(entry);
700     entry->release();
701 }
702 
resetKeyRepeatLocked()703 void InputDispatcher::resetKeyRepeatLocked() {
704     if (mKeyRepeatState.lastKeyEntry) {
705         mKeyRepeatState.lastKeyEntry->release();
706         mKeyRepeatState.lastKeyEntry = nullptr;
707     }
708 }
709 
synthesizeKeyRepeatLocked(nsecs_t currentTime)710 KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
711     KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
712 
713     // Reuse the repeated key entry if it is otherwise unreferenced.
714     uint32_t policyFlags = entry->policyFlags &
715             (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
716     if (entry->refCount == 1) {
717         entry->recycle();
718         entry->eventTime = currentTime;
719         entry->policyFlags = policyFlags;
720         entry->repeatCount += 1;
721     } else {
722         KeyEntry* newEntry =
723                 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
724                              entry->source, entry->displayId, policyFlags, entry->action,
725                              entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
726                              entry->repeatCount + 1, entry->downTime);
727 
728         mKeyRepeatState.lastKeyEntry = newEntry;
729         entry->release();
730 
731         entry = newEntry;
732     }
733     entry->syntheticRepeat = true;
734 
735     // Increment reference count since we keep a reference to the event in
736     // mKeyRepeatState.lastKeyEntry in addition to the one we return.
737     entry->refCount += 1;
738 
739     mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
740     return entry;
741 }
742 
dispatchConfigurationChangedLocked(nsecs_t currentTime,ConfigurationChangedEntry * entry)743 bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
744                                                          ConfigurationChangedEntry* entry) {
745 #if DEBUG_OUTBOUND_EVENT_DETAILS
746     ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
747 #endif
748 
749     // Reset key repeating in case a keyboard device was added or removed or something.
750     resetKeyRepeatLocked();
751 
752     // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
753     CommandEntry* commandEntry =
754             postCommandLocked(&InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
755     commandEntry->eventTime = entry->eventTime;
756     return true;
757 }
758 
dispatchDeviceResetLocked(nsecs_t currentTime,DeviceResetEntry * entry)759 bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
760 #if DEBUG_OUTBOUND_EVENT_DETAILS
761     ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
762           entry->deviceId);
763 #endif
764 
765     CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
766     options.deviceId = entry->deviceId;
767     synthesizeCancelationEventsForAllConnectionsLocked(options);
768     return true;
769 }
770 
dispatchKeyLocked(nsecs_t currentTime,KeyEntry * entry,DropReason * dropReason,nsecs_t * nextWakeupTime)771 bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
772                                         DropReason* dropReason, nsecs_t* nextWakeupTime) {
773     // Preprocessing.
774     if (!entry->dispatchInProgress) {
775         if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
776             (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
777             (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
778             if (mKeyRepeatState.lastKeyEntry &&
779                 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
780                 // We have seen two identical key downs in a row which indicates that the device
781                 // driver is automatically generating key repeats itself.  We take note of the
782                 // repeat here, but we disable our own next key repeat timer since it is clear that
783                 // we will not need to synthesize key repeats ourselves.
784                 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
785                 resetKeyRepeatLocked();
786                 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
787             } else {
788                 // Not a repeat.  Save key down state in case we do see a repeat later.
789                 resetKeyRepeatLocked();
790                 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
791             }
792             mKeyRepeatState.lastKeyEntry = entry;
793             entry->refCount += 1;
794         } else if (!entry->syntheticRepeat) {
795             resetKeyRepeatLocked();
796         }
797 
798         if (entry->repeatCount == 1) {
799             entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
800         } else {
801             entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
802         }
803 
804         entry->dispatchInProgress = true;
805 
806         logOutboundKeyDetails("dispatchKey - ", entry);
807     }
808 
809     // Handle case where the policy asked us to try again later last time.
810     if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
811         if (currentTime < entry->interceptKeyWakeupTime) {
812             if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
813                 *nextWakeupTime = entry->interceptKeyWakeupTime;
814             }
815             return false; // wait until next wakeup
816         }
817         entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
818         entry->interceptKeyWakeupTime = 0;
819     }
820 
821     // Give the policy a chance to intercept the key.
822     if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
823         if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
824             CommandEntry* commandEntry = postCommandLocked(
825                     &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
826             sp<InputWindowHandle> focusedWindowHandle =
827                     getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
828             if (focusedWindowHandle != nullptr) {
829                 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
830             }
831             commandEntry->keyEntry = entry;
832             entry->refCount += 1;
833             return false; // wait for the command to run
834         } else {
835             entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
836         }
837     } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
838         if (*dropReason == DROP_REASON_NOT_DROPPED) {
839             *dropReason = DROP_REASON_POLICY;
840         }
841     }
842 
843     // Clean up if dropping the event.
844     if (*dropReason != DROP_REASON_NOT_DROPPED) {
845         setInjectionResult(entry,
846                            *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
847                                                              : INPUT_EVENT_INJECTION_FAILED);
848         mReporter->reportDroppedKey(entry->sequenceNum);
849         return true;
850     }
851 
852     // Identify targets.
853     std::vector<InputTarget> inputTargets;
854     int32_t injectionResult =
855             findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
856     if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
857         return false;
858     }
859 
860     setInjectionResult(entry, injectionResult);
861     if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
862         return true;
863     }
864 
865     // Add monitor channels from event's or focused display.
866     addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
867 
868     // Dispatch the key.
869     dispatchEventLocked(currentTime, entry, inputTargets);
870     return true;
871 }
872 
logOutboundKeyDetails(const char * prefix,const KeyEntry * entry)873 void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
874 #if DEBUG_OUTBOUND_EVENT_DETAILS
875     ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
876           "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
877           "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
878           prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
879           entry->policyFlags, entry->action, entry->flags, entry->keyCode, entry->scanCode,
880           entry->metaState, entry->repeatCount, entry->downTime);
881 #endif
882 }
883 
dispatchMotionLocked(nsecs_t currentTime,MotionEntry * entry,DropReason * dropReason,nsecs_t * nextWakeupTime)884 bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
885                                            DropReason* dropReason, nsecs_t* nextWakeupTime) {
886     ATRACE_CALL();
887     // Preprocessing.
888     if (!entry->dispatchInProgress) {
889         entry->dispatchInProgress = true;
890 
891         logOutboundMotionDetails("dispatchMotion - ", entry);
892     }
893 
894     // Clean up if dropping the event.
895     if (*dropReason != DROP_REASON_NOT_DROPPED) {
896         setInjectionResult(entry,
897                            *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
898                                                              : INPUT_EVENT_INJECTION_FAILED);
899         return true;
900     }
901 
902     bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
903 
904     // Identify targets.
905     std::vector<InputTarget> inputTargets;
906 
907     bool conflictingPointerActions = false;
908     int32_t injectionResult;
909     if (isPointerEvent) {
910         // Pointer event.  (eg. touchscreen)
911         injectionResult =
912                 findTouchedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime,
913                                                &conflictingPointerActions);
914     } else {
915         // Non touch event.  (eg. trackball)
916         injectionResult =
917                 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
918     }
919     if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
920         return false;
921     }
922 
923     setInjectionResult(entry, injectionResult);
924     if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
925         if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
926             CancelationOptions::Mode mode(isPointerEvent
927                                                   ? CancelationOptions::CANCEL_POINTER_EVENTS
928                                                   : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
929             CancelationOptions options(mode, "input event injection failed");
930             synthesizeCancelationEventsForMonitorsLocked(options);
931         }
932         return true;
933     }
934 
935     // Add monitor channels from event's or focused display.
936     addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
937 
938     if (isPointerEvent) {
939         ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
940         if (stateIndex >= 0) {
941             const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
942             if (!state.portalWindows.empty()) {
943                 // The event has gone through these portal windows, so we add monitoring targets of
944                 // the corresponding displays as well.
945                 for (size_t i = 0; i < state.portalWindows.size(); i++) {
946                     const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
947                     addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
948                                                      -windowInfo->frameLeft, -windowInfo->frameTop);
949                 }
950             }
951         }
952     }
953 
954     // Dispatch the motion.
955     if (conflictingPointerActions) {
956         CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
957                                    "conflicting pointer actions");
958         synthesizeCancelationEventsForAllConnectionsLocked(options);
959     }
960     dispatchEventLocked(currentTime, entry, inputTargets);
961     return true;
962 }
963 
logOutboundMotionDetails(const char * prefix,const MotionEntry * entry)964 void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
965 #if DEBUG_OUTBOUND_EVENT_DETAILS
966     ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
967           ", policyFlags=0x%x, "
968           "action=0x%x, actionButton=0x%x, flags=0x%x, "
969           "metaState=0x%x, buttonState=0x%x,"
970           "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
971           prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
972           entry->policyFlags, entry->action, entry->actionButton, entry->flags, entry->metaState,
973           entry->buttonState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
974           entry->downTime);
975 
976     for (uint32_t i = 0; i < entry->pointerCount; i++) {
977         ALOGD("  Pointer %d: id=%d, toolType=%d, "
978               "x=%f, y=%f, pressure=%f, size=%f, "
979               "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
980               "orientation=%f",
981               i, entry->pointerProperties[i].id, entry->pointerProperties[i].toolType,
982               entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
983               entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
984               entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
985               entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
986               entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
987               entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
988               entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
989               entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
990               entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
991     }
992 #endif
993 }
994 
dispatchEventLocked(nsecs_t currentTime,EventEntry * eventEntry,const std::vector<InputTarget> & inputTargets)995 void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
996                                           const std::vector<InputTarget>& inputTargets) {
997     ATRACE_CALL();
998 #if DEBUG_DISPATCH_CYCLE
999     ALOGD("dispatchEventToCurrentInputTargets");
1000 #endif
1001 
1002     ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1003 
1004     pokeUserActivityLocked(eventEntry);
1005 
1006     for (const InputTarget& inputTarget : inputTargets) {
1007         ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1008         if (connectionIndex >= 0) {
1009             sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1010             prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1011         } else {
1012 #if DEBUG_FOCUS
1013             ALOGD("Dropping event delivery to target with channel '%s' because it "
1014                   "is no longer registered with the input dispatcher.",
1015                   inputTarget.inputChannel->getName().c_str());
1016 #endif
1017         }
1018     }
1019 }
1020 
handleTargetsNotReadyLocked(nsecs_t currentTime,const EventEntry * entry,const sp<InputApplicationHandle> & applicationHandle,const sp<InputWindowHandle> & windowHandle,nsecs_t * nextWakeupTime,const char * reason)1021 int32_t InputDispatcher::handleTargetsNotReadyLocked(
1022         nsecs_t currentTime, const EventEntry* entry,
1023         const sp<InputApplicationHandle>& applicationHandle,
1024         const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
1025     if (applicationHandle == nullptr && windowHandle == nullptr) {
1026         if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1027 #if DEBUG_FOCUS
1028             ALOGD("Waiting for system to become ready for input.  Reason: %s", reason);
1029 #endif
1030             mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1031             mInputTargetWaitStartTime = currentTime;
1032             mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1033             mInputTargetWaitTimeoutExpired = false;
1034             mInputTargetWaitApplicationToken.clear();
1035         }
1036     } else {
1037         if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1038 #if DEBUG_FOCUS
1039             ALOGD("Waiting for application to become ready for input: %s.  Reason: %s",
1040                   getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1041 #endif
1042             nsecs_t timeout;
1043             if (windowHandle != nullptr) {
1044                 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1045             } else if (applicationHandle != nullptr) {
1046                 timeout =
1047                         applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1048             } else {
1049                 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1050             }
1051 
1052             mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1053             mInputTargetWaitStartTime = currentTime;
1054             mInputTargetWaitTimeoutTime = currentTime + timeout;
1055             mInputTargetWaitTimeoutExpired = false;
1056             mInputTargetWaitApplicationToken.clear();
1057 
1058             if (windowHandle != nullptr) {
1059                 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
1060             }
1061             if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1062                 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
1063             }
1064         }
1065     }
1066 
1067     if (mInputTargetWaitTimeoutExpired) {
1068         return INPUT_EVENT_INJECTION_TIMED_OUT;
1069     }
1070 
1071     if (currentTime >= mInputTargetWaitTimeoutTime) {
1072         onANRLocked(currentTime, applicationHandle, windowHandle, entry->eventTime,
1073                     mInputTargetWaitStartTime, reason);
1074 
1075         // Force poll loop to wake up immediately on next iteration once we get the
1076         // ANR response back from the policy.
1077         *nextWakeupTime = LONG_LONG_MIN;
1078         return INPUT_EVENT_INJECTION_PENDING;
1079     } else {
1080         // Force poll loop to wake up when timeout is due.
1081         if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1082             *nextWakeupTime = mInputTargetWaitTimeoutTime;
1083         }
1084         return INPUT_EVENT_INJECTION_PENDING;
1085     }
1086 }
1087 
removeWindowByTokenLocked(const sp<IBinder> & token)1088 void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1089     for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1090         TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1091         state.removeWindowByToken(token);
1092     }
1093 }
1094 
resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,const sp<InputChannel> & inputChannel)1095 void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
1096         nsecs_t newTimeout, const sp<InputChannel>& inputChannel) {
1097     if (newTimeout > 0) {
1098         // Extend the timeout.
1099         mInputTargetWaitTimeoutTime = now() + newTimeout;
1100     } else {
1101         // Give up.
1102         mInputTargetWaitTimeoutExpired = true;
1103 
1104         // Input state will not be realistic.  Mark it out of sync.
1105         if (inputChannel.get()) {
1106             ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1107             if (connectionIndex >= 0) {
1108                 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1109                 sp<IBinder> token = connection->inputChannel->getToken();
1110 
1111                 if (token != nullptr) {
1112                     removeWindowByTokenLocked(token);
1113                 }
1114 
1115                 if (connection->status == Connection::STATUS_NORMAL) {
1116                     CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1117                                                "application not responding");
1118                     synthesizeCancelationEventsForConnectionLocked(connection, options);
1119                 }
1120             }
1121         }
1122     }
1123 }
1124 
getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime)1125 nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
1126     if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1127         return currentTime - mInputTargetWaitStartTime;
1128     }
1129     return 0;
1130 }
1131 
resetANRTimeoutsLocked()1132 void InputDispatcher::resetANRTimeoutsLocked() {
1133 #if DEBUG_FOCUS
1134     ALOGD("Resetting ANR timeouts.");
1135 #endif
1136 
1137     // Reset input target wait timeout.
1138     mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1139     mInputTargetWaitApplicationToken.clear();
1140 }
1141 
1142 /**
1143  * Get the display id that the given event should go to. If this event specifies a valid display id,
1144  * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1145  * Focused display is the display that the user most recently interacted with.
1146  */
getTargetDisplayId(const EventEntry * entry)1147 int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1148     int32_t displayId;
1149     switch (entry->type) {
1150         case EventEntry::TYPE_KEY: {
1151             const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1152             displayId = typedEntry->displayId;
1153             break;
1154         }
1155         case EventEntry::TYPE_MOTION: {
1156             const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1157             displayId = typedEntry->displayId;
1158             break;
1159         }
1160         default: {
1161             ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1162             return ADISPLAY_ID_NONE;
1163         }
1164     }
1165     return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1166 }
1167 
findFocusedWindowTargetsLocked(nsecs_t currentTime,const EventEntry * entry,std::vector<InputTarget> & inputTargets,nsecs_t * nextWakeupTime)1168 int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1169                                                         const EventEntry* entry,
1170                                                         std::vector<InputTarget>& inputTargets,
1171                                                         nsecs_t* nextWakeupTime) {
1172     int32_t injectionResult;
1173     std::string reason;
1174 
1175     int32_t displayId = getTargetDisplayId(entry);
1176     sp<InputWindowHandle> focusedWindowHandle =
1177             getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1178     sp<InputApplicationHandle> focusedApplicationHandle =
1179             getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1180 
1181     // If there is no currently focused window and no focused application
1182     // then drop the event.
1183     if (focusedWindowHandle == nullptr) {
1184         if (focusedApplicationHandle != nullptr) {
1185             injectionResult =
1186                     handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1187                                                 nullptr, nextWakeupTime,
1188                                                 "Waiting because no window has focus but there is "
1189                                                 "a "
1190                                                 "focused application that may eventually add a "
1191                                                 "window "
1192                                                 "when it finishes starting up.");
1193             goto Unresponsive;
1194         }
1195 
1196         ALOGI("Dropping event because there is no focused window or focused application in display "
1197               "%" PRId32 ".",
1198               displayId);
1199         injectionResult = INPUT_EVENT_INJECTION_FAILED;
1200         goto Failed;
1201     }
1202 
1203     // Check permissions.
1204     if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
1205         injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1206         goto Failed;
1207     }
1208 
1209     // Check whether the window is ready for more input.
1210     reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
1211     if (!reason.empty()) {
1212         injectionResult =
1213                 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1214                                             focusedWindowHandle, nextWakeupTime, reason.c_str());
1215         goto Unresponsive;
1216     }
1217 
1218     // Success!  Output targets.
1219     injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1220     addWindowTargetLocked(focusedWindowHandle,
1221                           InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1222                           BitSet32(0), inputTargets);
1223 
1224     // Done.
1225 Failed:
1226 Unresponsive:
1227     nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1228     updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
1229 #if DEBUG_FOCUS
1230     ALOGD("findFocusedWindow finished: injectionResult=%d, "
1231           "timeSpentWaitingForApplication=%0.1fms",
1232           injectionResult, timeSpentWaitingForApplication / 1000000.0);
1233 #endif
1234     return injectionResult;
1235 }
1236 
findTouchedWindowTargetsLocked(nsecs_t currentTime,const MotionEntry * entry,std::vector<InputTarget> & inputTargets,nsecs_t * nextWakeupTime,bool * outConflictingPointerActions)1237 int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1238                                                         const MotionEntry* entry,
1239                                                         std::vector<InputTarget>& inputTargets,
1240                                                         nsecs_t* nextWakeupTime,
1241                                                         bool* outConflictingPointerActions) {
1242     ATRACE_CALL();
1243     enum InjectionPermission {
1244         INJECTION_PERMISSION_UNKNOWN,
1245         INJECTION_PERMISSION_GRANTED,
1246         INJECTION_PERMISSION_DENIED
1247     };
1248 
1249     // For security reasons, we defer updating the touch state until we are sure that
1250     // event injection will be allowed.
1251     int32_t displayId = entry->displayId;
1252     int32_t action = entry->action;
1253     int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1254 
1255     // Update the touch state as needed based on the properties of the touch event.
1256     int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1257     InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1258     sp<InputWindowHandle> newHoverWindowHandle;
1259 
1260     // Copy current touch state into mTempTouchState.
1261     // This state is always reset at the end of this function, so if we don't find state
1262     // for the specified display then our initial state will be empty.
1263     const TouchState* oldState = nullptr;
1264     ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1265     if (oldStateIndex >= 0) {
1266         oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1267         mTempTouchState.copyFrom(*oldState);
1268     }
1269 
1270     bool isSplit = mTempTouchState.split;
1271     bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
1272             (mTempTouchState.deviceId != entry->deviceId ||
1273              mTempTouchState.source != entry->source || mTempTouchState.displayId != displayId);
1274     bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1275                           maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1276                           maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1277     bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1278                        maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
1279     bool wrongDevice = false;
1280     if (newGesture) {
1281         bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1282         if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
1283 #if DEBUG_FOCUS
1284             ALOGD("Dropping event because a pointer for a different device is already down "
1285                   "in display %" PRId32,
1286                   displayId);
1287 #endif
1288             // TODO: test multiple simultaneous input streams.
1289             injectionResult = INPUT_EVENT_INJECTION_FAILED;
1290             switchedDevice = false;
1291             wrongDevice = true;
1292             goto Failed;
1293         }
1294         mTempTouchState.reset();
1295         mTempTouchState.down = down;
1296         mTempTouchState.deviceId = entry->deviceId;
1297         mTempTouchState.source = entry->source;
1298         mTempTouchState.displayId = displayId;
1299         isSplit = false;
1300     } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1301 #if DEBUG_FOCUS
1302         ALOGI("Dropping move event because a pointer for a different device is already active "
1303               "in display %" PRId32,
1304               displayId);
1305 #endif
1306         // TODO: test multiple simultaneous input streams.
1307         injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1308         switchedDevice = false;
1309         wrongDevice = true;
1310         goto Failed;
1311     }
1312 
1313     if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1314         /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1315 
1316         int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1317         int32_t x = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1318         int32_t y = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
1319         bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1320         sp<InputWindowHandle> newTouchedWindowHandle =
1321                 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1322                                           true /*addPortalWindows*/);
1323 
1324         std::vector<TouchedMonitor> newGestureMonitors = isDown
1325                 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1326                 : std::vector<TouchedMonitor>{};
1327 
1328         // Figure out whether splitting will be allowed for this window.
1329         if (newTouchedWindowHandle != nullptr &&
1330             newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1331             // New window supports splitting.
1332             isSplit = true;
1333         } else if (isSplit) {
1334             // New window does not support splitting but we have already split events.
1335             // Ignore the new window.
1336             newTouchedWindowHandle = nullptr;
1337         }
1338 
1339         // Handle the case where we did not find a window.
1340         if (newTouchedWindowHandle == nullptr) {
1341             // Try to assign the pointer to the first foreground window we find, if there is one.
1342             newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1343         }
1344 
1345         if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1346             ALOGI("Dropping event because there is no touchable window or gesture monitor at "
1347                   "(%d, %d) in display %" PRId32 ".",
1348                   x, y, displayId);
1349             injectionResult = INPUT_EVENT_INJECTION_FAILED;
1350             goto Failed;
1351         }
1352 
1353         if (newTouchedWindowHandle != nullptr) {
1354             // Set target flags.
1355             int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1356             if (isSplit) {
1357                 targetFlags |= InputTarget::FLAG_SPLIT;
1358             }
1359             if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1360                 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1361             } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1362                 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1363             }
1364 
1365             // Update hover state.
1366             if (isHoverAction) {
1367                 newHoverWindowHandle = newTouchedWindowHandle;
1368             } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1369                 newHoverWindowHandle = mLastHoverWindowHandle;
1370             }
1371 
1372             // Update the temporary touch state.
1373             BitSet32 pointerIds;
1374             if (isSplit) {
1375                 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1376                 pointerIds.markBit(pointerId);
1377             }
1378             mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1379         }
1380 
1381         mTempTouchState.addGestureMonitors(newGestureMonitors);
1382     } else {
1383         /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1384 
1385         // If the pointer is not currently down, then ignore the event.
1386         if (!mTempTouchState.down) {
1387 #if DEBUG_FOCUS
1388             ALOGD("Dropping event because the pointer is not down or we previously "
1389                   "dropped the pointer down event in display %" PRId32,
1390                   displayId);
1391 #endif
1392             injectionResult = INPUT_EVENT_INJECTION_FAILED;
1393             goto Failed;
1394         }
1395 
1396         // Check whether touches should slip outside of the current foreground window.
1397         if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry->pointerCount == 1 &&
1398             mTempTouchState.isSlippery()) {
1399             int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1400             int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1401 
1402             sp<InputWindowHandle> oldTouchedWindowHandle =
1403                     mTempTouchState.getFirstForegroundWindowHandle();
1404             sp<InputWindowHandle> newTouchedWindowHandle =
1405                     findTouchedWindowAtLocked(displayId, x, y);
1406             if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1407                 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
1408 #if DEBUG_FOCUS
1409                 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1410                       oldTouchedWindowHandle->getName().c_str(),
1411                       newTouchedWindowHandle->getName().c_str(), displayId);
1412 #endif
1413                 // Make a slippery exit from the old window.
1414                 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1415                                                   InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1416                                                   BitSet32(0));
1417 
1418                 // Make a slippery entrance into the new window.
1419                 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1420                     isSplit = true;
1421                 }
1422 
1423                 int32_t targetFlags =
1424                         InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1425                 if (isSplit) {
1426                     targetFlags |= InputTarget::FLAG_SPLIT;
1427                 }
1428                 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1429                     targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1430                 }
1431 
1432                 BitSet32 pointerIds;
1433                 if (isSplit) {
1434                     pointerIds.markBit(entry->pointerProperties[0].id);
1435                 }
1436                 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1437             }
1438         }
1439     }
1440 
1441     if (newHoverWindowHandle != mLastHoverWindowHandle) {
1442         // Let the previous window know that the hover sequence is over.
1443         if (mLastHoverWindowHandle != nullptr) {
1444 #if DEBUG_HOVER
1445             ALOGD("Sending hover exit event to window %s.",
1446                   mLastHoverWindowHandle->getName().c_str());
1447 #endif
1448             mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1449                                               InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1450                                               BitSet32(0));
1451         }
1452 
1453         // Let the new window know that the hover sequence is starting.
1454         if (newHoverWindowHandle != nullptr) {
1455 #if DEBUG_HOVER
1456             ALOGD("Sending hover enter event to window %s.",
1457                   newHoverWindowHandle->getName().c_str());
1458 #endif
1459             mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1460                                               InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1461                                               BitSet32(0));
1462         }
1463     }
1464 
1465     // Check permission to inject into all touched foreground windows and ensure there
1466     // is at least one touched foreground window.
1467     {
1468         bool haveForegroundWindow = false;
1469         for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1470             if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1471                 haveForegroundWindow = true;
1472                 if (!checkInjectionPermission(touchedWindow.windowHandle, entry->injectionState)) {
1473                     injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1474                     injectionPermission = INJECTION_PERMISSION_DENIED;
1475                     goto Failed;
1476                 }
1477             }
1478         }
1479         bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1480         if (!haveForegroundWindow && !hasGestureMonitor) {
1481 #if DEBUG_FOCUS
1482             ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1483                   " or gesture monitor to receive it.",
1484                   displayId);
1485 #endif
1486             injectionResult = INPUT_EVENT_INJECTION_FAILED;
1487             goto Failed;
1488         }
1489 
1490         // Permission granted to injection into all touched foreground windows.
1491         injectionPermission = INJECTION_PERMISSION_GRANTED;
1492     }
1493 
1494     // Check whether windows listening for outside touches are owned by the same UID. If it is
1495     // set the policy flag that we will not reveal coordinate information to this window.
1496     if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1497         sp<InputWindowHandle> foregroundWindowHandle =
1498                 mTempTouchState.getFirstForegroundWindowHandle();
1499         if (foregroundWindowHandle) {
1500             const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1501             for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1502                 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1503                     sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1504                     if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1505                         mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1506                                                           InputTarget::FLAG_ZERO_COORDS,
1507                                                           BitSet32(0));
1508                     }
1509                 }
1510             }
1511         }
1512     }
1513 
1514     // Ensure all touched foreground windows are ready for new input.
1515     for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1516         if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1517             // Check whether the window is ready for more input.
1518             std::string reason =
1519                     checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1520                                                        entry, "touched");
1521             if (!reason.empty()) {
1522                 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1523                                                               touchedWindow.windowHandle,
1524                                                               nextWakeupTime, reason.c_str());
1525                 goto Unresponsive;
1526             }
1527         }
1528     }
1529 
1530     // If this is the first pointer going down and the touched window has a wallpaper
1531     // then also add the touched wallpaper windows so they are locked in for the duration
1532     // of the touch gesture.
1533     // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1534     // engine only supports touch events.  We would need to add a mechanism similar
1535     // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1536     if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1537         sp<InputWindowHandle> foregroundWindowHandle =
1538                 mTempTouchState.getFirstForegroundWindowHandle();
1539         if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
1540             const std::vector<sp<InputWindowHandle>> windowHandles =
1541                     getWindowHandlesLocked(displayId);
1542             for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
1543                 const InputWindowInfo* info = windowHandle->getInfo();
1544                 if (info->displayId == displayId &&
1545                     windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1546                     mTempTouchState
1547                             .addOrUpdateWindow(windowHandle,
1548                                                InputTarget::FLAG_WINDOW_IS_OBSCURED |
1549                                                        InputTarget::
1550                                                                FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1551                                                        InputTarget::FLAG_DISPATCH_AS_IS,
1552                                                BitSet32(0));
1553                 }
1554             }
1555         }
1556     }
1557 
1558     // Success!  Output targets.
1559     injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1560 
1561     for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1562         addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1563                               touchedWindow.pointerIds, inputTargets);
1564     }
1565 
1566     for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1567         addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
1568                                   touchedMonitor.yOffset, inputTargets);
1569     }
1570 
1571     // Drop the outside or hover touch windows since we will not care about them
1572     // in the next iteration.
1573     mTempTouchState.filterNonAsIsTouchWindows();
1574 
1575 Failed:
1576     // Check injection permission once and for all.
1577     if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1578         if (checkInjectionPermission(nullptr, entry->injectionState)) {
1579             injectionPermission = INJECTION_PERMISSION_GRANTED;
1580         } else {
1581             injectionPermission = INJECTION_PERMISSION_DENIED;
1582         }
1583     }
1584 
1585     // Update final pieces of touch state if the injector had permission.
1586     if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1587         if (!wrongDevice) {
1588             if (switchedDevice) {
1589 #if DEBUG_FOCUS
1590                 ALOGD("Conflicting pointer actions: Switched to a different device.");
1591 #endif
1592                 *outConflictingPointerActions = true;
1593             }
1594 
1595             if (isHoverAction) {
1596                 // Started hovering, therefore no longer down.
1597                 if (oldState && oldState->down) {
1598 #if DEBUG_FOCUS
1599                     ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1600 #endif
1601                     *outConflictingPointerActions = true;
1602                 }
1603                 mTempTouchState.reset();
1604                 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1605                     maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1606                     mTempTouchState.deviceId = entry->deviceId;
1607                     mTempTouchState.source = entry->source;
1608                     mTempTouchState.displayId = displayId;
1609                 }
1610             } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1611                        maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1612                 // All pointers up or canceled.
1613                 mTempTouchState.reset();
1614             } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1615                 // First pointer went down.
1616                 if (oldState && oldState->down) {
1617 #if DEBUG_FOCUS
1618                     ALOGD("Conflicting pointer actions: Down received while already down.");
1619 #endif
1620                     *outConflictingPointerActions = true;
1621                 }
1622             } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1623                 // One pointer went up.
1624                 if (isSplit) {
1625                     int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1626                     uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1627 
1628                     for (size_t i = 0; i < mTempTouchState.windows.size();) {
1629                         TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1630                         if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1631                             touchedWindow.pointerIds.clearBit(pointerId);
1632                             if (touchedWindow.pointerIds.isEmpty()) {
1633                                 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
1634                                 continue;
1635                             }
1636                         }
1637                         i += 1;
1638                     }
1639                 }
1640             }
1641 
1642             // Save changes unless the action was scroll in which case the temporary touch
1643             // state was only valid for this one action.
1644             if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1645                 if (mTempTouchState.displayId >= 0) {
1646                     if (oldStateIndex >= 0) {
1647                         mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1648                     } else {
1649                         mTouchStatesByDisplay.add(displayId, mTempTouchState);
1650                     }
1651                 } else if (oldStateIndex >= 0) {
1652                     mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1653                 }
1654             }
1655 
1656             // Update hover state.
1657             mLastHoverWindowHandle = newHoverWindowHandle;
1658         }
1659     } else {
1660 #if DEBUG_FOCUS
1661         ALOGD("Not updating touch focus because injection was denied.");
1662 #endif
1663     }
1664 
1665 Unresponsive:
1666     // Reset temporary touch state to ensure we release unnecessary references to input channels.
1667     mTempTouchState.reset();
1668 
1669     nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1670     updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
1671 #if DEBUG_FOCUS
1672     ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1673           "timeSpentWaitingForApplication=%0.1fms",
1674           injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1675 #endif
1676     return injectionResult;
1677 }
1678 
addWindowTargetLocked(const sp<InputWindowHandle> & windowHandle,int32_t targetFlags,BitSet32 pointerIds,std::vector<InputTarget> & inputTargets)1679 void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1680                                             int32_t targetFlags, BitSet32 pointerIds,
1681                                             std::vector<InputTarget>& inputTargets) {
1682     sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1683     if (inputChannel == nullptr) {
1684         ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1685         return;
1686     }
1687 
1688     const InputWindowInfo* windowInfo = windowHandle->getInfo();
1689     InputTarget target;
1690     target.inputChannel = inputChannel;
1691     target.flags = targetFlags;
1692     target.xOffset = -windowInfo->frameLeft;
1693     target.yOffset = -windowInfo->frameTop;
1694     target.globalScaleFactor = windowInfo->globalScaleFactor;
1695     target.windowXScale = windowInfo->windowXScale;
1696     target.windowYScale = windowInfo->windowYScale;
1697     target.pointerIds = pointerIds;
1698     inputTargets.push_back(target);
1699 }
1700 
addGlobalMonitoringTargetsLocked(std::vector<InputTarget> & inputTargets,int32_t displayId,float xOffset,float yOffset)1701 void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
1702                                                        int32_t displayId, float xOffset,
1703                                                        float yOffset) {
1704     std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1705             mGlobalMonitorsByDisplay.find(displayId);
1706 
1707     if (it != mGlobalMonitorsByDisplay.end()) {
1708         const std::vector<Monitor>& monitors = it->second;
1709         for (const Monitor& monitor : monitors) {
1710             addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
1711         }
1712     }
1713 }
1714 
addMonitoringTargetLocked(const Monitor & monitor,float xOffset,float yOffset,std::vector<InputTarget> & inputTargets)1715 void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1716                                                 float yOffset,
1717                                                 std::vector<InputTarget>& inputTargets) {
1718     InputTarget target;
1719     target.inputChannel = monitor.inputChannel;
1720     target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1721     target.xOffset = xOffset;
1722     target.yOffset = yOffset;
1723     target.pointerIds.clear();
1724     target.globalScaleFactor = 1.0f;
1725     inputTargets.push_back(target);
1726 }
1727 
checkInjectionPermission(const sp<InputWindowHandle> & windowHandle,const InjectionState * injectionState)1728 bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1729                                                const InjectionState* injectionState) {
1730     if (injectionState &&
1731         (windowHandle == nullptr ||
1732          windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1733         !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1734         if (windowHandle != nullptr) {
1735             ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1736                   "owned by uid %d",
1737                   injectionState->injectorPid, injectionState->injectorUid,
1738                   windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
1739         } else {
1740             ALOGW("Permission denied: injecting event from pid %d uid %d",
1741                   injectionState->injectorPid, injectionState->injectorUid);
1742         }
1743         return false;
1744     }
1745     return true;
1746 }
1747 
isWindowObscuredAtPointLocked(const sp<InputWindowHandle> & windowHandle,int32_t x,int32_t y) const1748 bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1749                                                     int32_t x, int32_t y) const {
1750     int32_t displayId = windowHandle->getInfo()->displayId;
1751     const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1752     for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
1753         if (otherHandle == windowHandle) {
1754             break;
1755         }
1756 
1757         const InputWindowInfo* otherInfo = otherHandle->getInfo();
1758         if (otherInfo->displayId == displayId && otherInfo->visible &&
1759             !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
1760             return true;
1761         }
1762     }
1763     return false;
1764 }
1765 
isWindowObscuredLocked(const sp<InputWindowHandle> & windowHandle) const1766 bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1767     int32_t displayId = windowHandle->getInfo()->displayId;
1768     const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1769     const InputWindowInfo* windowInfo = windowHandle->getInfo();
1770     for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
1771         if (otherHandle == windowHandle) {
1772             break;
1773         }
1774 
1775         const InputWindowInfo* otherInfo = otherHandle->getInfo();
1776         if (otherInfo->displayId == displayId && otherInfo->visible &&
1777             !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
1778             return true;
1779         }
1780     }
1781     return false;
1782 }
1783 
checkWindowReadyForMoreInputLocked(nsecs_t currentTime,const sp<InputWindowHandle> & windowHandle,const EventEntry * eventEntry,const char * targetType)1784 std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1785         nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
1786         const EventEntry* eventEntry, const char* targetType) {
1787     // If the window is paused then keep waiting.
1788     if (windowHandle->getInfo()->paused) {
1789         return StringPrintf("Waiting because the %s window is paused.", targetType);
1790     }
1791 
1792     // If the window's connection is not registered then keep waiting.
1793     ssize_t connectionIndex =
1794             getConnectionIndexLocked(getInputChannelLocked(windowHandle->getToken()));
1795     if (connectionIndex < 0) {
1796         return StringPrintf("Waiting because the %s window's input channel is not "
1797                             "registered with the input dispatcher.  The window may be in the "
1798                             "process "
1799                             "of being removed.",
1800                             targetType);
1801     }
1802 
1803     // If the connection is dead then keep waiting.
1804     sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1805     if (connection->status != Connection::STATUS_NORMAL) {
1806         return StringPrintf("Waiting because the %s window's input connection is %s."
1807                             "The window may be in the process of being removed.",
1808                             targetType, connection->getStatusLabel());
1809     }
1810 
1811     // If the connection is backed up then keep waiting.
1812     if (connection->inputPublisherBlocked) {
1813         return StringPrintf("Waiting because the %s window's input channel is full.  "
1814                             "Outbound queue length: %d.  Wait queue length: %d.",
1815                             targetType, connection->outboundQueue.count(),
1816                             connection->waitQueue.count());
1817     }
1818 
1819     // Ensure that the dispatch queues aren't too far backed up for this event.
1820     if (eventEntry->type == EventEntry::TYPE_KEY) {
1821         // If the event is a key event, then we must wait for all previous events to
1822         // complete before delivering it because previous events may have the
1823         // side-effect of transferring focus to a different window and we want to
1824         // ensure that the following keys are sent to the new window.
1825         //
1826         // Suppose the user touches a button in a window then immediately presses "A".
1827         // If the button causes a pop-up window to appear then we want to ensure that
1828         // the "A" key is delivered to the new pop-up window.  This is because users
1829         // often anticipate pending UI changes when typing on a keyboard.
1830         // To obtain this behavior, we must serialize key events with respect to all
1831         // prior input events.
1832         if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
1833             return StringPrintf("Waiting to send key event because the %s window has not "
1834                                 "finished processing all of the input events that were previously "
1835                                 "delivered to it.  Outbound queue length: %d.  Wait queue length: "
1836                                 "%d.",
1837                                 targetType, connection->outboundQueue.count(),
1838                                 connection->waitQueue.count());
1839         }
1840     } else {
1841         // Touch events can always be sent to a window immediately because the user intended
1842         // to touch whatever was visible at the time.  Even if focus changes or a new
1843         // window appears moments later, the touch event was meant to be delivered to
1844         // whatever window happened to be on screen at the time.
1845         //
1846         // Generic motion events, such as trackball or joystick events are a little trickier.
1847         // Like key events, generic motion events are delivered to the focused window.
1848         // Unlike key events, generic motion events don't tend to transfer focus to other
1849         // windows and it is not important for them to be serialized.  So we prefer to deliver
1850         // generic motion events as soon as possible to improve efficiency and reduce lag
1851         // through batching.
1852         //
1853         // The one case where we pause input event delivery is when the wait queue is piling
1854         // up with lots of events because the application is not responding.
1855         // This condition ensures that ANRs are detected reliably.
1856         if (!connection->waitQueue.isEmpty() &&
1857             currentTime >= connection->waitQueue.head->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
1858             return StringPrintf("Waiting to send non-key event because the %s window has not "
1859                                 "finished processing certain input events that were delivered to "
1860                                 "it over "
1861                                 "%0.1fms ago.  Wait queue length: %d.  Wait queue head age: "
1862                                 "%0.1fms.",
1863                                 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1864                                 connection->waitQueue.count(),
1865                                 (currentTime - connection->waitQueue.head->deliveryTime) *
1866                                         0.000001f);
1867         }
1868     }
1869     return "";
1870 }
1871 
getApplicationWindowLabel(const sp<InputApplicationHandle> & applicationHandle,const sp<InputWindowHandle> & windowHandle)1872 std::string InputDispatcher::getApplicationWindowLabel(
1873         const sp<InputApplicationHandle>& applicationHandle,
1874         const sp<InputWindowHandle>& windowHandle) {
1875     if (applicationHandle != nullptr) {
1876         if (windowHandle != nullptr) {
1877             std::string label(applicationHandle->getName());
1878             label += " - ";
1879             label += windowHandle->getName();
1880             return label;
1881         } else {
1882             return applicationHandle->getName();
1883         }
1884     } else if (windowHandle != nullptr) {
1885         return windowHandle->getName();
1886     } else {
1887         return "<unknown application or window>";
1888     }
1889 }
1890 
pokeUserActivityLocked(const EventEntry * eventEntry)1891 void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1892     int32_t displayId = getTargetDisplayId(eventEntry);
1893     sp<InputWindowHandle> focusedWindowHandle =
1894             getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1895     if (focusedWindowHandle != nullptr) {
1896         const InputWindowInfo* info = focusedWindowHandle->getInfo();
1897         if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1898 #if DEBUG_DISPATCH_CYCLE
1899             ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
1900 #endif
1901             return;
1902         }
1903     }
1904 
1905     int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1906     switch (eventEntry->type) {
1907         case EventEntry::TYPE_MOTION: {
1908             const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1909             if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1910                 return;
1911             }
1912 
1913             if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1914                 eventType = USER_ACTIVITY_EVENT_TOUCH;
1915             }
1916             break;
1917         }
1918         case EventEntry::TYPE_KEY: {
1919             const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1920             if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1921                 return;
1922             }
1923             eventType = USER_ACTIVITY_EVENT_BUTTON;
1924             break;
1925         }
1926     }
1927 
1928     CommandEntry* commandEntry =
1929             postCommandLocked(&InputDispatcher::doPokeUserActivityLockedInterruptible);
1930     commandEntry->eventTime = eventEntry->eventTime;
1931     commandEntry->userActivityEventType = eventType;
1932 }
1933 
prepareDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,EventEntry * eventEntry,const InputTarget * inputTarget)1934 void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1935                                                  const sp<Connection>& connection,
1936                                                  EventEntry* eventEntry,
1937                                                  const InputTarget* inputTarget) {
1938     if (ATRACE_ENABLED()) {
1939         std::string message =
1940                 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1941                              connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
1942         ATRACE_NAME(message.c_str());
1943     }
1944 #if DEBUG_DISPATCH_CYCLE
1945     ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1946           "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1947           "windowScaleFactor=(%f, %f), pointerIds=0x%x",
1948           connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
1949           inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
1950           inputTarget->windowYScale, inputTarget->pointerIds.value);
1951 #endif
1952 
1953     // Skip this event if the connection status is not normal.
1954     // We don't want to enqueue additional outbound events if the connection is broken.
1955     if (connection->status != Connection::STATUS_NORMAL) {
1956 #if DEBUG_DISPATCH_CYCLE
1957         ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
1958               connection->getInputChannelName().c_str(), connection->getStatusLabel());
1959 #endif
1960         return;
1961     }
1962 
1963     // Split a motion event if needed.
1964     if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1965         ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1966 
1967         MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1968         if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1969             MotionEntry* splitMotionEntry =
1970                     splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
1971             if (!splitMotionEntry) {
1972                 return; // split event was dropped
1973             }
1974 #if DEBUG_FOCUS
1975             ALOGD("channel '%s' ~ Split motion event.", connection->getInputChannelName().c_str());
1976             logOutboundMotionDetails("  ", splitMotionEntry);
1977 #endif
1978             enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
1979             splitMotionEntry->release();
1980             return;
1981         }
1982     }
1983 
1984     // Not splitting.  Enqueue dispatch entries for the event as is.
1985     enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1986 }
1987 
enqueueDispatchEntriesLocked(nsecs_t currentTime,const sp<Connection> & connection,EventEntry * eventEntry,const InputTarget * inputTarget)1988 void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1989                                                    const sp<Connection>& connection,
1990                                                    EventEntry* eventEntry,
1991                                                    const InputTarget* inputTarget) {
1992     if (ATRACE_ENABLED()) {
1993         std::string message =
1994                 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
1995                              ")",
1996                              connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
1997         ATRACE_NAME(message.c_str());
1998     }
1999 
2000     bool wasEmpty = connection->outboundQueue.isEmpty();
2001 
2002     // Enqueue dispatch entries for the requested modes.
2003     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2004                                InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
2005     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2006                                InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
2007     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2008                                InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
2009     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2010                                InputTarget::FLAG_DISPATCH_AS_IS);
2011     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2012                                InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
2013     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2014                                InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
2015 
2016     // If the outbound queue was previously empty, start the dispatch cycle going.
2017     if (wasEmpty && !connection->outboundQueue.isEmpty()) {
2018         startDispatchCycleLocked(currentTime, connection);
2019     }
2020 }
2021 
enqueueDispatchEntryLocked(const sp<Connection> & connection,EventEntry * eventEntry,const InputTarget * inputTarget,int32_t dispatchMode)2022 void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2023                                                  EventEntry* eventEntry,
2024                                                  const InputTarget* inputTarget,
2025                                                  int32_t dispatchMode) {
2026     if (ATRACE_ENABLED()) {
2027         std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2028                                            connection->getInputChannelName().c_str(),
2029                                            dispatchModeToString(dispatchMode).c_str());
2030         ATRACE_NAME(message.c_str());
2031     }
2032     int32_t inputTargetFlags = inputTarget->flags;
2033     if (!(inputTargetFlags & dispatchMode)) {
2034         return;
2035     }
2036     inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2037 
2038     // This is a new event.
2039     // Enqueue a new dispatch entry onto the outbound queue for this connection.
2040     DispatchEntry* dispatchEntry =
2041             new DispatchEntry(eventEntry, // increments ref
2042                               inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2043                               inputTarget->globalScaleFactor, inputTarget->windowXScale,
2044                               inputTarget->windowYScale);
2045 
2046     // Apply target flags and update the connection's input state.
2047     switch (eventEntry->type) {
2048         case EventEntry::TYPE_KEY: {
2049             KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2050             dispatchEntry->resolvedAction = keyEntry->action;
2051             dispatchEntry->resolvedFlags = keyEntry->flags;
2052 
2053             if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2054                                                  dispatchEntry->resolvedFlags)) {
2055 #if DEBUG_DISPATCH_CYCLE
2056                 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2057                       connection->getInputChannelName().c_str());
2058 #endif
2059                 delete dispatchEntry;
2060                 return; // skip the inconsistent event
2061             }
2062             break;
2063         }
2064 
2065         case EventEntry::TYPE_MOTION: {
2066             MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2067             if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2068                 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2069             } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2070                 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2071             } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2072                 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2073             } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2074                 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2075             } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2076                 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2077             } else {
2078                 dispatchEntry->resolvedAction = motionEntry->action;
2079             }
2080             if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
2081                 !connection->inputState.isHovering(motionEntry->deviceId, motionEntry->source,
2082                                                    motionEntry->displayId)) {
2083 #if DEBUG_DISPATCH_CYCLE
2084                 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2085                       "event",
2086                       connection->getInputChannelName().c_str());
2087 #endif
2088                 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2089             }
2090 
2091             dispatchEntry->resolvedFlags = motionEntry->flags;
2092             if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2093                 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2094             }
2095             if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2096                 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2097             }
2098 
2099             if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2100                                                     dispatchEntry->resolvedFlags)) {
2101 #if DEBUG_DISPATCH_CYCLE
2102                 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2103                       "event",
2104                       connection->getInputChannelName().c_str());
2105 #endif
2106                 delete dispatchEntry;
2107                 return; // skip the inconsistent event
2108             }
2109 
2110             dispatchPointerDownOutsideFocus(motionEntry->source, dispatchEntry->resolvedAction,
2111                                             inputTarget->inputChannel->getToken());
2112 
2113             break;
2114         }
2115     }
2116 
2117     // Remember that we are waiting for this dispatch to complete.
2118     if (dispatchEntry->hasForegroundTarget()) {
2119         incrementPendingForegroundDispatches(eventEntry);
2120     }
2121 
2122     // Enqueue the dispatch entry.
2123     connection->outboundQueue.enqueueAtTail(dispatchEntry);
2124     traceOutboundQueueLength(connection);
2125 }
2126 
dispatchPointerDownOutsideFocus(uint32_t source,int32_t action,const sp<IBinder> & newToken)2127 void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
2128                                                       const sp<IBinder>& newToken) {
2129     int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2130     uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2131     if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
2132         return;
2133     }
2134 
2135     sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2136     if (inputWindowHandle == nullptr) {
2137         return;
2138     }
2139 
2140     sp<InputWindowHandle> focusedWindowHandle =
2141             getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
2142 
2143     bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2144 
2145     if (!hasFocusChanged) {
2146         return;
2147     }
2148 
2149     CommandEntry* commandEntry =
2150             postCommandLocked(&InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
2151     commandEntry->newToken = newToken;
2152 }
2153 
startDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection)2154 void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2155                                                const sp<Connection>& connection) {
2156     if (ATRACE_ENABLED()) {
2157         std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
2158                                            connection->getInputChannelName().c_str());
2159         ATRACE_NAME(message.c_str());
2160     }
2161 #if DEBUG_DISPATCH_CYCLE
2162     ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
2163 #endif
2164 
2165     while (connection->status == Connection::STATUS_NORMAL &&
2166            !connection->outboundQueue.isEmpty()) {
2167         DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2168         dispatchEntry->deliveryTime = currentTime;
2169 
2170         // Publish the event.
2171         status_t status;
2172         EventEntry* eventEntry = dispatchEntry->eventEntry;
2173         switch (eventEntry->type) {
2174             case EventEntry::TYPE_KEY: {
2175                 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2176 
2177                 // Publish the key event.
2178                 status = connection->inputPublisher
2179                                  .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2180                                                   keyEntry->source, keyEntry->displayId,
2181                                                   dispatchEntry->resolvedAction,
2182                                                   dispatchEntry->resolvedFlags, keyEntry->keyCode,
2183                                                   keyEntry->scanCode, keyEntry->metaState,
2184                                                   keyEntry->repeatCount, keyEntry->downTime,
2185                                                   keyEntry->eventTime);
2186                 break;
2187             }
2188 
2189             case EventEntry::TYPE_MOTION: {
2190                 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2191 
2192                 PointerCoords scaledCoords[MAX_POINTERS];
2193                 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2194 
2195                 // Set the X and Y offset depending on the input source.
2196                 float xOffset, yOffset;
2197                 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2198                     !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2199                     float globalScaleFactor = dispatchEntry->globalScaleFactor;
2200                     float wxs = dispatchEntry->windowXScale;
2201                     float wys = dispatchEntry->windowYScale;
2202                     xOffset = dispatchEntry->xOffset * wxs;
2203                     yOffset = dispatchEntry->yOffset * wys;
2204                     if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2205                         for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2206                             scaledCoords[i] = motionEntry->pointerCoords[i];
2207                             scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2208                         }
2209                         usingCoords = scaledCoords;
2210                     }
2211                 } else {
2212                     xOffset = 0.0f;
2213                     yOffset = 0.0f;
2214 
2215                     // We don't want the dispatch target to know.
2216                     if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2217                         for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2218                             scaledCoords[i].clear();
2219                         }
2220                         usingCoords = scaledCoords;
2221                     }
2222                 }
2223 
2224                 // Publish the motion event.
2225                 status = connection->inputPublisher
2226                                  .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2227                                                      motionEntry->source, motionEntry->displayId,
2228                                                      dispatchEntry->resolvedAction,
2229                                                      motionEntry->actionButton,
2230                                                      dispatchEntry->resolvedFlags,
2231                                                      motionEntry->edgeFlags, motionEntry->metaState,
2232                                                      motionEntry->buttonState,
2233                                                      motionEntry->classification, xOffset, yOffset,
2234                                                      motionEntry->xPrecision,
2235                                                      motionEntry->yPrecision, motionEntry->downTime,
2236                                                      motionEntry->eventTime,
2237                                                      motionEntry->pointerCount,
2238                                                      motionEntry->pointerProperties, usingCoords);
2239                 break;
2240             }
2241 
2242             default:
2243                 ALOG_ASSERT(false);
2244                 return;
2245         }
2246 
2247         // Check the result.
2248         if (status) {
2249             if (status == WOULD_BLOCK) {
2250                 if (connection->waitQueue.isEmpty()) {
2251                     ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2252                           "This is unexpected because the wait queue is empty, so the pipe "
2253                           "should be empty and we shouldn't have any problems writing an "
2254                           "event to it, status=%d",
2255                           connection->getInputChannelName().c_str(), status);
2256                     abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2257                 } else {
2258                     // Pipe is full and we are waiting for the app to finish process some events
2259                     // before sending more events to it.
2260 #if DEBUG_DISPATCH_CYCLE
2261                     ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2262                           "waiting for the application to catch up",
2263                           connection->getInputChannelName().c_str());
2264 #endif
2265                     connection->inputPublisherBlocked = true;
2266                 }
2267             } else {
2268                 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2269                       "status=%d",
2270                       connection->getInputChannelName().c_str(), status);
2271                 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2272             }
2273             return;
2274         }
2275 
2276         // Re-enqueue the event on the wait queue.
2277         connection->outboundQueue.dequeue(dispatchEntry);
2278         traceOutboundQueueLength(connection);
2279         connection->waitQueue.enqueueAtTail(dispatchEntry);
2280         traceWaitQueueLength(connection);
2281     }
2282 }
2283 
finishDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,uint32_t seq,bool handled)2284 void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2285                                                 const sp<Connection>& connection, uint32_t seq,
2286                                                 bool handled) {
2287 #if DEBUG_DISPATCH_CYCLE
2288     ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2289           connection->getInputChannelName().c_str(), seq, toString(handled));
2290 #endif
2291 
2292     connection->inputPublisherBlocked = false;
2293 
2294     if (connection->status == Connection::STATUS_BROKEN ||
2295         connection->status == Connection::STATUS_ZOMBIE) {
2296         return;
2297     }
2298 
2299     // Notify other system components and prepare to start the next dispatch cycle.
2300     onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2301 }
2302 
abortBrokenDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,bool notify)2303 void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2304                                                      const sp<Connection>& connection,
2305                                                      bool notify) {
2306 #if DEBUG_DISPATCH_CYCLE
2307     ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2308           connection->getInputChannelName().c_str(), toString(notify));
2309 #endif
2310 
2311     // Clear the dispatch queues.
2312     drainDispatchQueue(&connection->outboundQueue);
2313     traceOutboundQueueLength(connection);
2314     drainDispatchQueue(&connection->waitQueue);
2315     traceWaitQueueLength(connection);
2316 
2317     // The connection appears to be unrecoverably broken.
2318     // Ignore already broken or zombie connections.
2319     if (connection->status == Connection::STATUS_NORMAL) {
2320         connection->status = Connection::STATUS_BROKEN;
2321 
2322         if (notify) {
2323             // Notify other system components.
2324             onDispatchCycleBrokenLocked(currentTime, connection);
2325         }
2326     }
2327 }
2328 
drainDispatchQueue(Queue<DispatchEntry> * queue)2329 void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
2330     while (!queue->isEmpty()) {
2331         DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2332         releaseDispatchEntry(dispatchEntry);
2333     }
2334 }
2335 
releaseDispatchEntry(DispatchEntry * dispatchEntry)2336 void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
2337     if (dispatchEntry->hasForegroundTarget()) {
2338         decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
2339     }
2340     delete dispatchEntry;
2341 }
2342 
handleReceiveCallback(int fd,int events,void * data)2343 int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2344     InputDispatcher* d = static_cast<InputDispatcher*>(data);
2345 
2346     { // acquire lock
2347         std::scoped_lock _l(d->mLock);
2348 
2349         ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2350         if (connectionIndex < 0) {
2351             ALOGE("Received spurious receive callback for unknown input channel.  "
2352                   "fd=%d, events=0x%x",
2353                   fd, events);
2354             return 0; // remove the callback
2355         }
2356 
2357         bool notify;
2358         sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2359         if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2360             if (!(events & ALOOPER_EVENT_INPUT)) {
2361                 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event.  "
2362                       "events=0x%x",
2363                       connection->getInputChannelName().c_str(), events);
2364                 return 1;
2365             }
2366 
2367             nsecs_t currentTime = now();
2368             bool gotOne = false;
2369             status_t status;
2370             for (;;) {
2371                 uint32_t seq;
2372                 bool handled;
2373                 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2374                 if (status) {
2375                     break;
2376                 }
2377                 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2378                 gotOne = true;
2379             }
2380             if (gotOne) {
2381                 d->runCommandsLockedInterruptible();
2382                 if (status == WOULD_BLOCK) {
2383                     return 1;
2384                 }
2385             }
2386 
2387             notify = status != DEAD_OBJECT || !connection->monitor;
2388             if (notify) {
2389                 ALOGE("channel '%s' ~ Failed to receive finished signal.  status=%d",
2390                       connection->getInputChannelName().c_str(), status);
2391             }
2392         } else {
2393             // Monitor channels are never explicitly unregistered.
2394             // We do it automatically when the remote endpoint is closed so don't warn
2395             // about them.
2396             notify = !connection->monitor;
2397             if (notify) {
2398                 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred.  "
2399                       "events=0x%x",
2400                       connection->getInputChannelName().c_str(), events);
2401             }
2402         }
2403 
2404         // Unregister the channel.
2405         d->unregisterInputChannelLocked(connection->inputChannel, notify);
2406         return 0; // remove the callback
2407     }             // release lock
2408 }
2409 
synthesizeCancelationEventsForAllConnectionsLocked(const CancelationOptions & options)2410 void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2411         const CancelationOptions& options) {
2412     for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2413         synthesizeCancelationEventsForConnectionLocked(mConnectionsByFd.valueAt(i), options);
2414     }
2415 }
2416 
synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions & options)2417 void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2418         const CancelationOptions& options) {
2419     synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2420     synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2421 }
2422 
synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions & options,std::unordered_map<int32_t,std::vector<Monitor>> & monitorsByDisplay)2423 void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2424         const CancelationOptions& options,
2425         std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2426     for (const auto& it : monitorsByDisplay) {
2427         const std::vector<Monitor>& monitors = it.second;
2428         for (const Monitor& monitor : monitors) {
2429             synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
2430         }
2431     }
2432 }
2433 
synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel> & channel,const CancelationOptions & options)2434 void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2435         const sp<InputChannel>& channel, const CancelationOptions& options) {
2436     ssize_t index = getConnectionIndexLocked(channel);
2437     if (index >= 0) {
2438         synthesizeCancelationEventsForConnectionLocked(mConnectionsByFd.valueAt(index), options);
2439     }
2440 }
2441 
synthesizeCancelationEventsForConnectionLocked(const sp<Connection> & connection,const CancelationOptions & options)2442 void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2443         const sp<Connection>& connection, const CancelationOptions& options) {
2444     if (connection->status == Connection::STATUS_BROKEN) {
2445         return;
2446     }
2447 
2448     nsecs_t currentTime = now();
2449 
2450     std::vector<EventEntry*> cancelationEvents;
2451     connection->inputState.synthesizeCancelationEvents(currentTime, cancelationEvents, options);
2452 
2453     if (!cancelationEvents.empty()) {
2454 #if DEBUG_OUTBOUND_EVENT_DETAILS
2455         ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2456               "with reality: %s, mode=%d.",
2457               connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2458               options.mode);
2459 #endif
2460         for (size_t i = 0; i < cancelationEvents.size(); i++) {
2461             EventEntry* cancelationEventEntry = cancelationEvents[i];
2462             switch (cancelationEventEntry->type) {
2463                 case EventEntry::TYPE_KEY:
2464                     logOutboundKeyDetails("cancel - ",
2465                                           static_cast<KeyEntry*>(cancelationEventEntry));
2466                     break;
2467                 case EventEntry::TYPE_MOTION:
2468                     logOutboundMotionDetails("cancel - ",
2469                                              static_cast<MotionEntry*>(cancelationEventEntry));
2470                     break;
2471             }
2472 
2473             InputTarget target;
2474             sp<InputWindowHandle> windowHandle =
2475                     getWindowHandleLocked(connection->inputChannel->getToken());
2476             if (windowHandle != nullptr) {
2477                 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2478                 target.xOffset = -windowInfo->frameLeft;
2479                 target.yOffset = -windowInfo->frameTop;
2480                 target.globalScaleFactor = windowInfo->globalScaleFactor;
2481                 target.windowXScale = windowInfo->windowXScale;
2482                 target.windowYScale = windowInfo->windowYScale;
2483             } else {
2484                 target.xOffset = 0;
2485                 target.yOffset = 0;
2486                 target.globalScaleFactor = 1.0f;
2487             }
2488             target.inputChannel = connection->inputChannel;
2489             target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2490 
2491             enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2492                                        &target, InputTarget::FLAG_DISPATCH_AS_IS);
2493 
2494             cancelationEventEntry->release();
2495         }
2496 
2497         startDispatchCycleLocked(currentTime, connection);
2498     }
2499 }
2500 
splitMotionEvent(const MotionEntry * originalMotionEntry,BitSet32 pointerIds)2501 MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry,
2502                                                BitSet32 pointerIds) {
2503     ALOG_ASSERT(pointerIds.value != 0);
2504 
2505     uint32_t splitPointerIndexMap[MAX_POINTERS];
2506     PointerProperties splitPointerProperties[MAX_POINTERS];
2507     PointerCoords splitPointerCoords[MAX_POINTERS];
2508 
2509     uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2510     uint32_t splitPointerCount = 0;
2511 
2512     for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2513          originalPointerIndex++) {
2514         const PointerProperties& pointerProperties =
2515                 originalMotionEntry->pointerProperties[originalPointerIndex];
2516         uint32_t pointerId = uint32_t(pointerProperties.id);
2517         if (pointerIds.hasBit(pointerId)) {
2518             splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2519             splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2520             splitPointerCoords[splitPointerCount].copyFrom(
2521                     originalMotionEntry->pointerCoords[originalPointerIndex]);
2522             splitPointerCount += 1;
2523         }
2524     }
2525 
2526     if (splitPointerCount != pointerIds.count()) {
2527         // This is bad.  We are missing some of the pointers that we expected to deliver.
2528         // Most likely this indicates that we received an ACTION_MOVE events that has
2529         // different pointer ids than we expected based on the previous ACTION_DOWN
2530         // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2531         // in this way.
2532         ALOGW("Dropping split motion event because the pointer count is %d but "
2533               "we expected there to be %d pointers.  This probably means we received "
2534               "a broken sequence of pointer ids from the input device.",
2535               splitPointerCount, pointerIds.count());
2536         return nullptr;
2537     }
2538 
2539     int32_t action = originalMotionEntry->action;
2540     int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2541     if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2542         maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2543         int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2544         const PointerProperties& pointerProperties =
2545                 originalMotionEntry->pointerProperties[originalPointerIndex];
2546         uint32_t pointerId = uint32_t(pointerProperties.id);
2547         if (pointerIds.hasBit(pointerId)) {
2548             if (pointerIds.count() == 1) {
2549                 // The first/last pointer went down/up.
2550                 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2551                         ? AMOTION_EVENT_ACTION_DOWN
2552                         : AMOTION_EVENT_ACTION_UP;
2553             } else {
2554                 // A secondary pointer went down/up.
2555                 uint32_t splitPointerIndex = 0;
2556                 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2557                     splitPointerIndex += 1;
2558                 }
2559                 action = maskedAction |
2560                         (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2561             }
2562         } else {
2563             // An unrelated pointer changed.
2564             action = AMOTION_EVENT_ACTION_MOVE;
2565         }
2566     }
2567 
2568     MotionEntry* splitMotionEntry =
2569             new MotionEntry(originalMotionEntry->sequenceNum, originalMotionEntry->eventTime,
2570                             originalMotionEntry->deviceId, originalMotionEntry->source,
2571                             originalMotionEntry->displayId, originalMotionEntry->policyFlags,
2572                             action, originalMotionEntry->actionButton, originalMotionEntry->flags,
2573                             originalMotionEntry->metaState, originalMotionEntry->buttonState,
2574                             originalMotionEntry->classification, originalMotionEntry->edgeFlags,
2575                             originalMotionEntry->xPrecision, originalMotionEntry->yPrecision,
2576                             originalMotionEntry->downTime, splitPointerCount,
2577                             splitPointerProperties, splitPointerCoords, 0, 0);
2578 
2579     if (originalMotionEntry->injectionState) {
2580         splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2581         splitMotionEntry->injectionState->refCount += 1;
2582     }
2583 
2584     return splitMotionEntry;
2585 }
2586 
notifyConfigurationChanged(const NotifyConfigurationChangedArgs * args)2587 void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2588 #if DEBUG_INBOUND_EVENT_DETAILS
2589     ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
2590 #endif
2591 
2592     bool needWake;
2593     { // acquire lock
2594         std::scoped_lock _l(mLock);
2595 
2596         ConfigurationChangedEntry* newEntry =
2597                 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
2598         needWake = enqueueInboundEventLocked(newEntry);
2599     } // release lock
2600 
2601     if (needWake) {
2602         mLooper->wake();
2603     }
2604 }
2605 
2606 /**
2607  * If one of the meta shortcuts is detected, process them here:
2608  *     Meta + Backspace -> generate BACK
2609  *     Meta + Enter -> generate HOME
2610  * This will potentially overwrite keyCode and metaState.
2611  */
accelerateMetaShortcuts(const int32_t deviceId,const int32_t action,int32_t & keyCode,int32_t & metaState)2612 void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2613                                               int32_t& keyCode, int32_t& metaState) {
2614     if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2615         int32_t newKeyCode = AKEYCODE_UNKNOWN;
2616         if (keyCode == AKEYCODE_DEL) {
2617             newKeyCode = AKEYCODE_BACK;
2618         } else if (keyCode == AKEYCODE_ENTER) {
2619             newKeyCode = AKEYCODE_HOME;
2620         }
2621         if (newKeyCode != AKEYCODE_UNKNOWN) {
2622             std::scoped_lock _l(mLock);
2623             struct KeyReplacement replacement = {keyCode, deviceId};
2624             mReplacedKeys.add(replacement, newKeyCode);
2625             keyCode = newKeyCode;
2626             metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2627         }
2628     } else if (action == AKEY_EVENT_ACTION_UP) {
2629         // In order to maintain a consistent stream of up and down events, check to see if the key
2630         // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2631         // even if the modifier was released between the down and the up events.
2632         std::scoped_lock _l(mLock);
2633         struct KeyReplacement replacement = {keyCode, deviceId};
2634         ssize_t index = mReplacedKeys.indexOfKey(replacement);
2635         if (index >= 0) {
2636             keyCode = mReplacedKeys.valueAt(index);
2637             mReplacedKeys.removeItemsAt(index);
2638             metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2639         }
2640     }
2641 }
2642 
notifyKey(const NotifyKeyArgs * args)2643 void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2644 #if DEBUG_INBOUND_EVENT_DETAILS
2645     ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2646           "policyFlags=0x%x, action=0x%x, "
2647           "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2648           args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2649           args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2650           args->downTime);
2651 #endif
2652     if (!validateKeyEvent(args->action)) {
2653         return;
2654     }
2655 
2656     uint32_t policyFlags = args->policyFlags;
2657     int32_t flags = args->flags;
2658     int32_t metaState = args->metaState;
2659     // InputDispatcher tracks and generates key repeats on behalf of
2660     // whatever notifies it, so repeatCount should always be set to 0
2661     constexpr int32_t repeatCount = 0;
2662     if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2663         policyFlags |= POLICY_FLAG_VIRTUAL;
2664         flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2665     }
2666     if (policyFlags & POLICY_FLAG_FUNCTION) {
2667         metaState |= AMETA_FUNCTION_ON;
2668     }
2669 
2670     policyFlags |= POLICY_FLAG_TRUSTED;
2671 
2672     int32_t keyCode = args->keyCode;
2673     accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
2674 
2675     KeyEvent event;
2676     event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2677                      args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
2678 
2679     android::base::Timer t;
2680     mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2681     if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2682         ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2683               std::to_string(t.duration().count()).c_str());
2684     }
2685 
2686     bool needWake;
2687     { // acquire lock
2688         mLock.lock();
2689 
2690         if (shouldSendKeyToInputFilterLocked(args)) {
2691             mLock.unlock();
2692 
2693             policyFlags |= POLICY_FLAG_FILTERED;
2694             if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2695                 return; // event was consumed by the filter
2696             }
2697 
2698             mLock.lock();
2699         }
2700 
2701         KeyEntry* newEntry =
2702                 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2703                              args->displayId, policyFlags, args->action, flags, keyCode,
2704                              args->scanCode, metaState, repeatCount, args->downTime);
2705 
2706         needWake = enqueueInboundEventLocked(newEntry);
2707         mLock.unlock();
2708     } // release lock
2709 
2710     if (needWake) {
2711         mLooper->wake();
2712     }
2713 }
2714 
shouldSendKeyToInputFilterLocked(const NotifyKeyArgs * args)2715 bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2716     return mInputFilterEnabled;
2717 }
2718 
notifyMotion(const NotifyMotionArgs * args)2719 void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2720 #if DEBUG_INBOUND_EVENT_DETAILS
2721     ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2722           ", policyFlags=0x%x, "
2723           "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
2724           "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2725           args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2726           args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
2727           args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2728     for (uint32_t i = 0; i < args->pointerCount; i++) {
2729         ALOGD("  Pointer %d: id=%d, toolType=%d, "
2730               "x=%f, y=%f, pressure=%f, size=%f, "
2731               "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2732               "orientation=%f",
2733               i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2734               args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2735               args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2736               args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2737               args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2738               args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2739               args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2740               args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2741               args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2742               args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2743     }
2744 #endif
2745     if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2746                              args->pointerProperties)) {
2747         return;
2748     }
2749 
2750     uint32_t policyFlags = args->policyFlags;
2751     policyFlags |= POLICY_FLAG_TRUSTED;
2752 
2753     android::base::Timer t;
2754     mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
2755     if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2756         ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2757               std::to_string(t.duration().count()).c_str());
2758     }
2759 
2760     bool needWake;
2761     { // acquire lock
2762         mLock.lock();
2763 
2764         if (shouldSendMotionToInputFilterLocked(args)) {
2765             mLock.unlock();
2766 
2767             MotionEvent event;
2768             event.initialize(args->deviceId, args->source, args->displayId, args->action,
2769                              args->actionButton, args->flags, args->edgeFlags, args->metaState,
2770                              args->buttonState, args->classification, 0, 0, args->xPrecision,
2771                              args->yPrecision, args->downTime, args->eventTime, args->pointerCount,
2772                              args->pointerProperties, args->pointerCoords);
2773 
2774             policyFlags |= POLICY_FLAG_FILTERED;
2775             if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2776                 return; // event was consumed by the filter
2777             }
2778 
2779             mLock.lock();
2780         }
2781 
2782         // Just enqueue a new motion event.
2783         MotionEntry* newEntry =
2784                 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2785                                 args->displayId, policyFlags, args->action, args->actionButton,
2786                                 args->flags, args->metaState, args->buttonState,
2787                                 args->classification, args->edgeFlags, args->xPrecision,
2788                                 args->yPrecision, args->downTime, args->pointerCount,
2789                                 args->pointerProperties, args->pointerCoords, 0, 0);
2790 
2791         needWake = enqueueInboundEventLocked(newEntry);
2792         mLock.unlock();
2793     } // release lock
2794 
2795     if (needWake) {
2796         mLooper->wake();
2797     }
2798 }
2799 
shouldSendMotionToInputFilterLocked(const NotifyMotionArgs * args)2800 bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2801     return mInputFilterEnabled;
2802 }
2803 
notifySwitch(const NotifySwitchArgs * args)2804 void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2805 #if DEBUG_INBOUND_EVENT_DETAILS
2806     ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2807           "switchMask=0x%08x",
2808           args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
2809 #endif
2810 
2811     uint32_t policyFlags = args->policyFlags;
2812     policyFlags |= POLICY_FLAG_TRUSTED;
2813     mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
2814 }
2815 
notifyDeviceReset(const NotifyDeviceResetArgs * args)2816 void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2817 #if DEBUG_INBOUND_EVENT_DETAILS
2818     ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2819           args->deviceId);
2820 #endif
2821 
2822     bool needWake;
2823     { // acquire lock
2824         std::scoped_lock _l(mLock);
2825 
2826         DeviceResetEntry* newEntry =
2827                 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
2828         needWake = enqueueInboundEventLocked(newEntry);
2829     } // release lock
2830 
2831     if (needWake) {
2832         mLooper->wake();
2833     }
2834 }
2835 
injectInputEvent(const InputEvent * event,int32_t injectorPid,int32_t injectorUid,int32_t syncMode,int32_t timeoutMillis,uint32_t policyFlags)2836 int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2837                                           int32_t injectorUid, int32_t syncMode,
2838                                           int32_t timeoutMillis, uint32_t policyFlags) {
2839 #if DEBUG_INBOUND_EVENT_DETAILS
2840     ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
2841           "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2842           event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
2843 #endif
2844 
2845     nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2846 
2847     policyFlags |= POLICY_FLAG_INJECTED;
2848     if (hasInjectionPermission(injectorPid, injectorUid)) {
2849         policyFlags |= POLICY_FLAG_TRUSTED;
2850     }
2851 
2852     EventEntry* firstInjectedEntry;
2853     EventEntry* lastInjectedEntry;
2854     switch (event->getType()) {
2855         case AINPUT_EVENT_TYPE_KEY: {
2856             KeyEvent keyEvent;
2857             keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2858             int32_t action = keyEvent.getAction();
2859             if (!validateKeyEvent(action)) {
2860                 return INPUT_EVENT_INJECTION_FAILED;
2861             }
2862 
2863             int32_t flags = keyEvent.getFlags();
2864             int32_t keyCode = keyEvent.getKeyCode();
2865             int32_t metaState = keyEvent.getMetaState();
2866             accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2867                                     /*byref*/ keyCode, /*byref*/ metaState);
2868             keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2869                                 keyEvent.getDisplayId(), action, flags, keyCode,
2870                                 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2871                                 keyEvent.getDownTime(), keyEvent.getEventTime());
2872 
2873             if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2874                 policyFlags |= POLICY_FLAG_VIRTUAL;
2875             }
2876 
2877             if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2878                 android::base::Timer t;
2879                 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2880                 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2881                     ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2882                           std::to_string(t.duration().count()).c_str());
2883                 }
2884             }
2885 
2886             mLock.lock();
2887             firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2888                                               keyEvent.getEventTime(), keyEvent.getDeviceId(),
2889                                               keyEvent.getSource(), keyEvent.getDisplayId(),
2890                                               policyFlags, action, flags, keyEvent.getKeyCode(),
2891                                               keyEvent.getScanCode(), keyEvent.getMetaState(),
2892                                               keyEvent.getRepeatCount(), keyEvent.getDownTime());
2893             lastInjectedEntry = firstInjectedEntry;
2894             break;
2895         }
2896 
2897         case AINPUT_EVENT_TYPE_MOTION: {
2898             const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2899             int32_t action = motionEvent->getAction();
2900             size_t pointerCount = motionEvent->getPointerCount();
2901             const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2902             int32_t actionButton = motionEvent->getActionButton();
2903             int32_t displayId = motionEvent->getDisplayId();
2904             if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2905                 return INPUT_EVENT_INJECTION_FAILED;
2906             }
2907 
2908             if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2909                 nsecs_t eventTime = motionEvent->getEventTime();
2910                 android::base::Timer t;
2911                 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2912                 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2913                     ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2914                           std::to_string(t.duration().count()).c_str());
2915                 }
2916             }
2917 
2918             mLock.lock();
2919             const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2920             const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2921             firstInjectedEntry =
2922                     new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2923                                     motionEvent->getDeviceId(), motionEvent->getSource(),
2924                                     motionEvent->getDisplayId(), policyFlags, action, actionButton,
2925                                     motionEvent->getFlags(), motionEvent->getMetaState(),
2926                                     motionEvent->getButtonState(), motionEvent->getClassification(),
2927                                     motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2928                                     motionEvent->getYPrecision(), motionEvent->getDownTime(),
2929                                     uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2930                                     motionEvent->getXOffset(), motionEvent->getYOffset());
2931             lastInjectedEntry = firstInjectedEntry;
2932             for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2933                 sampleEventTimes += 1;
2934                 samplePointerCoords += pointerCount;
2935                 MotionEntry* nextInjectedEntry =
2936                         new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2937                                         motionEvent->getDeviceId(), motionEvent->getSource(),
2938                                         motionEvent->getDisplayId(), policyFlags, action,
2939                                         actionButton, motionEvent->getFlags(),
2940                                         motionEvent->getMetaState(), motionEvent->getButtonState(),
2941                                         motionEvent->getClassification(),
2942                                         motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2943                                         motionEvent->getYPrecision(), motionEvent->getDownTime(),
2944                                         uint32_t(pointerCount), pointerProperties,
2945                                         samplePointerCoords, motionEvent->getXOffset(),
2946                                         motionEvent->getYOffset());
2947                 lastInjectedEntry->next = nextInjectedEntry;
2948                 lastInjectedEntry = nextInjectedEntry;
2949             }
2950             break;
2951         }
2952 
2953         default:
2954             ALOGW("Cannot inject event of type %d", event->getType());
2955             return INPUT_EVENT_INJECTION_FAILED;
2956     }
2957 
2958     InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2959     if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2960         injectionState->injectionIsAsync = true;
2961     }
2962 
2963     injectionState->refCount += 1;
2964     lastInjectedEntry->injectionState = injectionState;
2965 
2966     bool needWake = false;
2967     for (EventEntry* entry = firstInjectedEntry; entry != nullptr;) {
2968         EventEntry* nextEntry = entry->next;
2969         needWake |= enqueueInboundEventLocked(entry);
2970         entry = nextEntry;
2971     }
2972 
2973     mLock.unlock();
2974 
2975     if (needWake) {
2976         mLooper->wake();
2977     }
2978 
2979     int32_t injectionResult;
2980     { // acquire lock
2981         std::unique_lock _l(mLock);
2982 
2983         if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2984             injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2985         } else {
2986             for (;;) {
2987                 injectionResult = injectionState->injectionResult;
2988                 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2989                     break;
2990                 }
2991 
2992                 nsecs_t remainingTimeout = endTime - now();
2993                 if (remainingTimeout <= 0) {
2994 #if DEBUG_INJECTION
2995                     ALOGD("injectInputEvent - Timed out waiting for injection result "
2996                           "to become available.");
2997 #endif
2998                     injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2999                     break;
3000                 }
3001 
3002                 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
3003             }
3004 
3005             if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3006                 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
3007                 while (injectionState->pendingForegroundDispatches != 0) {
3008 #if DEBUG_INJECTION
3009                     ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
3010                           injectionState->pendingForegroundDispatches);
3011 #endif
3012                     nsecs_t remainingTimeout = endTime - now();
3013                     if (remainingTimeout <= 0) {
3014 #if DEBUG_INJECTION
3015                         ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3016                               "dispatches to finish.");
3017 #endif
3018                         injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3019                         break;
3020                     }
3021 
3022                     mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
3023                 }
3024             }
3025         }
3026 
3027         injectionState->release();
3028     } // release lock
3029 
3030 #if DEBUG_INJECTION
3031     ALOGD("injectInputEvent - Finished with result %d.  "
3032           "injectorPid=%d, injectorUid=%d",
3033           injectionResult, injectorPid, injectorUid);
3034 #endif
3035 
3036     return injectionResult;
3037 }
3038 
hasInjectionPermission(int32_t injectorPid,int32_t injectorUid)3039 bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3040     return injectorUid == 0 ||
3041             mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3042 }
3043 
setInjectionResult(EventEntry * entry,int32_t injectionResult)3044 void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
3045     InjectionState* injectionState = entry->injectionState;
3046     if (injectionState) {
3047 #if DEBUG_INJECTION
3048         ALOGD("Setting input event injection result to %d.  "
3049               "injectorPid=%d, injectorUid=%d",
3050               injectionResult, injectionState->injectorPid, injectionState->injectorUid);
3051 #endif
3052 
3053         if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
3054             // Log the outcome since the injector did not wait for the injection result.
3055             switch (injectionResult) {
3056                 case INPUT_EVENT_INJECTION_SUCCEEDED:
3057                     ALOGV("Asynchronous input event injection succeeded.");
3058                     break;
3059                 case INPUT_EVENT_INJECTION_FAILED:
3060                     ALOGW("Asynchronous input event injection failed.");
3061                     break;
3062                 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3063                     ALOGW("Asynchronous input event injection permission denied.");
3064                     break;
3065                 case INPUT_EVENT_INJECTION_TIMED_OUT:
3066                     ALOGW("Asynchronous input event injection timed out.");
3067                     break;
3068             }
3069         }
3070 
3071         injectionState->injectionResult = injectionResult;
3072         mInjectionResultAvailable.notify_all();
3073     }
3074 }
3075 
incrementPendingForegroundDispatches(EventEntry * entry)3076 void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
3077     InjectionState* injectionState = entry->injectionState;
3078     if (injectionState) {
3079         injectionState->pendingForegroundDispatches += 1;
3080     }
3081 }
3082 
decrementPendingForegroundDispatches(EventEntry * entry)3083 void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
3084     InjectionState* injectionState = entry->injectionState;
3085     if (injectionState) {
3086         injectionState->pendingForegroundDispatches -= 1;
3087 
3088         if (injectionState->pendingForegroundDispatches == 0) {
3089             mInjectionSyncFinished.notify_all();
3090         }
3091     }
3092 }
3093 
getWindowHandlesLocked(int32_t displayId) const3094 std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3095         int32_t displayId) const {
3096     std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it =
3097             mWindowHandlesByDisplay.find(displayId);
3098     if (it != mWindowHandlesByDisplay.end()) {
3099         return it->second;
3100     }
3101 
3102     // Return an empty one if nothing found.
3103     return std::vector<sp<InputWindowHandle>>();
3104 }
3105 
getWindowHandleLocked(const sp<IBinder> & windowHandleToken) const3106 sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3107         const sp<IBinder>& windowHandleToken) const {
3108     for (auto& it : mWindowHandlesByDisplay) {
3109         const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3110         for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
3111             if (windowHandle->getToken() == windowHandleToken) {
3112                 return windowHandle;
3113             }
3114         }
3115     }
3116     return nullptr;
3117 }
3118 
hasWindowHandleLocked(const sp<InputWindowHandle> & windowHandle) const3119 bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3120     for (auto& it : mWindowHandlesByDisplay) {
3121         const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3122         for (const sp<InputWindowHandle>& handle : windowHandles) {
3123             if (handle->getToken() == windowHandle->getToken()) {
3124                 if (windowHandle->getInfo()->displayId != it.first) {
3125                     ALOGE("Found window %s in display %" PRId32
3126                           ", but it should belong to display %" PRId32,
3127                           windowHandle->getName().c_str(), it.first,
3128                           windowHandle->getInfo()->displayId);
3129                 }
3130                 return true;
3131             }
3132         }
3133     }
3134     return false;
3135 }
3136 
getInputChannelLocked(const sp<IBinder> & token) const3137 sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3138     size_t count = mInputChannelsByToken.count(token);
3139     if (count == 0) {
3140         return nullptr;
3141     }
3142     return mInputChannelsByToken.at(token);
3143 }
3144 
3145 /**
3146  * Called from InputManagerService, update window handle list by displayId that can receive input.
3147  * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3148  * If set an empty list, remove all handles from the specific display.
3149  * For focused handle, check if need to change and send a cancel event to previous one.
3150  * For removed handle, check if need to send a cancel event if already in touch.
3151  */
setInputWindows(const std::vector<sp<InputWindowHandle>> & inputWindowHandles,int32_t displayId,const sp<ISetInputWindowsListener> & setInputWindowsListener)3152 void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
3153                                       int32_t displayId,
3154                                       const sp<ISetInputWindowsListener>& setInputWindowsListener) {
3155 #if DEBUG_FOCUS
3156     ALOGD("setInputWindows displayId=%" PRId32, displayId);
3157 #endif
3158     { // acquire lock
3159         std::scoped_lock _l(mLock);
3160 
3161         // Copy old handles for release if they are no longer present.
3162         const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3163                 getWindowHandlesLocked(displayId);
3164 
3165         sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3166         bool foundHoveredWindow = false;
3167 
3168         if (inputWindowHandles.empty()) {
3169             // Remove all handles on a display if there are no windows left.
3170             mWindowHandlesByDisplay.erase(displayId);
3171         } else {
3172             // Since we compare the pointer of input window handles across window updates, we need
3173             // to make sure the handle object for the same window stays unchanged across updates.
3174             const std::vector<sp<InputWindowHandle>>& oldHandles =
3175                     mWindowHandlesByDisplay[displayId];
3176             std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3177             for (const sp<InputWindowHandle>& handle : oldHandles) {
3178                 oldHandlesByTokens[handle->getToken()] = handle;
3179             }
3180 
3181             std::vector<sp<InputWindowHandle>> newHandles;
3182             for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3183                 if (!handle->updateInfo()) {
3184                     // handle no longer valid
3185                     continue;
3186                 }
3187                 const InputWindowInfo* info = handle->getInfo();
3188 
3189                 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3190                      info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3191                     const bool noInputChannel =
3192                             info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3193                     const bool canReceiveInput =
3194                             !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3195                             !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3196                     if (canReceiveInput && !noInputChannel) {
3197                         ALOGE("Window handle %s has no registered input channel",
3198                               handle->getName().c_str());
3199                     }
3200                     continue;
3201                 }
3202 
3203                 if (info->displayId != displayId) {
3204                     ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3205                           handle->getName().c_str(), displayId, info->displayId);
3206                     continue;
3207                 }
3208 
3209                 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3210                     const sp<InputWindowHandle> oldHandle =
3211                             oldHandlesByTokens.at(handle->getToken());
3212                     oldHandle->updateFrom(handle);
3213                     newHandles.push_back(oldHandle);
3214                 } else {
3215                     newHandles.push_back(handle);
3216                 }
3217             }
3218 
3219             for (const sp<InputWindowHandle>& windowHandle : newHandles) {
3220                 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3221                 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3222                     windowHandle->getInfo()->visible) {
3223                     newFocusedWindowHandle = windowHandle;
3224                 }
3225                 if (windowHandle == mLastHoverWindowHandle) {
3226                     foundHoveredWindow = true;
3227                 }
3228             }
3229 
3230             // Insert or replace
3231             mWindowHandlesByDisplay[displayId] = newHandles;
3232         }
3233 
3234         if (!foundHoveredWindow) {
3235             mLastHoverWindowHandle = nullptr;
3236         }
3237 
3238         sp<InputWindowHandle> oldFocusedWindowHandle =
3239                 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3240 
3241         if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3242             if (oldFocusedWindowHandle != nullptr) {
3243 #if DEBUG_FOCUS
3244                 ALOGD("Focus left window: %s in display %" PRId32,
3245                       oldFocusedWindowHandle->getName().c_str(), displayId);
3246 #endif
3247                 sp<InputChannel> focusedInputChannel =
3248                         getInputChannelLocked(oldFocusedWindowHandle->getToken());
3249                 if (focusedInputChannel != nullptr) {
3250                     CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3251                                                "focus left window");
3252                     synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3253                 }
3254                 mFocusedWindowHandlesByDisplay.erase(displayId);
3255             }
3256             if (newFocusedWindowHandle != nullptr) {
3257 #if DEBUG_FOCUS
3258                 ALOGD("Focus entered window: %s in display %" PRId32,
3259                       newFocusedWindowHandle->getName().c_str(), displayId);
3260 #endif
3261                 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3262             }
3263 
3264             if (mFocusedDisplayId == displayId) {
3265                 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
3266             }
3267         }
3268 
3269         ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3270         if (stateIndex >= 0) {
3271             TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
3272             for (size_t i = 0; i < state.windows.size();) {
3273                 TouchedWindow& touchedWindow = state.windows[i];
3274                 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
3275 #if DEBUG_FOCUS
3276                     ALOGD("Touched window was removed: %s in display %" PRId32,
3277                           touchedWindow.windowHandle->getName().c_str(), displayId);
3278 #endif
3279                     sp<InputChannel> touchedInputChannel =
3280                             getInputChannelLocked(touchedWindow.windowHandle->getToken());
3281                     if (touchedInputChannel != nullptr) {
3282                         CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3283                                                    "touched window was removed");
3284                         synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3285                                                                          options);
3286                     }
3287                     state.windows.erase(state.windows.begin() + i);
3288                 } else {
3289                     ++i;
3290                 }
3291             }
3292         }
3293 
3294         // Release information for windows that are no longer present.
3295         // This ensures that unused input channels are released promptly.
3296         // Otherwise, they might stick around until the window handle is destroyed
3297         // which might not happen until the next GC.
3298         for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3299             if (!hasWindowHandleLocked(oldWindowHandle)) {
3300 #if DEBUG_FOCUS
3301                 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3302 #endif
3303                 oldWindowHandle->releaseChannel();
3304             }
3305         }
3306     } // release lock
3307 
3308     // Wake up poll loop since it may need to make new input dispatching choices.
3309     mLooper->wake();
3310 
3311     if (setInputWindowsListener) {
3312         setInputWindowsListener->onSetInputWindowsFinished();
3313     }
3314 }
3315 
setFocusedApplication(int32_t displayId,const sp<InputApplicationHandle> & inputApplicationHandle)3316 void InputDispatcher::setFocusedApplication(
3317         int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
3318 #if DEBUG_FOCUS
3319     ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
3320 #endif
3321     { // acquire lock
3322         std::scoped_lock _l(mLock);
3323 
3324         sp<InputApplicationHandle> oldFocusedApplicationHandle =
3325                 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
3326         if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
3327             if (oldFocusedApplicationHandle != inputApplicationHandle) {
3328                 if (oldFocusedApplicationHandle != nullptr) {
3329                     resetANRTimeoutsLocked();
3330                 }
3331                 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
3332             }
3333         } else if (oldFocusedApplicationHandle != nullptr) {
3334             resetANRTimeoutsLocked();
3335             oldFocusedApplicationHandle.clear();
3336             mFocusedApplicationHandlesByDisplay.erase(displayId);
3337         }
3338 
3339 #if DEBUG_FOCUS
3340         // logDispatchStateLocked();
3341 #endif
3342     } // release lock
3343 
3344     // Wake up poll loop since it may need to make new input dispatching choices.
3345     mLooper->wake();
3346 }
3347 
3348 /**
3349  * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3350  * the display not specified.
3351  *
3352  * We track any unreleased events for each window. If a window loses the ability to receive the
3353  * released event, we will send a cancel event to it. So when the focused display is changed, we
3354  * cancel all the unreleased display-unspecified events for the focused window on the old focused
3355  * display. The display-specified events won't be affected.
3356  */
setFocusedDisplay(int32_t displayId)3357 void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3358 #if DEBUG_FOCUS
3359     ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3360 #endif
3361     { // acquire lock
3362         std::scoped_lock _l(mLock);
3363 
3364         if (mFocusedDisplayId != displayId) {
3365             sp<InputWindowHandle> oldFocusedWindowHandle =
3366                     getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3367             if (oldFocusedWindowHandle != nullptr) {
3368                 sp<InputChannel> inputChannel =
3369                         getInputChannelLocked(oldFocusedWindowHandle->getToken());
3370                 if (inputChannel != nullptr) {
3371                     CancelationOptions
3372                             options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3373                                     "The display which contains this window no longer has focus.");
3374                     options.displayId = ADISPLAY_ID_NONE;
3375                     synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3376                 }
3377             }
3378             mFocusedDisplayId = displayId;
3379 
3380             // Sanity check
3381             sp<InputWindowHandle> newFocusedWindowHandle =
3382                     getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3383             onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
3384 
3385             if (newFocusedWindowHandle == nullptr) {
3386                 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3387                 if (!mFocusedWindowHandlesByDisplay.empty()) {
3388                     ALOGE("But another display has a focused window:");
3389                     for (auto& it : mFocusedWindowHandlesByDisplay) {
3390                         const int32_t displayId = it.first;
3391                         const sp<InputWindowHandle>& windowHandle = it.second;
3392                         ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3393                               windowHandle->getName().c_str());
3394                     }
3395                 }
3396             }
3397         }
3398 
3399 #if DEBUG_FOCUS
3400         logDispatchStateLocked();
3401 #endif
3402     } // release lock
3403 
3404     // Wake up poll loop since it may need to make new input dispatching choices.
3405     mLooper->wake();
3406 }
3407 
setInputDispatchMode(bool enabled,bool frozen)3408 void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3409 #if DEBUG_FOCUS
3410     ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3411 #endif
3412 
3413     bool changed;
3414     { // acquire lock
3415         std::scoped_lock _l(mLock);
3416 
3417         if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3418             if (mDispatchFrozen && !frozen) {
3419                 resetANRTimeoutsLocked();
3420             }
3421 
3422             if (mDispatchEnabled && !enabled) {
3423                 resetAndDropEverythingLocked("dispatcher is being disabled");
3424             }
3425 
3426             mDispatchEnabled = enabled;
3427             mDispatchFrozen = frozen;
3428             changed = true;
3429         } else {
3430             changed = false;
3431         }
3432 
3433 #if DEBUG_FOCUS
3434         logDispatchStateLocked();
3435 #endif
3436     } // release lock
3437 
3438     if (changed) {
3439         // Wake up poll loop since it may need to make new input dispatching choices.
3440         mLooper->wake();
3441     }
3442 }
3443 
setInputFilterEnabled(bool enabled)3444 void InputDispatcher::setInputFilterEnabled(bool enabled) {
3445 #if DEBUG_FOCUS
3446     ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3447 #endif
3448 
3449     { // acquire lock
3450         std::scoped_lock _l(mLock);
3451 
3452         if (mInputFilterEnabled == enabled) {
3453             return;
3454         }
3455 
3456         mInputFilterEnabled = enabled;
3457         resetAndDropEverythingLocked("input filter is being enabled or disabled");
3458     } // release lock
3459 
3460     // Wake up poll loop since there might be work to do to drop everything.
3461     mLooper->wake();
3462 }
3463 
transferTouchFocus(const sp<IBinder> & fromToken,const sp<IBinder> & toToken)3464 bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3465     if (fromToken == toToken) {
3466 #if DEBUG_FOCUS
3467         ALOGD("Trivial transfer to same window.");
3468 #endif
3469         return true;
3470     }
3471 
3472     { // acquire lock
3473         std::scoped_lock _l(mLock);
3474 
3475         sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3476         sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
3477         if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
3478             ALOGW("Cannot transfer focus because from or to window not found.");
3479             return false;
3480         }
3481 #if DEBUG_FOCUS
3482         ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3483               fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3484 #endif
3485         if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3486 #if DEBUG_FOCUS
3487             ALOGD("Cannot transfer focus because windows are on different displays.");
3488 #endif
3489             return false;
3490         }
3491 
3492         bool found = false;
3493         for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3494             TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3495             for (size_t i = 0; i < state.windows.size(); i++) {
3496                 const TouchedWindow& touchedWindow = state.windows[i];
3497                 if (touchedWindow.windowHandle == fromWindowHandle) {
3498                     int32_t oldTargetFlags = touchedWindow.targetFlags;
3499                     BitSet32 pointerIds = touchedWindow.pointerIds;
3500 
3501                     state.windows.erase(state.windows.begin() + i);
3502 
3503                     int32_t newTargetFlags = oldTargetFlags &
3504                             (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3505                              InputTarget::FLAG_DISPATCH_AS_IS);
3506                     state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
3507 
3508                     found = true;
3509                     goto Found;
3510                 }
3511             }
3512         }
3513     Found:
3514 
3515         if (!found) {
3516 #if DEBUG_FOCUS
3517             ALOGD("Focus transfer failed because from window did not have focus.");
3518 #endif
3519             return false;
3520         }
3521 
3522         sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3523         sp<InputChannel> toChannel = getInputChannelLocked(toToken);
3524         ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3525         ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3526         if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3527             sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3528             sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3529 
3530             fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3531             CancelationOptions
3532                     options(CancelationOptions::CANCEL_POINTER_EVENTS,
3533                             "transferring touch focus from this window to another window");
3534             synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3535         }
3536 
3537 #if DEBUG_FOCUS
3538         logDispatchStateLocked();
3539 #endif
3540     } // release lock
3541 
3542     // Wake up poll loop since it may need to make new input dispatching choices.
3543     mLooper->wake();
3544     return true;
3545 }
3546 
resetAndDropEverythingLocked(const char * reason)3547 void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3548 #if DEBUG_FOCUS
3549     ALOGD("Resetting and dropping all events (%s).", reason);
3550 #endif
3551 
3552     CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3553     synthesizeCancelationEventsForAllConnectionsLocked(options);
3554 
3555     resetKeyRepeatLocked();
3556     releasePendingEventLocked();
3557     drainInboundQueueLocked();
3558     resetANRTimeoutsLocked();
3559 
3560     mTouchStatesByDisplay.clear();
3561     mLastHoverWindowHandle.clear();
3562     mReplacedKeys.clear();
3563 }
3564 
logDispatchStateLocked()3565 void InputDispatcher::logDispatchStateLocked() {
3566     std::string dump;
3567     dumpDispatchStateLocked(dump);
3568 
3569     std::istringstream stream(dump);
3570     std::string line;
3571 
3572     while (std::getline(stream, line, '\n')) {
3573         ALOGD("%s", line.c_str());
3574     }
3575 }
3576 
dumpDispatchStateLocked(std::string & dump)3577 void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3578     dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3579     dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3580     dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
3581     dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
3582 
3583     if (!mFocusedApplicationHandlesByDisplay.empty()) {
3584         dump += StringPrintf(INDENT "FocusedApplications:\n");
3585         for (auto& it : mFocusedApplicationHandlesByDisplay) {
3586             const int32_t displayId = it.first;
3587             const sp<InputApplicationHandle>& applicationHandle = it.second;
3588             dump += StringPrintf(INDENT2 "displayId=%" PRId32
3589                                          ", name='%s', dispatchingTimeout=%0.3fms\n",
3590                                  displayId, applicationHandle->getName().c_str(),
3591                                  applicationHandle->getDispatchingTimeout(
3592                                          DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3593                                          1000000.0);
3594         }
3595     } else {
3596         dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
3597     }
3598 
3599     if (!mFocusedWindowHandlesByDisplay.empty()) {
3600         dump += StringPrintf(INDENT "FocusedWindows:\n");
3601         for (auto& it : mFocusedWindowHandlesByDisplay) {
3602             const int32_t displayId = it.first;
3603             const sp<InputWindowHandle>& windowHandle = it.second;
3604             dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3605                                  windowHandle->getName().c_str());
3606         }
3607     } else {
3608         dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3609     }
3610 
3611     if (!mTouchStatesByDisplay.isEmpty()) {
3612         dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
3613         for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3614             const TouchState& state = mTouchStatesByDisplay.valueAt(i);
3615             dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
3616                                  state.displayId, toString(state.down), toString(state.split),
3617                                  state.deviceId, state.source);
3618             if (!state.windows.empty()) {
3619                 dump += INDENT3 "Windows:\n";
3620                 for (size_t i = 0; i < state.windows.size(); i++) {
3621                     const TouchedWindow& touchedWindow = state.windows[i];
3622                     dump += StringPrintf(INDENT4
3623                                          "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3624                                          i, touchedWindow.windowHandle->getName().c_str(),
3625                                          touchedWindow.pointerIds.value, touchedWindow.targetFlags);
3626                 }
3627             } else {
3628                 dump += INDENT3 "Windows: <none>\n";
3629             }
3630             if (!state.portalWindows.empty()) {
3631                 dump += INDENT3 "Portal windows:\n";
3632                 for (size_t i = 0; i < state.portalWindows.size(); i++) {
3633                     const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
3634                     dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3635                                          portalWindowHandle->getName().c_str());
3636                 }
3637             }
3638         }
3639     } else {
3640         dump += INDENT "TouchStates: <no displays touched>\n";
3641     }
3642 
3643     if (!mWindowHandlesByDisplay.empty()) {
3644         for (auto& it : mWindowHandlesByDisplay) {
3645             const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3646             dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
3647             if (!windowHandles.empty()) {
3648                 dump += INDENT2 "Windows:\n";
3649                 for (size_t i = 0; i < windowHandles.size(); i++) {
3650                     const sp<InputWindowHandle>& windowHandle = windowHandles[i];
3651                     const InputWindowInfo* windowInfo = windowHandle->getInfo();
3652 
3653                     dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3654                                                  "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3655                                                  "hasWallpaper=%s, "
3656                                                  "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3657                                                  "type=0x%08x, layer=%d, "
3658                                                  "frame=[%d,%d][%d,%d], globalScale=%f, "
3659                                                  "windowScale=(%f,%f), "
3660                                                  "touchableRegion=",
3661                                          i, windowInfo->name.c_str(), windowInfo->displayId,
3662                                          windowInfo->portalToDisplayId,
3663                                          toString(windowInfo->paused),
3664                                          toString(windowInfo->hasFocus),
3665                                          toString(windowInfo->hasWallpaper),
3666                                          toString(windowInfo->visible),
3667                                          toString(windowInfo->canReceiveKeys),
3668                                          windowInfo->layoutParamsFlags,
3669                                          windowInfo->layoutParamsType, windowInfo->layer,
3670                                          windowInfo->frameLeft, windowInfo->frameTop,
3671                                          windowInfo->frameRight, windowInfo->frameBottom,
3672                                          windowInfo->globalScaleFactor, windowInfo->windowXScale,
3673                                          windowInfo->windowYScale);
3674                     dumpRegion(dump, windowInfo->touchableRegion);
3675                     dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3676                     dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3677                                          windowInfo->ownerPid, windowInfo->ownerUid,
3678                                          windowInfo->dispatchingTimeout / 1000000.0);
3679                 }
3680             } else {
3681                 dump += INDENT2 "Windows: <none>\n";
3682             }
3683         }
3684     } else {
3685         dump += INDENT "Displays: <none>\n";
3686     }
3687 
3688     if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
3689         for (auto& it : mGlobalMonitorsByDisplay) {
3690             const std::vector<Monitor>& monitors = it.second;
3691             dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3692             dumpMonitors(dump, monitors);
3693         }
3694         for (auto& it : mGestureMonitorsByDisplay) {
3695             const std::vector<Monitor>& monitors = it.second;
3696             dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3697             dumpMonitors(dump, monitors);
3698         }
3699     } else {
3700         dump += INDENT "Monitors: <none>\n";
3701     }
3702 
3703     nsecs_t currentTime = now();
3704 
3705     // Dump recently dispatched or dropped events from oldest to newest.
3706     if (!mRecentQueue.isEmpty()) {
3707         dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
3708         for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
3709             dump += INDENT2;
3710             entry->appendDescription(dump);
3711             dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
3712         }
3713     } else {
3714         dump += INDENT "RecentQueue: <empty>\n";
3715     }
3716 
3717     // Dump event currently being dispatched.
3718     if (mPendingEvent) {
3719         dump += INDENT "PendingEvent:\n";
3720         dump += INDENT2;
3721         mPendingEvent->appendDescription(dump);
3722         dump += StringPrintf(", age=%0.1fms\n",
3723                              (currentTime - mPendingEvent->eventTime) * 0.000001f);
3724     } else {
3725         dump += INDENT "PendingEvent: <none>\n";
3726     }
3727 
3728     // Dump inbound events from oldest to newest.
3729     if (!mInboundQueue.isEmpty()) {
3730         dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3731         for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3732             dump += INDENT2;
3733             entry->appendDescription(dump);
3734             dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
3735         }
3736     } else {
3737         dump += INDENT "InboundQueue: <empty>\n";
3738     }
3739 
3740     if (!mReplacedKeys.isEmpty()) {
3741         dump += INDENT "ReplacedKeys:\n";
3742         for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3743             const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3744             int32_t newKeyCode = mReplacedKeys.valueAt(i);
3745             dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3746                                  replacement.keyCode, replacement.deviceId, newKeyCode);
3747         }
3748     } else {
3749         dump += INDENT "ReplacedKeys: <empty>\n";
3750     }
3751 
3752     if (!mConnectionsByFd.isEmpty()) {
3753         dump += INDENT "Connections:\n";
3754         for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3755             const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3756             dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
3757                                          "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3758                                  i, connection->getInputChannelName().c_str(),
3759                                  connection->getWindowName().c_str(), connection->getStatusLabel(),
3760                                  toString(connection->monitor),
3761                                  toString(connection->inputPublisherBlocked));
3762 
3763             if (!connection->outboundQueue.isEmpty()) {
3764                 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
3765                                      connection->outboundQueue.count());
3766                 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3767                      entry = entry->next) {
3768                     dump.append(INDENT4);
3769                     entry->eventEntry->appendDescription(dump);
3770                     dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
3771                                          entry->targetFlags, entry->resolvedAction,
3772                                          (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3773                 }
3774             } else {
3775                 dump += INDENT3 "OutboundQueue: <empty>\n";
3776             }
3777 
3778             if (!connection->waitQueue.isEmpty()) {
3779                 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
3780                                      connection->waitQueue.count());
3781                 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3782                      entry = entry->next) {
3783                     dump += INDENT4;
3784                     entry->eventEntry->appendDescription(dump);
3785                     dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
3786                                          "age=%0.1fms, wait=%0.1fms\n",
3787                                          entry->targetFlags, entry->resolvedAction,
3788                                          (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3789                                          (currentTime - entry->deliveryTime) * 0.000001f);
3790                 }
3791             } else {
3792                 dump += INDENT3 "WaitQueue: <empty>\n";
3793             }
3794         }
3795     } else {
3796         dump += INDENT "Connections: <none>\n";
3797     }
3798 
3799     if (isAppSwitchPendingLocked()) {
3800         dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
3801                              (mAppSwitchDueTime - now()) / 1000000.0);
3802     } else {
3803         dump += INDENT "AppSwitch: not pending\n";
3804     }
3805 
3806     dump += INDENT "Configuration:\n";
3807     dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3808     dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3809                          mConfig.keyRepeatTimeout * 0.000001f);
3810 }
3811 
dumpMonitors(std::string & dump,const std::vector<Monitor> & monitors)3812 void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3813     const size_t numMonitors = monitors.size();
3814     for (size_t i = 0; i < numMonitors; i++) {
3815         const Monitor& monitor = monitors[i];
3816         const sp<InputChannel>& channel = monitor.inputChannel;
3817         dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3818         dump += "\n";
3819     }
3820 }
3821 
registerInputChannel(const sp<InputChannel> & inputChannel,int32_t displayId)3822 status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3823                                                int32_t displayId) {
3824 #if DEBUG_REGISTRATION
3825     ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3826           inputChannel->getName().c_str(), displayId);
3827 #endif
3828 
3829     { // acquire lock
3830         std::scoped_lock _l(mLock);
3831 
3832         if (getConnectionIndexLocked(inputChannel) >= 0) {
3833             ALOGW("Attempted to register already registered input channel '%s'",
3834                   inputChannel->getName().c_str());
3835             return BAD_VALUE;
3836         }
3837 
3838         sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
3839 
3840         int fd = inputChannel->getFd();
3841         mConnectionsByFd.add(fd, connection);
3842         mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
3843 
3844         mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3845     } // release lock
3846 
3847     // Wake the looper because some connections have changed.
3848     mLooper->wake();
3849     return OK;
3850 }
3851 
registerInputMonitor(const sp<InputChannel> & inputChannel,int32_t displayId,bool isGestureMonitor)3852 status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
3853                                                int32_t displayId, bool isGestureMonitor) {
3854     { // acquire lock
3855         std::scoped_lock _l(mLock);
3856 
3857         if (displayId < 0) {
3858             ALOGW("Attempted to register input monitor without a specified display.");
3859             return BAD_VALUE;
3860         }
3861 
3862         if (inputChannel->getToken() == nullptr) {
3863             ALOGW("Attempted to register input monitor without an identifying token.");
3864             return BAD_VALUE;
3865         }
3866 
3867         sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3868 
3869         const int fd = inputChannel->getFd();
3870         mConnectionsByFd.add(fd, connection);
3871         mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
3872 
3873         auto& monitorsByDisplay =
3874                 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
3875         monitorsByDisplay[displayId].emplace_back(inputChannel);
3876 
3877         mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3878     }
3879     // Wake the looper because some connections have changed.
3880     mLooper->wake();
3881     return OK;
3882 }
3883 
unregisterInputChannel(const sp<InputChannel> & inputChannel)3884 status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3885 #if DEBUG_REGISTRATION
3886     ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
3887 #endif
3888 
3889     { // acquire lock
3890         std::scoped_lock _l(mLock);
3891 
3892         status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3893         if (status) {
3894             return status;
3895         }
3896     } // release lock
3897 
3898     // Wake the poll loop because removing the connection may have changed the current
3899     // synchronization state.
3900     mLooper->wake();
3901     return OK;
3902 }
3903 
unregisterInputChannelLocked(const sp<InputChannel> & inputChannel,bool notify)3904 status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3905                                                        bool notify) {
3906     ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3907     if (connectionIndex < 0) {
3908         ALOGW("Attempted to unregister already unregistered input channel '%s'",
3909               inputChannel->getName().c_str());
3910         return BAD_VALUE;
3911     }
3912 
3913     sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3914     mConnectionsByFd.removeItemsAt(connectionIndex);
3915 
3916     mInputChannelsByToken.erase(inputChannel->getToken());
3917 
3918     if (connection->monitor) {
3919         removeMonitorChannelLocked(inputChannel);
3920     }
3921 
3922     mLooper->removeFd(inputChannel->getFd());
3923 
3924     nsecs_t currentTime = now();
3925     abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3926 
3927     connection->status = Connection::STATUS_ZOMBIE;
3928     return OK;
3929 }
3930 
removeMonitorChannelLocked(const sp<InputChannel> & inputChannel)3931 void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3932     removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3933     removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3934 }
3935 
removeMonitorChannelLocked(const sp<InputChannel> & inputChannel,std::unordered_map<int32_t,std::vector<Monitor>> & monitorsByDisplay)3936 void InputDispatcher::removeMonitorChannelLocked(
3937         const sp<InputChannel>& inputChannel,
3938         std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3939     for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
3940         std::vector<Monitor>& monitors = it->second;
3941         const size_t numMonitors = monitors.size();
3942         for (size_t i = 0; i < numMonitors; i++) {
3943             if (monitors[i].inputChannel == inputChannel) {
3944                 monitors.erase(monitors.begin() + i);
3945                 break;
3946             }
3947         }
3948         if (monitors.empty()) {
3949             it = monitorsByDisplay.erase(it);
3950         } else {
3951             ++it;
3952         }
3953     }
3954 }
3955 
pilferPointers(const sp<IBinder> & token)3956 status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
3957     { // acquire lock
3958         std::scoped_lock _l(mLock);
3959         std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
3960 
3961         if (!foundDisplayId) {
3962             ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
3963             return BAD_VALUE;
3964         }
3965         int32_t displayId = foundDisplayId.value();
3966 
3967         ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3968         if (stateIndex < 0) {
3969             ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
3970             return BAD_VALUE;
3971         }
3972 
3973         TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
3974         std::optional<int32_t> foundDeviceId;
3975         for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
3976             if (touchedMonitor.monitor.inputChannel->getToken() == token) {
3977                 foundDeviceId = state.deviceId;
3978             }
3979         }
3980         if (!foundDeviceId || !state.down) {
3981             ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
3982                   " Ignoring.");
3983             return BAD_VALUE;
3984         }
3985         int32_t deviceId = foundDeviceId.value();
3986 
3987         // Send cancel events to all the input channels we're stealing from.
3988         CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3989                                    "gesture monitor stole pointer stream");
3990         options.deviceId = deviceId;
3991         options.displayId = displayId;
3992         for (const TouchedWindow& window : state.windows) {
3993             sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
3994             synthesizeCancelationEventsForInputChannelLocked(channel, options);
3995         }
3996         // Then clear the current touch state so we stop dispatching to them as well.
3997         state.filterNonMonitors();
3998     }
3999     return OK;
4000 }
4001 
findGestureMonitorDisplayByTokenLocked(const sp<IBinder> & token)4002 std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4003         const sp<IBinder>& token) {
4004     for (const auto& it : mGestureMonitorsByDisplay) {
4005         const std::vector<Monitor>& monitors = it.second;
4006         for (const Monitor& monitor : monitors) {
4007             if (monitor.inputChannel->getToken() == token) {
4008                 return it.first;
4009             }
4010         }
4011     }
4012     return std::nullopt;
4013 }
4014 
getConnectionIndexLocked(const sp<InputChannel> & inputChannel)4015 ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
4016     if (inputChannel == nullptr) {
4017         return -1;
4018     }
4019 
4020     for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
4021         sp<Connection> connection = mConnectionsByFd.valueAt(i);
4022         if (connection->inputChannel->getToken() == inputChannel->getToken()) {
4023             return i;
4024         }
4025     }
4026 
4027     return -1;
4028 }
4029 
onDispatchCycleFinishedLocked(nsecs_t currentTime,const sp<Connection> & connection,uint32_t seq,bool handled)4030 void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4031                                                     const sp<Connection>& connection, uint32_t seq,
4032                                                     bool handled) {
4033     CommandEntry* commandEntry =
4034             postCommandLocked(&InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
4035     commandEntry->connection = connection;
4036     commandEntry->eventTime = currentTime;
4037     commandEntry->seq = seq;
4038     commandEntry->handled = handled;
4039 }
4040 
onDispatchCycleBrokenLocked(nsecs_t currentTime,const sp<Connection> & connection)4041 void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4042                                                   const sp<Connection>& connection) {
4043     ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
4044           connection->getInputChannelName().c_str());
4045 
4046     CommandEntry* commandEntry =
4047             postCommandLocked(&InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
4048     commandEntry->connection = connection;
4049 }
4050 
onFocusChangedLocked(const sp<InputWindowHandle> & oldFocus,const sp<InputWindowHandle> & newFocus)4051 void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
4052                                            const sp<InputWindowHandle>& newFocus) {
4053     sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4054     sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
4055     CommandEntry* commandEntry =
4056             postCommandLocked(&InputDispatcher::doNotifyFocusChangedLockedInterruptible);
4057     commandEntry->oldToken = oldToken;
4058     commandEntry->newToken = newToken;
4059 }
4060 
onANRLocked(nsecs_t currentTime,const sp<InputApplicationHandle> & applicationHandle,const sp<InputWindowHandle> & windowHandle,nsecs_t eventTime,nsecs_t waitStartTime,const char * reason)4061 void InputDispatcher::onANRLocked(nsecs_t currentTime,
4062                                   const sp<InputApplicationHandle>& applicationHandle,
4063                                   const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4064                                   nsecs_t waitStartTime, const char* reason) {
4065     float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4066     float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4067     ALOGI("Application is not responding: %s.  "
4068           "It has been %0.1fms since event, %0.1fms since wait started.  Reason: %s",
4069           getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4070           waitDuration, reason);
4071 
4072     // Capture a record of the InputDispatcher state at the time of the ANR.
4073     time_t t = time(nullptr);
4074     struct tm tm;
4075     localtime_r(&t, &tm);
4076     char timestr[64];
4077     strftime(timestr, sizeof(timestr), "%F %T", &tm);
4078     mLastANRState.clear();
4079     mLastANRState += INDENT "ANR:\n";
4080     mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4081     mLastANRState +=
4082             StringPrintf(INDENT2 "Window: %s\n",
4083                          getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
4084     mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4085     mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4086     mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
4087     dumpDispatchStateLocked(mLastANRState);
4088 
4089     CommandEntry* commandEntry =
4090             postCommandLocked(&InputDispatcher::doNotifyANRLockedInterruptible);
4091     commandEntry->inputApplicationHandle = applicationHandle;
4092     commandEntry->inputChannel =
4093             windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
4094     commandEntry->reason = reason;
4095 }
4096 
doNotifyConfigurationChangedLockedInterruptible(CommandEntry * commandEntry)4097 void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
4098     mLock.unlock();
4099 
4100     mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4101 
4102     mLock.lock();
4103 }
4104 
doNotifyInputChannelBrokenLockedInterruptible(CommandEntry * commandEntry)4105 void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
4106     sp<Connection> connection = commandEntry->connection;
4107 
4108     if (connection->status != Connection::STATUS_ZOMBIE) {
4109         mLock.unlock();
4110 
4111         mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
4112 
4113         mLock.lock();
4114     }
4115 }
4116 
doNotifyFocusChangedLockedInterruptible(CommandEntry * commandEntry)4117 void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
4118     sp<IBinder> oldToken = commandEntry->oldToken;
4119     sp<IBinder> newToken = commandEntry->newToken;
4120     mLock.unlock();
4121     mPolicy->notifyFocusChanged(oldToken, newToken);
4122     mLock.lock();
4123 }
4124 
doNotifyANRLockedInterruptible(CommandEntry * commandEntry)4125 void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
4126     mLock.unlock();
4127 
4128     nsecs_t newTimeout =
4129             mPolicy->notifyANR(commandEntry->inputApplicationHandle,
4130                                commandEntry->inputChannel ? commandEntry->inputChannel->getToken()
4131                                                           : nullptr,
4132                                commandEntry->reason);
4133 
4134     mLock.lock();
4135 
4136     resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
4137 }
4138 
doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry * commandEntry)4139 void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4140         CommandEntry* commandEntry) {
4141     KeyEntry* entry = commandEntry->keyEntry;
4142 
4143     KeyEvent event;
4144     initializeKeyEvent(&event, entry);
4145 
4146     mLock.unlock();
4147 
4148     android::base::Timer t;
4149     sp<IBinder> token = commandEntry->inputChannel != nullptr
4150             ? commandEntry->inputChannel->getToken()
4151             : nullptr;
4152     nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
4153     if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4154         ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
4155               std::to_string(t.duration().count()).c_str());
4156     }
4157 
4158     mLock.lock();
4159 
4160     if (delay < 0) {
4161         entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4162     } else if (!delay) {
4163         entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4164     } else {
4165         entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4166         entry->interceptKeyWakeupTime = now() + delay;
4167     }
4168     entry->release();
4169 }
4170 
doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry * commandEntry)4171 void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4172     mLock.unlock();
4173     mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4174     mLock.lock();
4175 }
4176 
doDispatchCycleFinishedLockedInterruptible(CommandEntry * commandEntry)4177 void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
4178     sp<Connection> connection = commandEntry->connection;
4179     nsecs_t finishTime = commandEntry->eventTime;
4180     uint32_t seq = commandEntry->seq;
4181     bool handled = commandEntry->handled;
4182 
4183     // Handle post-event policy actions.
4184     DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4185     if (dispatchEntry) {
4186         nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4187         if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4188             std::string msg =
4189                     StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4190                                  connection->getWindowName().c_str(), eventDuration * 0.000001f);
4191             dispatchEntry->eventEntry->appendDescription(msg);
4192             ALOGI("%s", msg.c_str());
4193         }
4194 
4195         bool restartEvent;
4196         if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4197             KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4198             restartEvent =
4199                     afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
4200         } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4201             MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4202             restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry,
4203                                                                motionEntry, handled);
4204         } else {
4205             restartEvent = false;
4206         }
4207 
4208         // Dequeue the event and start the next cycle.
4209         // Note that because the lock might have been released, it is possible that the
4210         // contents of the wait queue to have been drained, so we need to double-check
4211         // a few things.
4212         if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4213             connection->waitQueue.dequeue(dispatchEntry);
4214             traceWaitQueueLength(connection);
4215             if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4216                 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4217                 traceOutboundQueueLength(connection);
4218             } else {
4219                 releaseDispatchEntry(dispatchEntry);
4220             }
4221         }
4222 
4223         // Start the next dispatch cycle for this connection.
4224         startDispatchCycleLocked(now(), connection);
4225     }
4226 }
4227 
afterKeyEventLockedInterruptible(const sp<Connection> & connection,DispatchEntry * dispatchEntry,KeyEntry * keyEntry,bool handled)4228 bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4229                                                        DispatchEntry* dispatchEntry,
4230                                                        KeyEntry* keyEntry, bool handled) {
4231     if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4232         if (!handled) {
4233             // Report the key as unhandled, since the fallback was not handled.
4234             mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4235         }
4236         return false;
4237     }
4238 
4239     // Get the fallback key state.
4240     // Clear it out after dispatching the UP.
4241     int32_t originalKeyCode = keyEntry->keyCode;
4242     int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4243     if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4244         connection->inputState.removeFallbackKey(originalKeyCode);
4245     }
4246 
4247     if (handled || !dispatchEntry->hasForegroundTarget()) {
4248         // If the application handles the original key for which we previously
4249         // generated a fallback or if the window is not a foreground window,
4250         // then cancel the associated fallback key, if any.
4251         if (fallbackKeyCode != -1) {
4252             // Dispatch the unhandled key to the policy with the cancel flag.
4253 #if DEBUG_OUTBOUND_EVENT_DETAILS
4254             ALOGD("Unhandled key event: Asking policy to cancel fallback action.  "
4255                   "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4256                   keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4257                   keyEntry->policyFlags);
4258 #endif
4259             KeyEvent event;
4260             initializeKeyEvent(&event, keyEntry);
4261             event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
4262 
4263             mLock.unlock();
4264 
4265             mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4266                                           keyEntry->policyFlags, &event);
4267 
4268             mLock.lock();
4269 
4270             // Cancel the fallback key.
4271             if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
4272                 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4273                                            "application handled the original non-fallback key "
4274                                            "or is no longer a foreground target, "
4275                                            "canceling previously dispatched fallback key");
4276                 options.keyCode = fallbackKeyCode;
4277                 synthesizeCancelationEventsForConnectionLocked(connection, options);
4278             }
4279             connection->inputState.removeFallbackKey(originalKeyCode);
4280         }
4281     } else {
4282         // If the application did not handle a non-fallback key, first check
4283         // that we are in a good state to perform unhandled key event processing
4284         // Then ask the policy what to do with it.
4285         bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
4286         if (fallbackKeyCode == -1 && !initialDown) {
4287 #if DEBUG_OUTBOUND_EVENT_DETAILS
4288             ALOGD("Unhandled key event: Skipping unhandled key event processing "
4289                   "since this is not an initial down.  "
4290                   "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4291                   originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
4292 #endif
4293             return false;
4294         }
4295 
4296         // Dispatch the unhandled key to the policy.
4297 #if DEBUG_OUTBOUND_EVENT_DETAILS
4298         ALOGD("Unhandled key event: Asking policy to perform fallback action.  "
4299               "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4300               keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
4301 #endif
4302         KeyEvent event;
4303         initializeKeyEvent(&event, keyEntry);
4304 
4305         mLock.unlock();
4306 
4307         bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4308                                                       keyEntry->policyFlags, &event);
4309 
4310         mLock.lock();
4311 
4312         if (connection->status != Connection::STATUS_NORMAL) {
4313             connection->inputState.removeFallbackKey(originalKeyCode);
4314             return false;
4315         }
4316 
4317         // Latch the fallback keycode for this key on an initial down.
4318         // The fallback keycode cannot change at any other point in the lifecycle.
4319         if (initialDown) {
4320             if (fallback) {
4321                 fallbackKeyCode = event.getKeyCode();
4322             } else {
4323                 fallbackKeyCode = AKEYCODE_UNKNOWN;
4324             }
4325             connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4326         }
4327 
4328         ALOG_ASSERT(fallbackKeyCode != -1);
4329 
4330         // Cancel the fallback key if the policy decides not to send it anymore.
4331         // We will continue to dispatch the key to the policy but we will no
4332         // longer dispatch a fallback key to the application.
4333         if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4334             (!fallback || fallbackKeyCode != event.getKeyCode())) {
4335 #if DEBUG_OUTBOUND_EVENT_DETAILS
4336             if (fallback) {
4337                 ALOGD("Unhandled key event: Policy requested to send key %d"
4338                       "as a fallback for %d, but on the DOWN it had requested "
4339                       "to send %d instead.  Fallback canceled.",
4340                       event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4341             } else {
4342                 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4343                       "but on the DOWN it had requested to send %d.  "
4344                       "Fallback canceled.",
4345                       originalKeyCode, fallbackKeyCode);
4346             }
4347 #endif
4348 
4349             CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4350                                        "canceling fallback, policy no longer desires it");
4351             options.keyCode = fallbackKeyCode;
4352             synthesizeCancelationEventsForConnectionLocked(connection, options);
4353 
4354             fallback = false;
4355             fallbackKeyCode = AKEYCODE_UNKNOWN;
4356             if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4357                 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4358             }
4359         }
4360 
4361 #if DEBUG_OUTBOUND_EVENT_DETAILS
4362         {
4363             std::string msg;
4364             const KeyedVector<int32_t, int32_t>& fallbackKeys =
4365                     connection->inputState.getFallbackKeys();
4366             for (size_t i = 0; i < fallbackKeys.size(); i++) {
4367                 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
4368             }
4369             ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4370                   fallbackKeys.size(), msg.c_str());
4371         }
4372 #endif
4373 
4374         if (fallback) {
4375             // Restart the dispatch cycle using the fallback key.
4376             keyEntry->eventTime = event.getEventTime();
4377             keyEntry->deviceId = event.getDeviceId();
4378             keyEntry->source = event.getSource();
4379             keyEntry->displayId = event.getDisplayId();
4380             keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4381             keyEntry->keyCode = fallbackKeyCode;
4382             keyEntry->scanCode = event.getScanCode();
4383             keyEntry->metaState = event.getMetaState();
4384             keyEntry->repeatCount = event.getRepeatCount();
4385             keyEntry->downTime = event.getDownTime();
4386             keyEntry->syntheticRepeat = false;
4387 
4388 #if DEBUG_OUTBOUND_EVENT_DETAILS
4389             ALOGD("Unhandled key event: Dispatching fallback key.  "
4390                   "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4391                   originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4392 #endif
4393             return true; // restart the event
4394         } else {
4395 #if DEBUG_OUTBOUND_EVENT_DETAILS
4396             ALOGD("Unhandled key event: No fallback key.");
4397 #endif
4398 
4399             // Report the key as unhandled, since there is no fallback key.
4400             mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4401         }
4402     }
4403     return false;
4404 }
4405 
afterMotionEventLockedInterruptible(const sp<Connection> & connection,DispatchEntry * dispatchEntry,MotionEntry * motionEntry,bool handled)4406 bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4407                                                           DispatchEntry* dispatchEntry,
4408                                                           MotionEntry* motionEntry, bool handled) {
4409     return false;
4410 }
4411 
doPokeUserActivityLockedInterruptible(CommandEntry * commandEntry)4412 void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4413     mLock.unlock();
4414 
4415     mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4416 
4417     mLock.lock();
4418 }
4419 
initializeKeyEvent(KeyEvent * event,const KeyEntry * entry)4420 void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
4421     event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
4422                       entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4423                       entry->downTime, entry->eventTime);
4424 }
4425 
updateDispatchStatistics(nsecs_t currentTime,const EventEntry * entry,int32_t injectionResult,nsecs_t timeSpentWaitingForApplication)4426 void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
4427                                                int32_t injectionResult,
4428                                                nsecs_t timeSpentWaitingForApplication) {
4429     // TODO Write some statistics about how long we spend waiting.
4430 }
4431 
traceInboundQueueLengthLocked()4432 void InputDispatcher::traceInboundQueueLengthLocked() {
4433     if (ATRACE_ENABLED()) {
4434         ATRACE_INT("iq", mInboundQueue.count());
4435     }
4436 }
4437 
traceOutboundQueueLength(const sp<Connection> & connection)4438 void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
4439     if (ATRACE_ENABLED()) {
4440         char counterName[40];
4441         snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
4442         ATRACE_INT(counterName, connection->outboundQueue.count());
4443     }
4444 }
4445 
traceWaitQueueLength(const sp<Connection> & connection)4446 void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
4447     if (ATRACE_ENABLED()) {
4448         char counterName[40];
4449         snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
4450         ATRACE_INT(counterName, connection->waitQueue.count());
4451     }
4452 }
4453 
dump(std::string & dump)4454 void InputDispatcher::dump(std::string& dump) {
4455     std::scoped_lock _l(mLock);
4456 
4457     dump += "Input Dispatcher State:\n";
4458     dumpDispatchStateLocked(dump);
4459 
4460     if (!mLastANRState.empty()) {
4461         dump += "\nInput Dispatcher State at time of last ANR:\n";
4462         dump += mLastANRState;
4463     }
4464 }
4465 
monitor()4466 void InputDispatcher::monitor() {
4467     // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4468     std::unique_lock _l(mLock);
4469     mLooper->wake();
4470     mDispatcherIsAlive.wait(_l);
4471 }
4472 
4473 } // namespace android::inputdispatcher
4474