1 /*
2  * Copyright (C) 2005 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 #include <assert.h>
18 #include <dirent.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <inttypes.h>
22 #include <memory.h>
23 #include <stdint.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/capability.h>
28 #include <sys/epoll.h>
29 #include <sys/inotify.h>
30 #include <sys/ioctl.h>
31 #include <sys/limits.h>
32 #include <unistd.h>
33 
34 #define LOG_TAG "EventHub"
35 
36 // #define LOG_NDEBUG 0
37 
38 #include "EventHub.h"
39 
40 #include <android-base/stringprintf.h>
41 #include <cutils/properties.h>
42 #include <openssl/sha.h>
43 #include <utils/Errors.h>
44 #include <utils/Log.h>
45 #include <utils/Timers.h>
46 #include <utils/threads.h>
47 
48 #include <input/KeyCharacterMap.h>
49 #include <input/KeyLayoutMap.h>
50 #include <input/VirtualKeyMap.h>
51 
52 /* this macro is used to tell if "bit" is set in "array"
53  * it selects a byte from the array, and does a boolean AND
54  * operation with a byte that only has the relevant bit set.
55  * eg. to check for the 12th bit, we do (array[1] & 1<<4)
56  */
57 #define test_bit(bit, array) ((array)[(bit) / 8] & (1 << ((bit) % 8)))
58 
59 /* this macro computes the number of bytes needed to represent a bit array of the specified size */
60 #define sizeof_bit_array(bits) (((bits) + 7) / 8)
61 
62 #define INDENT "  "
63 #define INDENT2 "    "
64 #define INDENT3 "      "
65 
66 using android::base::StringPrintf;
67 
68 namespace android {
69 
70 static constexpr bool DEBUG = false;
71 
72 static const char* DEVICE_PATH = "/dev/input";
73 // v4l2 devices go directly into /dev
74 static const char* VIDEO_DEVICE_PATH = "/dev";
75 
toString(bool value)76 static inline const char* toString(bool value) {
77     return value ? "true" : "false";
78 }
79 
sha1(const std::string & in)80 static std::string sha1(const std::string& in) {
81     SHA_CTX ctx;
82     SHA1_Init(&ctx);
83     SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
84     u_char digest[SHA_DIGEST_LENGTH];
85     SHA1_Final(digest, &ctx);
86 
87     std::string out;
88     for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
89         out += StringPrintf("%02x", digest[i]);
90     }
91     return out;
92 }
93 
94 /**
95  * Return true if name matches "v4l-touch*"
96  */
isV4lTouchNode(const char * name)97 static bool isV4lTouchNode(const char* name) {
98     return strstr(name, "v4l-touch") == name;
99 }
100 
101 /**
102  * Returns true if V4L devices should be scanned.
103  *
104  * The system property ro.input.video_enabled can be used to control whether
105  * EventHub scans and opens V4L devices. As V4L does not support multiple
106  * clients, EventHub effectively blocks access to these devices when it opens
107  * them.
108  *
109  * Setting this to "false" would prevent any video devices from being discovered and
110  * associated with input devices.
111  *
112  * This property can be used as follows:
113  * 1. To turn off features that are dependent on video device presence.
114  * 2. During testing and development, to allow other clients to read video devices
115  * directly from /dev.
116  */
isV4lScanningEnabled()117 static bool isV4lScanningEnabled() {
118     return property_get_bool("ro.input.video_enabled", true /* default_value */);
119 }
120 
processEventTimestamp(const struct input_event & event)121 static nsecs_t processEventTimestamp(const struct input_event& event) {
122     // Use the time specified in the event instead of the current time
123     // so that downstream code can get more accurate estimates of
124     // event dispatch latency from the time the event is enqueued onto
125     // the evdev client buffer.
126     //
127     // The event's timestamp fortuitously uses the same monotonic clock
128     // time base as the rest of Android. The kernel event device driver
129     // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
130     // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
131     // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
132     // system call that also queries ktime_get_ts().
133 
134     const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
135             microseconds_to_nanoseconds(event.time.tv_usec);
136     return inputEventTime;
137 }
138 
139 // --- Global Functions ---
140 
getAbsAxisUsage(int32_t axis,uint32_t deviceClasses)141 uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
142     // Touch devices get dibs on touch-related axes.
143     if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
144         switch (axis) {
145             case ABS_X:
146             case ABS_Y:
147             case ABS_PRESSURE:
148             case ABS_TOOL_WIDTH:
149             case ABS_DISTANCE:
150             case ABS_TILT_X:
151             case ABS_TILT_Y:
152             case ABS_MT_SLOT:
153             case ABS_MT_TOUCH_MAJOR:
154             case ABS_MT_TOUCH_MINOR:
155             case ABS_MT_WIDTH_MAJOR:
156             case ABS_MT_WIDTH_MINOR:
157             case ABS_MT_ORIENTATION:
158             case ABS_MT_POSITION_X:
159             case ABS_MT_POSITION_Y:
160             case ABS_MT_TOOL_TYPE:
161             case ABS_MT_BLOB_ID:
162             case ABS_MT_TRACKING_ID:
163             case ABS_MT_PRESSURE:
164             case ABS_MT_DISTANCE:
165                 return INPUT_DEVICE_CLASS_TOUCH;
166         }
167     }
168 
169     // External stylus gets the pressure axis
170     if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
171         if (axis == ABS_PRESSURE) {
172             return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
173         }
174     }
175 
176     // Joystick devices get the rest.
177     return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
178 }
179 
180 // --- EventHub::Device ---
181 
Device(int fd,int32_t id,const std::string & path,const InputDeviceIdentifier & identifier)182 EventHub::Device::Device(int fd, int32_t id, const std::string& path,
183                          const InputDeviceIdentifier& identifier)
184       : next(nullptr),
185         fd(fd),
186         id(id),
187         path(path),
188         identifier(identifier),
189         classes(0),
190         configuration(nullptr),
191         virtualKeyMap(nullptr),
192         ffEffectPlaying(false),
193         ffEffectId(-1),
194         controllerNumber(0),
195         enabled(true),
196         isVirtual(fd < 0) {
197     memset(keyBitmask, 0, sizeof(keyBitmask));
198     memset(absBitmask, 0, sizeof(absBitmask));
199     memset(relBitmask, 0, sizeof(relBitmask));
200     memset(swBitmask, 0, sizeof(swBitmask));
201     memset(ledBitmask, 0, sizeof(ledBitmask));
202     memset(ffBitmask, 0, sizeof(ffBitmask));
203     memset(propBitmask, 0, sizeof(propBitmask));
204 }
205 
~Device()206 EventHub::Device::~Device() {
207     close();
208     delete configuration;
209 }
210 
close()211 void EventHub::Device::close() {
212     if (fd >= 0) {
213         ::close(fd);
214         fd = -1;
215     }
216 }
217 
enable()218 status_t EventHub::Device::enable() {
219     fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
220     if (fd < 0) {
221         ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
222         return -errno;
223     }
224     enabled = true;
225     return OK;
226 }
227 
disable()228 status_t EventHub::Device::disable() {
229     close();
230     enabled = false;
231     return OK;
232 }
233 
hasValidFd()234 bool EventHub::Device::hasValidFd() {
235     return !isVirtual && enabled;
236 }
237 
238 /**
239  * Get the capabilities for the current process.
240  * Crashes the system if unable to create / check / destroy the capabilities object.
241  */
242 class Capabilities final {
243 public:
Capabilities()244     explicit Capabilities() {
245         mCaps = cap_get_proc();
246         LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
247     }
248 
249     /**
250      * Check whether the current process has a specific capability
251      * in the set of effective capabilities.
252      * Return CAP_SET if the process has the requested capability
253      * Return CAP_CLEAR otherwise.
254      */
checkEffectiveCapability(cap_value_t capability)255     cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
256         cap_flag_value_t value;
257         const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
258         LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
259         return value;
260     }
261 
~Capabilities()262     ~Capabilities() {
263         const int result = cap_free(mCaps);
264         LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
265     }
266 
267 private:
268     cap_t mCaps;
269 };
270 
ensureProcessCanBlockSuspend()271 static void ensureProcessCanBlockSuspend() {
272     Capabilities capabilities;
273     const bool canBlockSuspend =
274             capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
275     LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
276                         "Input must be able to block suspend to properly process events");
277 }
278 
279 // --- EventHub ---
280 
281 const int EventHub::EPOLL_MAX_EVENTS;
282 
EventHub(void)283 EventHub::EventHub(void)
284       : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
285         mNextDeviceId(1),
286         mControllerNumbers(),
287         mOpeningDevices(nullptr),
288         mClosingDevices(nullptr),
289         mNeedToSendFinishedDeviceScan(false),
290         mNeedToReopenDevices(false),
291         mNeedToScanDevices(true),
292         mPendingEventCount(0),
293         mPendingEventIndex(0),
294         mPendingINotify(false) {
295     ensureProcessCanBlockSuspend();
296 
297     mEpollFd = epoll_create1(EPOLL_CLOEXEC);
298     LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
299 
300     mINotifyFd = inotify_init();
301     mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
302     LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
303                         strerror(errno));
304     if (isV4lScanningEnabled()) {
305         mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
306         LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
307                             VIDEO_DEVICE_PATH, strerror(errno));
308     } else {
309         mVideoWd = -1;
310         ALOGI("Video device scanning disabled");
311     }
312 
313     struct epoll_event eventItem = {};
314     eventItem.events = EPOLLIN | EPOLLWAKEUP;
315     eventItem.data.fd = mINotifyFd;
316     int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
317     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance.  errno=%d", errno);
318 
319     int wakeFds[2];
320     result = pipe(wakeFds);
321     LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe.  errno=%d", errno);
322 
323     mWakeReadPipeFd = wakeFds[0];
324     mWakeWritePipeFd = wakeFds[1];
325 
326     result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
327     LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking.  errno=%d",
328                         errno);
329 
330     result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
331     LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking.  errno=%d",
332                         errno);
333 
334     eventItem.data.fd = mWakeReadPipeFd;
335     result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
336     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance.  errno=%d",
337                         errno);
338 }
339 
~EventHub(void)340 EventHub::~EventHub(void) {
341     closeAllDevicesLocked();
342 
343     while (mClosingDevices) {
344         Device* device = mClosingDevices;
345         mClosingDevices = device->next;
346         delete device;
347     }
348 
349     ::close(mEpollFd);
350     ::close(mINotifyFd);
351     ::close(mWakeReadPipeFd);
352     ::close(mWakeWritePipeFd);
353 }
354 
getDeviceIdentifier(int32_t deviceId) const355 InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
356     AutoMutex _l(mLock);
357     Device* device = getDeviceLocked(deviceId);
358     if (device == nullptr) return InputDeviceIdentifier();
359     return device->identifier;
360 }
361 
getDeviceClasses(int32_t deviceId) const362 uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
363     AutoMutex _l(mLock);
364     Device* device = getDeviceLocked(deviceId);
365     if (device == nullptr) return 0;
366     return device->classes;
367 }
368 
getDeviceControllerNumber(int32_t deviceId) const369 int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
370     AutoMutex _l(mLock);
371     Device* device = getDeviceLocked(deviceId);
372     if (device == nullptr) return 0;
373     return device->controllerNumber;
374 }
375 
getConfiguration(int32_t deviceId,PropertyMap * outConfiguration) const376 void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
377     AutoMutex _l(mLock);
378     Device* device = getDeviceLocked(deviceId);
379     if (device && device->configuration) {
380         *outConfiguration = *device->configuration;
381     } else {
382         outConfiguration->clear();
383     }
384 }
385 
getAbsoluteAxisInfo(int32_t deviceId,int axis,RawAbsoluteAxisInfo * outAxisInfo) const386 status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
387                                        RawAbsoluteAxisInfo* outAxisInfo) const {
388     outAxisInfo->clear();
389 
390     if (axis >= 0 && axis <= ABS_MAX) {
391         AutoMutex _l(mLock);
392 
393         Device* device = getDeviceLocked(deviceId);
394         if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
395             struct input_absinfo info;
396             if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
397                 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
398                       device->identifier.name.c_str(), device->fd, errno);
399                 return -errno;
400             }
401 
402             if (info.minimum != info.maximum) {
403                 outAxisInfo->valid = true;
404                 outAxisInfo->minValue = info.minimum;
405                 outAxisInfo->maxValue = info.maximum;
406                 outAxisInfo->flat = info.flat;
407                 outAxisInfo->fuzz = info.fuzz;
408                 outAxisInfo->resolution = info.resolution;
409             }
410             return OK;
411         }
412     }
413     return -1;
414 }
415 
hasRelativeAxis(int32_t deviceId,int axis) const416 bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
417     if (axis >= 0 && axis <= REL_MAX) {
418         AutoMutex _l(mLock);
419 
420         Device* device = getDeviceLocked(deviceId);
421         if (device) {
422             return test_bit(axis, device->relBitmask);
423         }
424     }
425     return false;
426 }
427 
hasInputProperty(int32_t deviceId,int property) const428 bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
429     if (property >= 0 && property <= INPUT_PROP_MAX) {
430         AutoMutex _l(mLock);
431 
432         Device* device = getDeviceLocked(deviceId);
433         if (device) {
434             return test_bit(property, device->propBitmask);
435         }
436     }
437     return false;
438 }
439 
getScanCodeState(int32_t deviceId,int32_t scanCode) const440 int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
441     if (scanCode >= 0 && scanCode <= KEY_MAX) {
442         AutoMutex _l(mLock);
443 
444         Device* device = getDeviceLocked(deviceId);
445         if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
446             uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
447             memset(keyState, 0, sizeof(keyState));
448             if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
449                 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
450             }
451         }
452     }
453     return AKEY_STATE_UNKNOWN;
454 }
455 
getKeyCodeState(int32_t deviceId,int32_t keyCode) const456 int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
457     AutoMutex _l(mLock);
458 
459     Device* device = getDeviceLocked(deviceId);
460     if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
461         std::vector<int32_t> scanCodes;
462         device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
463         if (scanCodes.size() != 0) {
464             uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
465             memset(keyState, 0, sizeof(keyState));
466             if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
467                 for (size_t i = 0; i < scanCodes.size(); i++) {
468                     int32_t sc = scanCodes[i];
469                     if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
470                         return AKEY_STATE_DOWN;
471                     }
472                 }
473                 return AKEY_STATE_UP;
474             }
475         }
476     }
477     return AKEY_STATE_UNKNOWN;
478 }
479 
getSwitchState(int32_t deviceId,int32_t sw) const480 int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
481     if (sw >= 0 && sw <= SW_MAX) {
482         AutoMutex _l(mLock);
483 
484         Device* device = getDeviceLocked(deviceId);
485         if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
486             uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
487             memset(swState, 0, sizeof(swState));
488             if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
489                 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
490             }
491         }
492     }
493     return AKEY_STATE_UNKNOWN;
494 }
495 
getAbsoluteAxisValue(int32_t deviceId,int32_t axis,int32_t * outValue) const496 status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
497     *outValue = 0;
498 
499     if (axis >= 0 && axis <= ABS_MAX) {
500         AutoMutex _l(mLock);
501 
502         Device* device = getDeviceLocked(deviceId);
503         if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
504             struct input_absinfo info;
505             if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
506                 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
507                       device->identifier.name.c_str(), device->fd, errno);
508                 return -errno;
509             }
510 
511             *outValue = info.value;
512             return OK;
513         }
514     }
515     return -1;
516 }
517 
markSupportedKeyCodes(int32_t deviceId,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags) const518 bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
519                                      uint8_t* outFlags) const {
520     AutoMutex _l(mLock);
521 
522     Device* device = getDeviceLocked(deviceId);
523     if (device && device->keyMap.haveKeyLayout()) {
524         std::vector<int32_t> scanCodes;
525         for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
526             scanCodes.clear();
527 
528             status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
529                                                                             &scanCodes);
530             if (!err) {
531                 // check the possible scan codes identified by the layout map against the
532                 // map of codes actually emitted by the driver
533                 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
534                     if (test_bit(scanCodes[sc], device->keyBitmask)) {
535                         outFlags[codeIndex] = 1;
536                         break;
537                     }
538                 }
539             }
540         }
541         return true;
542     }
543     return false;
544 }
545 
mapKey(int32_t deviceId,int32_t scanCode,int32_t usageCode,int32_t metaState,int32_t * outKeycode,int32_t * outMetaState,uint32_t * outFlags) const546 status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
547                           int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
548     AutoMutex _l(mLock);
549     Device* device = getDeviceLocked(deviceId);
550     status_t status = NAME_NOT_FOUND;
551 
552     if (device) {
553         // Check the key character map first.
554         sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
555         if (kcm != nullptr) {
556             if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
557                 *outFlags = 0;
558                 status = NO_ERROR;
559             }
560         }
561 
562         // Check the key layout next.
563         if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
564             if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
565                 status = NO_ERROR;
566             }
567         }
568 
569         if (status == NO_ERROR) {
570             if (kcm != nullptr) {
571                 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
572             } else {
573                 *outMetaState = metaState;
574             }
575         }
576     }
577 
578     if (status != NO_ERROR) {
579         *outKeycode = 0;
580         *outFlags = 0;
581         *outMetaState = metaState;
582     }
583 
584     return status;
585 }
586 
mapAxis(int32_t deviceId,int32_t scanCode,AxisInfo * outAxisInfo) const587 status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
588     AutoMutex _l(mLock);
589     Device* device = getDeviceLocked(deviceId);
590 
591     if (device && device->keyMap.haveKeyLayout()) {
592         status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
593         if (err == NO_ERROR) {
594             return NO_ERROR;
595         }
596     }
597 
598     return NAME_NOT_FOUND;
599 }
600 
setExcludedDevices(const std::vector<std::string> & devices)601 void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
602     AutoMutex _l(mLock);
603 
604     mExcludedDevices = devices;
605 }
606 
hasScanCode(int32_t deviceId,int32_t scanCode) const607 bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
608     AutoMutex _l(mLock);
609     Device* device = getDeviceLocked(deviceId);
610     if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
611         if (test_bit(scanCode, device->keyBitmask)) {
612             return true;
613         }
614     }
615     return false;
616 }
617 
hasLed(int32_t deviceId,int32_t led) const618 bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
619     AutoMutex _l(mLock);
620     Device* device = getDeviceLocked(deviceId);
621     int32_t sc;
622     if (device && mapLed(device, led, &sc) == NO_ERROR) {
623         if (test_bit(sc, device->ledBitmask)) {
624             return true;
625         }
626     }
627     return false;
628 }
629 
setLedState(int32_t deviceId,int32_t led,bool on)630 void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
631     AutoMutex _l(mLock);
632     Device* device = getDeviceLocked(deviceId);
633     setLedStateLocked(device, led, on);
634 }
635 
setLedStateLocked(Device * device,int32_t led,bool on)636 void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
637     int32_t sc;
638     if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
639         struct input_event ev;
640         ev.time.tv_sec = 0;
641         ev.time.tv_usec = 0;
642         ev.type = EV_LED;
643         ev.code = sc;
644         ev.value = on ? 1 : 0;
645 
646         ssize_t nWrite;
647         do {
648             nWrite = write(device->fd, &ev, sizeof(struct input_event));
649         } while (nWrite == -1 && errno == EINTR);
650     }
651 }
652 
getVirtualKeyDefinitions(int32_t deviceId,std::vector<VirtualKeyDefinition> & outVirtualKeys) const653 void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
654                                         std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
655     outVirtualKeys.clear();
656 
657     AutoMutex _l(mLock);
658     Device* device = getDeviceLocked(deviceId);
659     if (device && device->virtualKeyMap) {
660         const std::vector<VirtualKeyDefinition> virtualKeys =
661                 device->virtualKeyMap->getVirtualKeys();
662         outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
663     }
664 }
665 
getKeyCharacterMap(int32_t deviceId) const666 sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
667     AutoMutex _l(mLock);
668     Device* device = getDeviceLocked(deviceId);
669     if (device) {
670         return device->getKeyCharacterMap();
671     }
672     return nullptr;
673 }
674 
setKeyboardLayoutOverlay(int32_t deviceId,const sp<KeyCharacterMap> & map)675 bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) {
676     AutoMutex _l(mLock);
677     Device* device = getDeviceLocked(deviceId);
678     if (device) {
679         if (map != device->overlayKeyMap) {
680             device->overlayKeyMap = map;
681             device->combinedKeyMap = KeyCharacterMap::combine(device->keyMap.keyCharacterMap, map);
682             return true;
683         }
684     }
685     return false;
686 }
687 
generateDescriptor(InputDeviceIdentifier & identifier)688 static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
689     std::string rawDescriptor;
690     rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
691     // TODO add handling for USB devices to not uniqueify kbs that show up twice
692     if (!identifier.uniqueId.empty()) {
693         rawDescriptor += "uniqueId:";
694         rawDescriptor += identifier.uniqueId;
695     } else if (identifier.nonce != 0) {
696         rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
697     }
698 
699     if (identifier.vendor == 0 && identifier.product == 0) {
700         // If we don't know the vendor and product id, then the device is probably
701         // built-in so we need to rely on other information to uniquely identify
702         // the input device.  Usually we try to avoid relying on the device name or
703         // location but for built-in input device, they are unlikely to ever change.
704         if (!identifier.name.empty()) {
705             rawDescriptor += "name:";
706             rawDescriptor += identifier.name;
707         } else if (!identifier.location.empty()) {
708             rawDescriptor += "location:";
709             rawDescriptor += identifier.location;
710         }
711     }
712     identifier.descriptor = sha1(rawDescriptor);
713     return rawDescriptor;
714 }
715 
assignDescriptorLocked(InputDeviceIdentifier & identifier)716 void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
717     // Compute a device descriptor that uniquely identifies the device.
718     // The descriptor is assumed to be a stable identifier.  Its value should not
719     // change between reboots, reconnections, firmware updates or new releases
720     // of Android. In practice we sometimes get devices that cannot be uniquely
721     // identified. In this case we enforce uniqueness between connected devices.
722     // Ideally, we also want the descriptor to be short and relatively opaque.
723 
724     identifier.nonce = 0;
725     std::string rawDescriptor = generateDescriptor(identifier);
726     if (identifier.uniqueId.empty()) {
727         // If it didn't have a unique id check for conflicts and enforce
728         // uniqueness if necessary.
729         while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
730             identifier.nonce++;
731             rawDescriptor = generateDescriptor(identifier);
732         }
733     }
734     ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
735           identifier.descriptor.c_str());
736 }
737 
vibrate(int32_t deviceId,nsecs_t duration)738 void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
739     AutoMutex _l(mLock);
740     Device* device = getDeviceLocked(deviceId);
741     if (device && device->hasValidFd()) {
742         ff_effect effect;
743         memset(&effect, 0, sizeof(effect));
744         effect.type = FF_RUMBLE;
745         effect.id = device->ffEffectId;
746         effect.u.rumble.strong_magnitude = 0xc000;
747         effect.u.rumble.weak_magnitude = 0xc000;
748         effect.replay.length = (duration + 999999LL) / 1000000LL;
749         effect.replay.delay = 0;
750         if (ioctl(device->fd, EVIOCSFF, &effect)) {
751             ALOGW("Could not upload force feedback effect to device %s due to error %d.",
752                   device->identifier.name.c_str(), errno);
753             return;
754         }
755         device->ffEffectId = effect.id;
756 
757         struct input_event ev;
758         ev.time.tv_sec = 0;
759         ev.time.tv_usec = 0;
760         ev.type = EV_FF;
761         ev.code = device->ffEffectId;
762         ev.value = 1;
763         if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
764             ALOGW("Could not start force feedback effect on device %s due to error %d.",
765                   device->identifier.name.c_str(), errno);
766             return;
767         }
768         device->ffEffectPlaying = true;
769     }
770 }
771 
cancelVibrate(int32_t deviceId)772 void EventHub::cancelVibrate(int32_t deviceId) {
773     AutoMutex _l(mLock);
774     Device* device = getDeviceLocked(deviceId);
775     if (device && device->hasValidFd()) {
776         if (device->ffEffectPlaying) {
777             device->ffEffectPlaying = false;
778 
779             struct input_event ev;
780             ev.time.tv_sec = 0;
781             ev.time.tv_usec = 0;
782             ev.type = EV_FF;
783             ev.code = device->ffEffectId;
784             ev.value = 0;
785             if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
786                 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
787                       device->identifier.name.c_str(), errno);
788                 return;
789             }
790         }
791     }
792 }
793 
getDeviceByDescriptorLocked(const std::string & descriptor) const794 EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
795     size_t size = mDevices.size();
796     for (size_t i = 0; i < size; i++) {
797         Device* device = mDevices.valueAt(i);
798         if (descriptor == device->identifier.descriptor) {
799             return device;
800         }
801     }
802     return nullptr;
803 }
804 
getDeviceLocked(int32_t deviceId) const805 EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
806     if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
807         deviceId = mBuiltInKeyboardId;
808     }
809     ssize_t index = mDevices.indexOfKey(deviceId);
810     return index >= 0 ? mDevices.valueAt(index) : NULL;
811 }
812 
getDeviceByPathLocked(const char * devicePath) const813 EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
814     for (size_t i = 0; i < mDevices.size(); i++) {
815         Device* device = mDevices.valueAt(i);
816         if (device->path == devicePath) {
817             return device;
818         }
819     }
820     return nullptr;
821 }
822 
823 /**
824  * The file descriptor could be either input device, or a video device (associated with a
825  * specific input device). Check both cases here, and return the device that this event
826  * belongs to. Caller can compare the fd's once more to determine event type.
827  * Looks through all input devices, and only attached video devices. Unattached video
828  * devices are ignored.
829  */
getDeviceByFdLocked(int fd) const830 EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
831     for (size_t i = 0; i < mDevices.size(); i++) {
832         Device* device = mDevices.valueAt(i);
833         if (device->fd == fd) {
834             // This is an input device event
835             return device;
836         }
837         if (device->videoDevice && device->videoDevice->getFd() == fd) {
838             // This is a video device event
839             return device;
840         }
841     }
842     // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
843     // and therefore should never be looked up by fd.
844     return nullptr;
845 }
846 
getEvents(int timeoutMillis,RawEvent * buffer,size_t bufferSize)847 size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
848     ALOG_ASSERT(bufferSize >= 1);
849 
850     AutoMutex _l(mLock);
851 
852     struct input_event readBuffer[bufferSize];
853 
854     RawEvent* event = buffer;
855     size_t capacity = bufferSize;
856     bool awoken = false;
857     for (;;) {
858         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
859 
860         // Reopen input devices if needed.
861         if (mNeedToReopenDevices) {
862             mNeedToReopenDevices = false;
863 
864             ALOGI("Reopening all input devices due to a configuration change.");
865 
866             closeAllDevicesLocked();
867             mNeedToScanDevices = true;
868             break; // return to the caller before we actually rescan
869         }
870 
871         // Report any devices that had last been added/removed.
872         while (mClosingDevices) {
873             Device* device = mClosingDevices;
874             ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
875             mClosingDevices = device->next;
876             event->when = now;
877             event->deviceId = (device->id == mBuiltInKeyboardId)
878                     ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
879                     : device->id;
880             event->type = DEVICE_REMOVED;
881             event += 1;
882             delete device;
883             mNeedToSendFinishedDeviceScan = true;
884             if (--capacity == 0) {
885                 break;
886             }
887         }
888 
889         if (mNeedToScanDevices) {
890             mNeedToScanDevices = false;
891             scanDevicesLocked();
892             mNeedToSendFinishedDeviceScan = true;
893         }
894 
895         while (mOpeningDevices != nullptr) {
896             Device* device = mOpeningDevices;
897             ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
898             mOpeningDevices = device->next;
899             event->when = now;
900             event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
901             event->type = DEVICE_ADDED;
902             event += 1;
903             mNeedToSendFinishedDeviceScan = true;
904             if (--capacity == 0) {
905                 break;
906             }
907         }
908 
909         if (mNeedToSendFinishedDeviceScan) {
910             mNeedToSendFinishedDeviceScan = false;
911             event->when = now;
912             event->type = FINISHED_DEVICE_SCAN;
913             event += 1;
914             if (--capacity == 0) {
915                 break;
916             }
917         }
918 
919         // Grab the next input event.
920         bool deviceChanged = false;
921         while (mPendingEventIndex < mPendingEventCount) {
922             const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
923             if (eventItem.data.fd == mINotifyFd) {
924                 if (eventItem.events & EPOLLIN) {
925                     mPendingINotify = true;
926                 } else {
927                     ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
928                 }
929                 continue;
930             }
931 
932             if (eventItem.data.fd == mWakeReadPipeFd) {
933                 if (eventItem.events & EPOLLIN) {
934                     ALOGV("awoken after wake()");
935                     awoken = true;
936                     char buffer[16];
937                     ssize_t nRead;
938                     do {
939                         nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
940                     } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
941                 } else {
942                     ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
943                           eventItem.events);
944                 }
945                 continue;
946             }
947 
948             Device* device = getDeviceByFdLocked(eventItem.data.fd);
949             if (!device) {
950                 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
951                       eventItem.data.fd);
952                 ALOG_ASSERT(!DEBUG);
953                 continue;
954             }
955             if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
956                 if (eventItem.events & EPOLLIN) {
957                     size_t numFrames = device->videoDevice->readAndQueueFrames();
958                     if (numFrames == 0) {
959                         ALOGE("Received epoll event for video device %s, but could not read frame",
960                               device->videoDevice->getName().c_str());
961                     }
962                 } else if (eventItem.events & EPOLLHUP) {
963                     // TODO(b/121395353) - consider adding EPOLLRDHUP
964                     ALOGI("Removing video device %s due to epoll hang-up event.",
965                           device->videoDevice->getName().c_str());
966                     unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
967                     device->videoDevice = nullptr;
968                 } else {
969                     ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
970                           device->videoDevice->getName().c_str());
971                     ALOG_ASSERT(!DEBUG);
972                 }
973                 continue;
974             }
975             // This must be an input event
976             if (eventItem.events & EPOLLIN) {
977                 int32_t readSize =
978                         read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
979                 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
980                     // Device was removed before INotify noticed.
981                     ALOGW("could not get event, removed? (fd: %d size: %" PRId32
982                           " bufferSize: %zu capacity: %zu errno: %d)\n",
983                           device->fd, readSize, bufferSize, capacity, errno);
984                     deviceChanged = true;
985                     closeDeviceLocked(device);
986                 } else if (readSize < 0) {
987                     if (errno != EAGAIN && errno != EINTR) {
988                         ALOGW("could not get event (errno=%d)", errno);
989                     }
990                 } else if ((readSize % sizeof(struct input_event)) != 0) {
991                     ALOGE("could not get event (wrong size: %d)", readSize);
992                 } else {
993                     int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
994 
995                     size_t count = size_t(readSize) / sizeof(struct input_event);
996                     for (size_t i = 0; i < count; i++) {
997                         struct input_event& iev = readBuffer[i];
998                         event->when = processEventTimestamp(iev);
999                         event->deviceId = deviceId;
1000                         event->type = iev.type;
1001                         event->code = iev.code;
1002                         event->value = iev.value;
1003                         event += 1;
1004                         capacity -= 1;
1005                     }
1006                     if (capacity == 0) {
1007                         // The result buffer is full.  Reset the pending event index
1008                         // so we will try to read the device again on the next iteration.
1009                         mPendingEventIndex -= 1;
1010                         break;
1011                     }
1012                 }
1013             } else if (eventItem.events & EPOLLHUP) {
1014                 ALOGI("Removing device %s due to epoll hang-up event.",
1015                       device->identifier.name.c_str());
1016                 deviceChanged = true;
1017                 closeDeviceLocked(device);
1018             } else {
1019                 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1020                       device->identifier.name.c_str());
1021             }
1022         }
1023 
1024         // readNotify() will modify the list of devices so this must be done after
1025         // processing all other events to ensure that we read all remaining events
1026         // before closing the devices.
1027         if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1028             mPendingINotify = false;
1029             readNotifyLocked();
1030             deviceChanged = true;
1031         }
1032 
1033         // Report added or removed devices immediately.
1034         if (deviceChanged) {
1035             continue;
1036         }
1037 
1038         // Return now if we have collected any events or if we were explicitly awoken.
1039         if (event != buffer || awoken) {
1040             break;
1041         }
1042 
1043         // Poll for events.
1044         // When a device driver has pending (unread) events, it acquires
1045         // a kernel wake lock.  Once the last pending event has been read, the device
1046         // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1047         // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1048         // is called again for the same fd that produced the event.
1049         // Thus the system can only sleep if there are no events pending or
1050         // currently being processed.
1051         //
1052         // The timeout is advisory only.  If the device is asleep, it will not wake just to
1053         // service the timeout.
1054         mPendingEventIndex = 0;
1055 
1056         mLock.unlock(); // release lock before poll
1057 
1058         int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1059 
1060         mLock.lock(); // reacquire lock after poll
1061 
1062         if (pollResult == 0) {
1063             // Timed out.
1064             mPendingEventCount = 0;
1065             break;
1066         }
1067 
1068         if (pollResult < 0) {
1069             // An error occurred.
1070             mPendingEventCount = 0;
1071 
1072             // Sleep after errors to avoid locking up the system.
1073             // Hopefully the error is transient.
1074             if (errno != EINTR) {
1075                 ALOGW("poll failed (errno=%d)\n", errno);
1076                 usleep(100000);
1077             }
1078         } else {
1079             // Some events occurred.
1080             mPendingEventCount = size_t(pollResult);
1081         }
1082     }
1083 
1084     // All done, return the number of events we read.
1085     return event - buffer;
1086 }
1087 
getVideoFrames(int32_t deviceId)1088 std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1089     AutoMutex _l(mLock);
1090 
1091     Device* device = getDeviceLocked(deviceId);
1092     if (!device || !device->videoDevice) {
1093         return {};
1094     }
1095     return device->videoDevice->consumeFrames();
1096 }
1097 
wake()1098 void EventHub::wake() {
1099     ALOGV("wake() called");
1100 
1101     ssize_t nWrite;
1102     do {
1103         nWrite = write(mWakeWritePipeFd, "W", 1);
1104     } while (nWrite == -1 && errno == EINTR);
1105 
1106     if (nWrite != 1 && errno != EAGAIN) {
1107         ALOGW("Could not write wake signal: %s", strerror(errno));
1108     }
1109 }
1110 
scanDevicesLocked()1111 void EventHub::scanDevicesLocked() {
1112     status_t result = scanDirLocked(DEVICE_PATH);
1113     if (result < 0) {
1114         ALOGE("scan dir failed for %s", DEVICE_PATH);
1115     }
1116     if (isV4lScanningEnabled()) {
1117         result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1118         if (result != OK) {
1119             ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1120         }
1121     }
1122     if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
1123         createVirtualKeyboardLocked();
1124     }
1125 }
1126 
1127 // ----------------------------------------------------------------------------
1128 
containsNonZeroByte(const uint8_t * array,uint32_t startIndex,uint32_t endIndex)1129 static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1130     const uint8_t* end = array + endIndex;
1131     array += startIndex;
1132     while (array != end) {
1133         if (*(array++) != 0) {
1134             return true;
1135         }
1136     }
1137     return false;
1138 }
1139 
1140 static const int32_t GAMEPAD_KEYCODES[] = {
1141         AKEYCODE_BUTTON_A,      AKEYCODE_BUTTON_B,      AKEYCODE_BUTTON_C,    //
1142         AKEYCODE_BUTTON_X,      AKEYCODE_BUTTON_Y,      AKEYCODE_BUTTON_Z,    //
1143         AKEYCODE_BUTTON_L1,     AKEYCODE_BUTTON_R1,                           //
1144         AKEYCODE_BUTTON_L2,     AKEYCODE_BUTTON_R2,                           //
1145         AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,                       //
1146         AKEYCODE_BUTTON_START,  AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
1147 };
1148 
registerFdForEpoll(int fd)1149 status_t EventHub::registerFdForEpoll(int fd) {
1150     // TODO(b/121395353) - consider adding EPOLLRDHUP
1151     struct epoll_event eventItem = {};
1152     eventItem.events = EPOLLIN | EPOLLWAKEUP;
1153     eventItem.data.fd = fd;
1154     if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1155         ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
1156         return -errno;
1157     }
1158     return OK;
1159 }
1160 
unregisterFdFromEpoll(int fd)1161 status_t EventHub::unregisterFdFromEpoll(int fd) {
1162     if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1163         ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1164         return -errno;
1165     }
1166     return OK;
1167 }
1168 
registerDeviceForEpollLocked(Device * device)1169 status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1170     if (device == nullptr) {
1171         if (DEBUG) {
1172             LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1173         }
1174         return BAD_VALUE;
1175     }
1176     status_t result = registerFdForEpoll(device->fd);
1177     if (result != OK) {
1178         ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
1179         return result;
1180     }
1181     if (device->videoDevice) {
1182         registerVideoDeviceForEpollLocked(*device->videoDevice);
1183     }
1184     return result;
1185 }
1186 
registerVideoDeviceForEpollLocked(const TouchVideoDevice & videoDevice)1187 void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1188     status_t result = registerFdForEpoll(videoDevice.getFd());
1189     if (result != OK) {
1190         ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1191     }
1192 }
1193 
unregisterDeviceFromEpollLocked(Device * device)1194 status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1195     if (device->hasValidFd()) {
1196         status_t result = unregisterFdFromEpoll(device->fd);
1197         if (result != OK) {
1198             ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1199             return result;
1200         }
1201     }
1202     if (device->videoDevice) {
1203         unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1204     }
1205     return OK;
1206 }
1207 
unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice & videoDevice)1208 void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1209     if (videoDevice.hasValidFd()) {
1210         status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1211         if (result != OK) {
1212             ALOGW("Could not remove video device fd from epoll for device: %s",
1213                   videoDevice.getName().c_str());
1214         }
1215     }
1216 }
1217 
openDeviceLocked(const char * devicePath)1218 status_t EventHub::openDeviceLocked(const char* devicePath) {
1219     char buffer[80];
1220 
1221     ALOGV("Opening device: %s", devicePath);
1222 
1223     int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
1224     if (fd < 0) {
1225         ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1226         return -1;
1227     }
1228 
1229     InputDeviceIdentifier identifier;
1230 
1231     // Get device name.
1232     if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1233         ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
1234     } else {
1235         buffer[sizeof(buffer) - 1] = '\0';
1236         identifier.name = buffer;
1237     }
1238 
1239     // Check to see if the device is on our excluded list
1240     for (size_t i = 0; i < mExcludedDevices.size(); i++) {
1241         const std::string& item = mExcludedDevices[i];
1242         if (identifier.name == item) {
1243             ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
1244             close(fd);
1245             return -1;
1246         }
1247     }
1248 
1249     // Get device driver version.
1250     int driverVersion;
1251     if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1252         ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1253         close(fd);
1254         return -1;
1255     }
1256 
1257     // Get device identifier.
1258     struct input_id inputId;
1259     if (ioctl(fd, EVIOCGID, &inputId)) {
1260         ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1261         close(fd);
1262         return -1;
1263     }
1264     identifier.bus = inputId.bustype;
1265     identifier.product = inputId.product;
1266     identifier.vendor = inputId.vendor;
1267     identifier.version = inputId.version;
1268 
1269     // Get device physical location.
1270     if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1271         // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1272     } else {
1273         buffer[sizeof(buffer) - 1] = '\0';
1274         identifier.location = buffer;
1275     }
1276 
1277     // Get device unique id.
1278     if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1279         // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1280     } else {
1281         buffer[sizeof(buffer) - 1] = '\0';
1282         identifier.uniqueId = buffer;
1283     }
1284 
1285     // Fill in the descriptor.
1286     assignDescriptorLocked(identifier);
1287 
1288     // Allocate device.  (The device object takes ownership of the fd at this point.)
1289     int32_t deviceId = mNextDeviceId++;
1290     Device* device = new Device(fd, deviceId, devicePath, identifier);
1291 
1292     ALOGV("add device %d: %s\n", deviceId, devicePath);
1293     ALOGV("  bus:        %04x\n"
1294           "  vendor      %04x\n"
1295           "  product     %04x\n"
1296           "  version     %04x\n",
1297           identifier.bus, identifier.vendor, identifier.product, identifier.version);
1298     ALOGV("  name:       \"%s\"\n", identifier.name.c_str());
1299     ALOGV("  location:   \"%s\"\n", identifier.location.c_str());
1300     ALOGV("  unique id:  \"%s\"\n", identifier.uniqueId.c_str());
1301     ALOGV("  descriptor: \"%s\"\n", identifier.descriptor.c_str());
1302     ALOGV("  driver:     v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1303           driverVersion & 0xff);
1304 
1305     // Load the configuration file for the device.
1306     loadConfigurationLocked(device);
1307 
1308     // Figure out the kinds of events the device reports.
1309     ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1310     ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1311     ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1312     ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1313     ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1314     ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1315     ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1316 
1317     // See if this is a keyboard.  Ignore everything in the button range except for
1318     // joystick and gamepad buttons which are handled like keyboards for the most part.
1319     bool haveKeyboardKeys =
1320             containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC)) ||
1321             containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_WHEEL),
1322                                 sizeof_bit_array(KEY_MAX + 1));
1323     bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1324                                                   sizeof_bit_array(BTN_MOUSE)) ||
1325             containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1326                                 sizeof_bit_array(BTN_DIGI));
1327     if (haveKeyboardKeys || haveGamepadButtons) {
1328         device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1329     }
1330 
1331     // See if this is a cursor device such as a trackball or mouse.
1332     if (test_bit(BTN_MOUSE, device->keyBitmask) && test_bit(REL_X, device->relBitmask) &&
1333         test_bit(REL_Y, device->relBitmask)) {
1334         device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1335     }
1336 
1337     // See if this is a rotary encoder type device.
1338     String8 deviceType = String8();
1339     if (device->configuration &&
1340         device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1341         if (!deviceType.compare(String8("rotaryEncoder"))) {
1342             device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1343         }
1344     }
1345 
1346     // See if this is a touch pad.
1347     // Is this a new modern multi-touch driver?
1348     if (test_bit(ABS_MT_POSITION_X, device->absBitmask) &&
1349         test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1350         // Some joysticks such as the PS3 controller report axes that conflict
1351         // with the ABS_MT range.  Try to confirm that the device really is
1352         // a touch screen.
1353         if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1354             device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1355         }
1356         // Is this an old style single-touch driver?
1357     } else if (test_bit(BTN_TOUCH, device->keyBitmask) && test_bit(ABS_X, device->absBitmask) &&
1358                test_bit(ABS_Y, device->absBitmask)) {
1359         device->classes |= INPUT_DEVICE_CLASS_TOUCH;
1360         // Is this a BT stylus?
1361     } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1362                 test_bit(BTN_TOUCH, device->keyBitmask)) &&
1363                !test_bit(ABS_X, device->absBitmask) && !test_bit(ABS_Y, device->absBitmask)) {
1364         device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1365         // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1366         // can fuse it with the touch screen data, so just take them back. Note this means an
1367         // external stylus cannot also be a keyboard device.
1368         device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
1369     }
1370 
1371     // See if this device is a joystick.
1372     // Assumes that joysticks always have gamepad buttons in order to distinguish them
1373     // from other devices such as accelerometers that also have absolute axes.
1374     if (haveGamepadButtons) {
1375         uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1376         for (int i = 0; i <= ABS_MAX; i++) {
1377             if (test_bit(i, device->absBitmask) &&
1378                 (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1379                 device->classes = assumedClasses;
1380                 break;
1381             }
1382         }
1383     }
1384 
1385     // Check whether this device has switches.
1386     for (int i = 0; i <= SW_MAX; i++) {
1387         if (test_bit(i, device->swBitmask)) {
1388             device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1389             break;
1390         }
1391     }
1392 
1393     // Check whether this device supports the vibrator.
1394     if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1395         device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1396     }
1397 
1398     // Configure virtual keys.
1399     if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1400         // Load the virtual keys for the touch screen, if any.
1401         // We do this now so that we can make sure to load the keymap if necessary.
1402         bool success = loadVirtualKeyMapLocked(device);
1403         if (success) {
1404             device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1405         }
1406     }
1407 
1408     // Load the key map.
1409     // We need to do this for joysticks too because the key layout may specify axes.
1410     status_t keyMapStatus = NAME_NOT_FOUND;
1411     if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1412         // Load the keymap for the device.
1413         keyMapStatus = loadKeyMapLocked(device);
1414     }
1415 
1416     // Configure the keyboard, gamepad or virtual keyboard.
1417     if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1418         // Register the keyboard as a built-in keyboard if it is eligible.
1419         if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
1420             isEligibleBuiltInKeyboard(device->identifier, device->configuration, &device->keyMap)) {
1421             mBuiltInKeyboardId = device->id;
1422         }
1423 
1424         // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1425         if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1426             device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1427         }
1428 
1429         // See if this device has a DPAD.
1430         if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1431             hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1432             hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1433             hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1434             hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1435             device->classes |= INPUT_DEVICE_CLASS_DPAD;
1436         }
1437 
1438         // See if this device has a gamepad.
1439         for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
1440             if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1441                 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1442                 break;
1443             }
1444         }
1445     }
1446 
1447     // If the device isn't recognized as something we handle, don't monitor it.
1448     if (device->classes == 0) {
1449         ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath,
1450               device->identifier.name.c_str());
1451         delete device;
1452         return -1;
1453     }
1454 
1455     // Determine whether the device has a mic.
1456     if (deviceHasMicLocked(device)) {
1457         device->classes |= INPUT_DEVICE_CLASS_MIC;
1458     }
1459 
1460     // Determine whether the device is external or internal.
1461     if (isExternalDeviceLocked(device)) {
1462         device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1463     }
1464 
1465     if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD) &&
1466         device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
1467         device->controllerNumber = getNextControllerNumberLocked(device);
1468         setLedForControllerLocked(device);
1469     }
1470 
1471     // Find a matching video device by comparing device names
1472     // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
1473     for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1474         if (device->identifier.name == videoDevice->getName()) {
1475             device->videoDevice = std::move(videoDevice);
1476             break;
1477         }
1478     }
1479     mUnattachedVideoDevices
1480             .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1481                                   [](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1482                                       return videoDevice == nullptr;
1483                                   }),
1484                    mUnattachedVideoDevices.end());
1485 
1486     if (registerDeviceForEpollLocked(device) != OK) {
1487         delete device;
1488         return -1;
1489     }
1490 
1491     configureFd(device);
1492 
1493     ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1494           "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
1495           deviceId, fd, devicePath, device->identifier.name.c_str(), device->classes,
1496           device->configurationFile.c_str(), device->keyMap.keyLayoutFile.c_str(),
1497           device->keyMap.keyCharacterMapFile.c_str(), toString(mBuiltInKeyboardId == deviceId));
1498 
1499     addDeviceLocked(device);
1500     return OK;
1501 }
1502 
configureFd(Device * device)1503 void EventHub::configureFd(Device* device) {
1504     // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1505     if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1506         // Disable kernel key repeat since we handle it ourselves
1507         unsigned int repeatRate[] = {0, 0};
1508         if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1509             ALOGW("Unable to disable kernel key repeat for %s: %s", device->path.c_str(),
1510                   strerror(errno));
1511         }
1512     }
1513 
1514     // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1515     // associated with input events.  This is important because the input system
1516     // uses the timestamps extensively and assumes they were recorded using the monotonic
1517     // clock.
1518     int clockId = CLOCK_MONOTONIC;
1519     bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
1520     ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
1521 }
1522 
openVideoDeviceLocked(const std::string & devicePath)1523 void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1524     std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1525     if (!videoDevice) {
1526         ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1527         return;
1528     }
1529     // Transfer ownership of this video device to a matching input device
1530     for (size_t i = 0; i < mDevices.size(); i++) {
1531         Device* device = mDevices.valueAt(i);
1532         if (videoDevice->getName() == device->identifier.name) {
1533             device->videoDevice = std::move(videoDevice);
1534             if (device->enabled) {
1535                 registerVideoDeviceForEpollLocked(*device->videoDevice);
1536             }
1537             return;
1538         }
1539     }
1540 
1541     // Couldn't find a matching input device, so just add it to a temporary holding queue.
1542     // A matching input device may appear later.
1543     ALOGI("Adding video device %s to list of unattached video devices",
1544           videoDevice->getName().c_str());
1545     mUnattachedVideoDevices.push_back(std::move(videoDevice));
1546 }
1547 
isDeviceEnabled(int32_t deviceId)1548 bool EventHub::isDeviceEnabled(int32_t deviceId) {
1549     AutoMutex _l(mLock);
1550     Device* device = getDeviceLocked(deviceId);
1551     if (device == nullptr) {
1552         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1553         return false;
1554     }
1555     return device->enabled;
1556 }
1557 
enableDevice(int32_t deviceId)1558 status_t EventHub::enableDevice(int32_t deviceId) {
1559     AutoMutex _l(mLock);
1560     Device* device = getDeviceLocked(deviceId);
1561     if (device == nullptr) {
1562         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1563         return BAD_VALUE;
1564     }
1565     if (device->enabled) {
1566         ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1567         return OK;
1568     }
1569     status_t result = device->enable();
1570     if (result != OK) {
1571         ALOGE("Failed to enable device %" PRId32, deviceId);
1572         return result;
1573     }
1574 
1575     configureFd(device);
1576 
1577     return registerDeviceForEpollLocked(device);
1578 }
1579 
disableDevice(int32_t deviceId)1580 status_t EventHub::disableDevice(int32_t deviceId) {
1581     AutoMutex _l(mLock);
1582     Device* device = getDeviceLocked(deviceId);
1583     if (device == nullptr) {
1584         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1585         return BAD_VALUE;
1586     }
1587     if (!device->enabled) {
1588         ALOGW("Duplicate call to %s, input device already disabled", __func__);
1589         return OK;
1590     }
1591     unregisterDeviceFromEpollLocked(device);
1592     return device->disable();
1593 }
1594 
createVirtualKeyboardLocked()1595 void EventHub::createVirtualKeyboardLocked() {
1596     InputDeviceIdentifier identifier;
1597     identifier.name = "Virtual";
1598     identifier.uniqueId = "<virtual>";
1599     assignDescriptorLocked(identifier);
1600 
1601     Device* device =
1602             new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
1603     device->classes = INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_ALPHAKEY |
1604             INPUT_DEVICE_CLASS_DPAD | INPUT_DEVICE_CLASS_VIRTUAL;
1605     loadKeyMapLocked(device);
1606     addDeviceLocked(device);
1607 }
1608 
addDeviceLocked(Device * device)1609 void EventHub::addDeviceLocked(Device* device) {
1610     mDevices.add(device->id, device);
1611     device->next = mOpeningDevices;
1612     mOpeningDevices = device;
1613 }
1614 
loadConfigurationLocked(Device * device)1615 void EventHub::loadConfigurationLocked(Device* device) {
1616     device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1617             device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
1618     if (device->configurationFile.empty()) {
1619         ALOGD("No input device configuration file found for device '%s'.",
1620               device->identifier.name.c_str());
1621     } else {
1622         status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
1623                                             &device->configuration);
1624         if (status) {
1625             ALOGE("Error loading input device configuration file for device '%s'.  "
1626                   "Using default configuration.",
1627                   device->identifier.name.c_str());
1628         }
1629     }
1630 }
1631 
loadVirtualKeyMapLocked(Device * device)1632 bool EventHub::loadVirtualKeyMapLocked(Device* device) {
1633     // The virtual key map is supplied by the kernel as a system board property file.
1634     std::string path;
1635     path += "/sys/board_properties/virtualkeys.";
1636     path += device->identifier.getCanonicalName();
1637     if (access(path.c_str(), R_OK)) {
1638         return false;
1639     }
1640     device->virtualKeyMap = VirtualKeyMap::load(path);
1641     return device->virtualKeyMap != nullptr;
1642 }
1643 
loadKeyMapLocked(Device * device)1644 status_t EventHub::loadKeyMapLocked(Device* device) {
1645     return device->keyMap.load(device->identifier, device->configuration);
1646 }
1647 
isExternalDeviceLocked(Device * device)1648 bool EventHub::isExternalDeviceLocked(Device* device) {
1649     if (device->configuration) {
1650         bool value;
1651         if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1652             return !value;
1653         }
1654     }
1655     return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1656 }
1657 
deviceHasMicLocked(Device * device)1658 bool EventHub::deviceHasMicLocked(Device* device) {
1659     if (device->configuration) {
1660         bool value;
1661         if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1662             return value;
1663         }
1664     }
1665     return false;
1666 }
1667 
getNextControllerNumberLocked(Device * device)1668 int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1669     if (mControllerNumbers.isFull()) {
1670         ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
1671               device->identifier.name.c_str());
1672         return 0;
1673     }
1674     // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1675     // one
1676     return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1677 }
1678 
releaseControllerNumberLocked(Device * device)1679 void EventHub::releaseControllerNumberLocked(Device* device) {
1680     int32_t num = device->controllerNumber;
1681     device->controllerNumber = 0;
1682     if (num == 0) {
1683         return;
1684     }
1685     mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1686 }
1687 
setLedForControllerLocked(Device * device)1688 void EventHub::setLedForControllerLocked(Device* device) {
1689     for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1690         setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1691     }
1692 }
1693 
hasKeycodeLocked(Device * device,int keycode) const1694 bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
1695     if (!device->keyMap.haveKeyLayout()) {
1696         return false;
1697     }
1698 
1699     std::vector<int32_t> scanCodes;
1700     device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1701     const size_t N = scanCodes.size();
1702     for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
1703         int32_t sc = scanCodes[i];
1704         if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1705             return true;
1706         }
1707     }
1708 
1709     return false;
1710 }
1711 
mapLed(Device * device,int32_t led,int32_t * outScanCode) const1712 status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
1713     if (!device->keyMap.haveKeyLayout()) {
1714         return NAME_NOT_FOUND;
1715     }
1716 
1717     int32_t scanCode;
1718     if (device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1719         if (scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1720             *outScanCode = scanCode;
1721             return NO_ERROR;
1722         }
1723     }
1724     return NAME_NOT_FOUND;
1725 }
1726 
closeDeviceByPathLocked(const char * devicePath)1727 void EventHub::closeDeviceByPathLocked(const char* devicePath) {
1728     Device* device = getDeviceByPathLocked(devicePath);
1729     if (device) {
1730         closeDeviceLocked(device);
1731         return;
1732     }
1733     ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1734 }
1735 
1736 /**
1737  * Find the video device by filename, and close it.
1738  * The video device is closed by path during an inotify event, where we don't have the
1739  * additional context about the video device fd, or the associated input device.
1740  */
closeVideoDeviceByPathLocked(const std::string & devicePath)1741 void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
1742     // A video device may be owned by an existing input device, or it may be stored in
1743     // the mUnattachedVideoDevices queue. Check both locations.
1744     for (size_t i = 0; i < mDevices.size(); i++) {
1745         Device* device = mDevices.valueAt(i);
1746         if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
1747             unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1748             device->videoDevice = nullptr;
1749             return;
1750         }
1751     }
1752     mUnattachedVideoDevices
1753             .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
1754                                   [&devicePath](
1755                                           const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1756                                       return videoDevice->getPath() == devicePath;
1757                                   }),
1758                    mUnattachedVideoDevices.end());
1759 }
1760 
closeAllDevicesLocked()1761 void EventHub::closeAllDevicesLocked() {
1762     mUnattachedVideoDevices.clear();
1763     while (mDevices.size() > 0) {
1764         closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1765     }
1766 }
1767 
closeDeviceLocked(Device * device)1768 void EventHub::closeDeviceLocked(Device* device) {
1769     ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x", device->path.c_str(),
1770           device->identifier.name.c_str(), device->id, device->fd, device->classes);
1771 
1772     if (device->id == mBuiltInKeyboardId) {
1773         ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
1774               device->path.c_str(), mBuiltInKeyboardId);
1775         mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1776     }
1777 
1778     unregisterDeviceFromEpollLocked(device);
1779     if (device->videoDevice) {
1780         // This must be done after the video device is removed from epoll
1781         mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1782     }
1783 
1784     releaseControllerNumberLocked(device);
1785 
1786     mDevices.removeItem(device->id);
1787     device->close();
1788 
1789     // Unlink for opening devices list if it is present.
1790     Device* pred = nullptr;
1791     bool found = false;
1792     for (Device* entry = mOpeningDevices; entry != nullptr;) {
1793         if (entry == device) {
1794             found = true;
1795             break;
1796         }
1797         pred = entry;
1798         entry = entry->next;
1799     }
1800     if (found) {
1801         // Unlink the device from the opening devices list then delete it.
1802         // We don't need to tell the client that the device was closed because
1803         // it does not even know it was opened in the first place.
1804         ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
1805         if (pred) {
1806             pred->next = device->next;
1807         } else {
1808             mOpeningDevices = device->next;
1809         }
1810         delete device;
1811     } else {
1812         // Link into closing devices list.
1813         // The device will be deleted later after we have informed the client.
1814         device->next = mClosingDevices;
1815         mClosingDevices = device;
1816     }
1817 }
1818 
readNotifyLocked()1819 status_t EventHub::readNotifyLocked() {
1820     int res;
1821     char event_buf[512];
1822     int event_size;
1823     int event_pos = 0;
1824     struct inotify_event* event;
1825 
1826     ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1827     res = read(mINotifyFd, event_buf, sizeof(event_buf));
1828     if (res < (int)sizeof(*event)) {
1829         if (errno == EINTR) return 0;
1830         ALOGW("could not get event, %s\n", strerror(errno));
1831         return -1;
1832     }
1833 
1834     while (res >= (int)sizeof(*event)) {
1835         event = (struct inotify_event*)(event_buf + event_pos);
1836         if (event->len) {
1837             if (event->wd == mInputWd) {
1838                 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
1839                 if (event->mask & IN_CREATE) {
1840                     openDeviceLocked(filename.c_str());
1841                 } else {
1842                     ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1843                     closeDeviceByPathLocked(filename.c_str());
1844                 }
1845             } else if (event->wd == mVideoWd) {
1846                 if (isV4lTouchNode(event->name)) {
1847                     std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
1848                     if (event->mask & IN_CREATE) {
1849                         openVideoDeviceLocked(filename);
1850                     } else {
1851                         ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1852                         closeVideoDeviceByPathLocked(filename);
1853                     }
1854                 }
1855             } else {
1856                 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
1857             }
1858         }
1859         event_size = sizeof(*event) + event->len;
1860         res -= event_size;
1861         event_pos += event_size;
1862     }
1863     return 0;
1864 }
1865 
scanDirLocked(const char * dirname)1866 status_t EventHub::scanDirLocked(const char* dirname) {
1867     char devname[PATH_MAX];
1868     char* filename;
1869     DIR* dir;
1870     struct dirent* de;
1871     dir = opendir(dirname);
1872     if (dir == nullptr) return -1;
1873     strcpy(devname, dirname);
1874     filename = devname + strlen(devname);
1875     *filename++ = '/';
1876     while ((de = readdir(dir))) {
1877         if (de->d_name[0] == '.' &&
1878             (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1879             continue;
1880         strcpy(filename, de->d_name);
1881         openDeviceLocked(devname);
1882     }
1883     closedir(dir);
1884     return 0;
1885 }
1886 
1887 /**
1888  * Look for all dirname/v4l-touch* devices, and open them.
1889  */
scanVideoDirLocked(const std::string & dirname)1890 status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
1891     DIR* dir;
1892     struct dirent* de;
1893     dir = opendir(dirname.c_str());
1894     if (!dir) {
1895         ALOGE("Could not open video directory %s", dirname.c_str());
1896         return BAD_VALUE;
1897     }
1898 
1899     while ((de = readdir(dir))) {
1900         const char* name = de->d_name;
1901         if (isV4lTouchNode(name)) {
1902             ALOGI("Found touch video device %s", name);
1903             openVideoDeviceLocked(dirname + "/" + name);
1904         }
1905     }
1906     closedir(dir);
1907     return OK;
1908 }
1909 
requestReopenDevices()1910 void EventHub::requestReopenDevices() {
1911     ALOGV("requestReopenDevices() called");
1912 
1913     AutoMutex _l(mLock);
1914     mNeedToReopenDevices = true;
1915 }
1916 
dump(std::string & dump)1917 void EventHub::dump(std::string& dump) {
1918     dump += "Event Hub State:\n";
1919 
1920     { // acquire lock
1921         AutoMutex _l(mLock);
1922 
1923         dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
1924 
1925         dump += INDENT "Devices:\n";
1926 
1927         for (size_t i = 0; i < mDevices.size(); i++) {
1928             const Device* device = mDevices.valueAt(i);
1929             if (mBuiltInKeyboardId == device->id) {
1930                 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
1931                                      device->id, device->identifier.name.c_str());
1932             } else {
1933                 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
1934                                      device->identifier.name.c_str());
1935             }
1936             dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
1937             dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
1938             dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
1939             dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1940             dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
1941             dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
1942             dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
1943             dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
1944                                          "product=0x%04x, version=0x%04x\n",
1945                                  device->identifier.bus, device->identifier.vendor,
1946                                  device->identifier.product, device->identifier.version);
1947             dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
1948                                  device->keyMap.keyLayoutFile.c_str());
1949             dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
1950                                  device->keyMap.keyCharacterMapFile.c_str());
1951             dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
1952                                  device->configurationFile.c_str());
1953             dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
1954                                  toString(device->overlayKeyMap != nullptr));
1955             dump += INDENT3 "VideoDevice: ";
1956             if (device->videoDevice) {
1957                 dump += device->videoDevice->dump() + "\n";
1958             } else {
1959                 dump += "<none>\n";
1960             }
1961         }
1962 
1963         dump += INDENT "Unattached video devices:\n";
1964         for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1965             dump += INDENT2 + videoDevice->dump() + "\n";
1966         }
1967         if (mUnattachedVideoDevices.empty()) {
1968             dump += INDENT2 "<none>\n";
1969         }
1970     } // release lock
1971 }
1972 
monitor()1973 void EventHub::monitor() {
1974     // Acquire and release the lock to ensure that the event hub has not deadlocked.
1975     mLock.lock();
1976     mLock.unlock();
1977 }
1978 
1979 }; // namespace android
1980