• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <sys/stat.h>
33 #include <sys/sysmacros.h>
34 #include <unistd.h>
35 
36 #define LOG_TAG "EventHub"
37 
38 // #define LOG_NDEBUG 0
39 #include <android-base/file.h>
40 #include <android-base/stringprintf.h>
41 #include <android-base/strings.h>
42 #include <cutils/properties.h>
43 #include <input/KeyCharacterMap.h>
44 #include <input/KeyLayoutMap.h>
45 #include <input/VirtualKeyMap.h>
46 #include <openssl/sha.h>
47 #include <statslog.h>
48 #include <utils/Errors.h>
49 #include <utils/Log.h>
50 #include <utils/Timers.h>
51 
52 #include <filesystem>
53 #include <regex>
54 
55 #include "EventHub.h"
56 
57 #define INDENT "  "
58 #define INDENT2 "    "
59 #define INDENT3 "      "
60 
61 using android::base::StringPrintf;
62 using namespace android::flag_operators;
63 
64 namespace android {
65 
66 static const char* DEVICE_PATH = "/dev/input";
67 // v4l2 devices go directly into /dev
68 static const char* VIDEO_DEVICE_PATH = "/dev";
69 
70 static constexpr size_t OBFUSCATED_LENGTH = 8;
71 
72 static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
73 static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
74 
75 // Mapping for input battery class node IDs lookup.
76 // https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
77 static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
78         {{"capacity", InputBatteryClass::CAPACITY},
79          {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
80          {"status", InputBatteryClass::STATUS}};
81 
82 // Mapping for input battery class node names lookup.
83 // https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
84 static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
85         {{InputBatteryClass::CAPACITY, "capacity"},
86          {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
87          {InputBatteryClass::STATUS, "status"}};
88 
89 // must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
90 static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
91         {{"Unknown", BATTERY_STATUS_UNKNOWN},
92          {"Charging", BATTERY_STATUS_CHARGING},
93          {"Discharging", BATTERY_STATUS_DISCHARGING},
94          {"Not charging", BATTERY_STATUS_NOT_CHARGING},
95          {"Full", BATTERY_STATUS_FULL}};
96 
97 // Mapping taken from
98 // https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
99 static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
100                                                                        {"Low", 10},
101                                                                        {"Normal", 55},
102                                                                        {"High", 70},
103                                                                        {"Full", 100},
104                                                                        {"Unknown", 50}};
105 
106 // Mapping for input led class node names lookup.
107 // https://www.kernel.org/doc/html/latest/leds/leds-class.html
108 static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
109         {{"red", InputLightClass::RED},
110          {"green", InputLightClass::GREEN},
111          {"blue", InputLightClass::BLUE},
112          {"global", InputLightClass::GLOBAL},
113          {"brightness", InputLightClass::BRIGHTNESS},
114          {"multi_index", InputLightClass::MULTI_INDEX},
115          {"multi_intensity", InputLightClass::MULTI_INTENSITY},
116          {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
117 
118 // Mapping for input multicolor led class node names.
119 // https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
120 static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
121         {{InputLightClass::BRIGHTNESS, "brightness"},
122          {InputLightClass::MULTI_INDEX, "multi_index"},
123          {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
124 
125 // Mapping for light color name and the light color
126 const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
127                                                                   {"green", LightColor::GREEN},
128                                                                   {"blue", LightColor::BLUE}};
129 
toString(bool value)130 static inline const char* toString(bool value) {
131     return value ? "true" : "false";
132 }
133 
sha1(const std::string & in)134 static std::string sha1(const std::string& in) {
135     SHA_CTX ctx;
136     SHA1_Init(&ctx);
137     SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
138     u_char digest[SHA_DIGEST_LENGTH];
139     SHA1_Final(digest, &ctx);
140 
141     std::string out;
142     for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
143         out += StringPrintf("%02x", digest[i]);
144     }
145     return out;
146 }
147 
148 /**
149  * Return true if name matches "v4l-touch*"
150  */
isV4lTouchNode(std::string name)151 static bool isV4lTouchNode(std::string name) {
152     return name.find("v4l-touch") != std::string::npos;
153 }
154 
155 /**
156  * Returns true if V4L devices should be scanned.
157  *
158  * The system property ro.input.video_enabled can be used to control whether
159  * EventHub scans and opens V4L devices. As V4L does not support multiple
160  * clients, EventHub effectively blocks access to these devices when it opens
161  * them.
162  *
163  * Setting this to "false" would prevent any video devices from being discovered and
164  * associated with input devices.
165  *
166  * This property can be used as follows:
167  * 1. To turn off features that are dependent on video device presence.
168  * 2. During testing and development, to allow other clients to read video devices
169  * directly from /dev.
170  */
isV4lScanningEnabled()171 static bool isV4lScanningEnabled() {
172     return property_get_bool("ro.input.video_enabled", true /* default_value */);
173 }
174 
processEventTimestamp(const struct input_event & event)175 static nsecs_t processEventTimestamp(const struct input_event& event) {
176     // Use the time specified in the event instead of the current time
177     // so that downstream code can get more accurate estimates of
178     // event dispatch latency from the time the event is enqueued onto
179     // the evdev client buffer.
180     //
181     // The event's timestamp fortuitously uses the same monotonic clock
182     // time base as the rest of Android. The kernel event device driver
183     // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
184     // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
185     // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
186     // system call that also queries ktime_get_ts().
187 
188     const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
189             microseconds_to_nanoseconds(event.time.tv_usec);
190     return inputEventTime;
191 }
192 
193 /**
194  * Returns the sysfs root path of the input device
195  *
196  */
getSysfsRootPath(const char * devicePath)197 static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
198     std::error_code errorCode;
199 
200     // Stat the device path to get the major and minor number of the character file
201     struct stat statbuf;
202     if (stat(devicePath, &statbuf) == -1) {
203         ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
204         return std::nullopt;
205     }
206 
207     unsigned int major_num = major(statbuf.st_rdev);
208     unsigned int minor_num = minor(statbuf.st_rdev);
209 
210     // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
211     auto sysfsPath = std::filesystem::path("/sys/dev/char/");
212     sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
213     sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
214 
215     // Make sure nothing went wrong in call to canonical()
216     if (errorCode) {
217         ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
218               errorCode.message().c_str());
219         return std::nullopt;
220     }
221 
222     // Continue to go up a directory until we reach a directory named "input"
223     while (sysfsPath != "/" && sysfsPath.filename() != "input") {
224         sysfsPath = sysfsPath.parent_path();
225     }
226 
227     // Then go up one more and you will be at the sysfs root of the device
228     sysfsPath = sysfsPath.parent_path();
229 
230     // Make sure we didn't reach root path and that directory actually exists
231     if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
232         if (errorCode) {
233             ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
234                   errorCode.message().c_str());
235         }
236 
237         // Not found
238         return std::nullopt;
239     }
240 
241     return sysfsPath;
242 }
243 
244 /**
245  * Returns the list of files under a specified path.
246  */
allFilesInPath(const std::filesystem::path & path)247 static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
248     std::vector<std::filesystem::path> nodes;
249     std::error_code errorCode;
250     auto iter = std::filesystem::directory_iterator(path, errorCode);
251     while (!errorCode && iter != std::filesystem::directory_iterator()) {
252         nodes.push_back(iter->path());
253         iter++;
254     }
255     return nodes;
256 }
257 
258 /**
259  * Returns the list of files under a specified directory in a sysfs path.
260  * Example:
261  * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
262  * in the sysfs path.
263  */
findSysfsNodes(const std::filesystem::path & sysfsRoot,SysfsClass clazz)264 static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
265                                                          SysfsClass clazz) {
266     std::string nodeStr = NamedEnum::string(clazz);
267     std::for_each(nodeStr.begin(), nodeStr.end(),
268                   [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
269     std::vector<std::filesystem::path> nodes;
270     for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
271         nodes = allFilesInPath(path / nodeStr);
272     }
273     return nodes;
274 }
275 
getColorIndexArray(std::filesystem::path path)276 static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
277         std::filesystem::path path) {
278     std::string indexStr;
279     if (!base::ReadFileToString(path, &indexStr)) {
280         return std::nullopt;
281     }
282 
283     // Parse the multi color LED index file, refer to kernel docs
284     // leds/leds-class-multicolor.html
285     std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
286     std::smatch results;
287     std::array<LightColor, COLOR_NUM> colors;
288     if (!std::regex_match(indexStr, results, indexPattern)) {
289         return std::nullopt;
290     }
291 
292     for (size_t i = 1; i < results.size(); i++) {
293         const auto it = LIGHT_COLORS.find(results[i].str());
294         if (it != LIGHT_COLORS.end()) {
295             // intensities.emplace(it->second, 0);
296             colors[i - 1] = it->second;
297         }
298     }
299     return colors;
300 }
301 
302 // --- Global Functions ---
303 
getAbsAxisUsage(int32_t axis,Flags<InputDeviceClass> deviceClasses)304 Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, Flags<InputDeviceClass> deviceClasses) {
305     // Touch devices get dibs on touch-related axes.
306     if (deviceClasses.test(InputDeviceClass::TOUCH)) {
307         switch (axis) {
308             case ABS_X:
309             case ABS_Y:
310             case ABS_PRESSURE:
311             case ABS_TOOL_WIDTH:
312             case ABS_DISTANCE:
313             case ABS_TILT_X:
314             case ABS_TILT_Y:
315             case ABS_MT_SLOT:
316             case ABS_MT_TOUCH_MAJOR:
317             case ABS_MT_TOUCH_MINOR:
318             case ABS_MT_WIDTH_MAJOR:
319             case ABS_MT_WIDTH_MINOR:
320             case ABS_MT_ORIENTATION:
321             case ABS_MT_POSITION_X:
322             case ABS_MT_POSITION_Y:
323             case ABS_MT_TOOL_TYPE:
324             case ABS_MT_BLOB_ID:
325             case ABS_MT_TRACKING_ID:
326             case ABS_MT_PRESSURE:
327             case ABS_MT_DISTANCE:
328                 return InputDeviceClass::TOUCH;
329         }
330     }
331 
332     if (deviceClasses.test(InputDeviceClass::SENSOR)) {
333         switch (axis) {
334             case ABS_X:
335             case ABS_Y:
336             case ABS_Z:
337             case ABS_RX:
338             case ABS_RY:
339             case ABS_RZ:
340                 return InputDeviceClass::SENSOR;
341         }
342     }
343 
344     // External stylus gets the pressure axis
345     if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
346         if (axis == ABS_PRESSURE) {
347             return InputDeviceClass::EXTERNAL_STYLUS;
348         }
349     }
350 
351     // Joystick devices get the rest.
352     return deviceClasses & InputDeviceClass::JOYSTICK;
353 }
354 
355 // --- EventHub::Device ---
356 
Device(int fd,int32_t id,const std::string & path,const InputDeviceIdentifier & identifier)357 EventHub::Device::Device(int fd, int32_t id, const std::string& path,
358                          const InputDeviceIdentifier& identifier)
359       : fd(fd),
360         id(id),
361         path(path),
362         identifier(identifier),
363         classes(0),
364         configuration(nullptr),
365         virtualKeyMap(nullptr),
366         ffEffectPlaying(false),
367         ffEffectId(-1),
368         associatedDevice(nullptr),
369         controllerNumber(0),
370         enabled(true),
371         isVirtual(fd < 0) {}
372 
~Device()373 EventHub::Device::~Device() {
374     close();
375 }
376 
close()377 void EventHub::Device::close() {
378     if (fd >= 0) {
379         ::close(fd);
380         fd = -1;
381     }
382 }
383 
enable()384 status_t EventHub::Device::enable() {
385     fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
386     if (fd < 0) {
387         ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
388         return -errno;
389     }
390     enabled = true;
391     return OK;
392 }
393 
disable()394 status_t EventHub::Device::disable() {
395     close();
396     enabled = false;
397     return OK;
398 }
399 
hasValidFd() const400 bool EventHub::Device::hasValidFd() const {
401     return !isVirtual && enabled;
402 }
403 
getKeyCharacterMap() const404 const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
405     return keyMap.keyCharacterMap;
406 }
407 
408 template <std::size_t N>
readDeviceBitMask(unsigned long ioctlCode,BitArray<N> & bitArray)409 status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
410     if (!hasValidFd()) {
411         return BAD_VALUE;
412     }
413     if ((_IOC_SIZE(ioctlCode) == 0)) {
414         ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
415     }
416 
417     typename BitArray<N>::Buffer buffer;
418     status_t ret = ioctl(fd, ioctlCode, buffer.data());
419     bitArray.loadFromBuffer(buffer);
420     return ret;
421 }
422 
configureFd()423 void EventHub::Device::configureFd() {
424     // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
425     if (classes.test(InputDeviceClass::KEYBOARD)) {
426         // Disable kernel key repeat since we handle it ourselves
427         unsigned int repeatRate[] = {0, 0};
428         if (ioctl(fd, EVIOCSREP, repeatRate)) {
429             ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
430         }
431     }
432 
433     // Tell the kernel that we want to use the monotonic clock for reporting timestamps
434     // associated with input events.  This is important because the input system
435     // uses the timestamps extensively and assumes they were recorded using the monotonic
436     // clock.
437     int clockId = CLOCK_MONOTONIC;
438     if (classes.test(InputDeviceClass::SENSOR)) {
439         // Each new sensor event should use the same time base as
440         // SystemClock.elapsedRealtimeNanos().
441         clockId = CLOCK_BOOTTIME;
442     }
443     bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
444     ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
445 }
446 
hasKeycodeLocked(int keycode) const447 bool EventHub::Device::hasKeycodeLocked(int keycode) const {
448     if (!keyMap.haveKeyLayout()) {
449         return false;
450     }
451 
452     std::vector<int32_t> scanCodes;
453     keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
454     const size_t N = scanCodes.size();
455     for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
456         int32_t sc = scanCodes[i];
457         if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
458             return true;
459         }
460     }
461 
462     return false;
463 }
464 
loadConfigurationLocked()465 void EventHub::Device::loadConfigurationLocked() {
466     configurationFile =
467             getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
468                                                                   InputDeviceConfigurationFileType::
469                                                                           CONFIGURATION);
470     if (configurationFile.empty()) {
471         ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
472     } else {
473         android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
474                 PropertyMap::load(configurationFile.c_str());
475         if (!propertyMap.ok()) {
476             ALOGE("Error loading input device configuration file for device '%s'.  "
477                   "Using default configuration.",
478                   identifier.name.c_str());
479         } else {
480             configuration = std::move(*propertyMap);
481         }
482     }
483 }
484 
loadVirtualKeyMapLocked()485 bool EventHub::Device::loadVirtualKeyMapLocked() {
486     // The virtual key map is supplied by the kernel as a system board property file.
487     std::string propPath = "/sys/board_properties/virtualkeys.";
488     propPath += identifier.getCanonicalName();
489     if (access(propPath.c_str(), R_OK)) {
490         return false;
491     }
492     virtualKeyMap = VirtualKeyMap::load(propPath);
493     return virtualKeyMap != nullptr;
494 }
495 
loadKeyMapLocked()496 status_t EventHub::Device::loadKeyMapLocked() {
497     return keyMap.load(identifier, configuration.get());
498 }
499 
isExternalDeviceLocked()500 bool EventHub::Device::isExternalDeviceLocked() {
501     if (configuration) {
502         bool value;
503         if (configuration->tryGetProperty(String8("device.internal"), value)) {
504             return !value;
505         }
506     }
507     return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
508 }
509 
deviceHasMicLocked()510 bool EventHub::Device::deviceHasMicLocked() {
511     if (configuration) {
512         bool value;
513         if (configuration->tryGetProperty(String8("audio.mic"), value)) {
514             return value;
515         }
516     }
517     return false;
518 }
519 
setLedStateLocked(int32_t led,bool on)520 void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
521     int32_t sc;
522     if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
523         struct input_event ev;
524         ev.time.tv_sec = 0;
525         ev.time.tv_usec = 0;
526         ev.type = EV_LED;
527         ev.code = sc;
528         ev.value = on ? 1 : 0;
529 
530         ssize_t nWrite;
531         do {
532             nWrite = write(fd, &ev, sizeof(struct input_event));
533         } while (nWrite == -1 && errno == EINTR);
534     }
535 }
536 
setLedForControllerLocked()537 void EventHub::Device::setLedForControllerLocked() {
538     for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
539         setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
540     }
541 }
542 
mapLed(int32_t led,int32_t * outScanCode) const543 status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
544     if (!keyMap.haveKeyLayout()) {
545         return NAME_NOT_FOUND;
546     }
547 
548     int32_t scanCode;
549     if (keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
550         if (scanCode >= 0 && scanCode <= LED_MAX && ledBitmask.test(scanCode)) {
551             *outScanCode = scanCode;
552             return NO_ERROR;
553         }
554     }
555     return NAME_NOT_FOUND;
556 }
557 
558 // Check the sysfs path for any input device batteries, returns true if battery found.
configureBatteryLocked()559 bool EventHub::AssociatedDevice::configureBatteryLocked() {
560     nextBatteryId = 0;
561     // Check if device has any battery.
562     const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
563     for (const auto& nodePath : paths) {
564         RawBatteryInfo info;
565         info.id = ++nextBatteryId;
566         info.path = nodePath;
567         info.name = nodePath.filename();
568 
569         // Scan the path for all the files
570         // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
571         const auto& files = allFilesInPath(nodePath);
572         for (const auto& file : files) {
573             const auto it = BATTERY_CLASSES.find(file.filename().string());
574             if (it != BATTERY_CLASSES.end()) {
575                 info.flags |= it->second;
576             }
577         }
578         batteryInfos.insert_or_assign(info.id, info);
579         ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
580     }
581     return !batteryInfos.empty();
582 }
583 
584 // Check the sysfs path for any input device lights, returns true if lights found.
configureLightsLocked()585 bool EventHub::AssociatedDevice::configureLightsLocked() {
586     nextLightId = 0;
587     // Check if device has any lights.
588     const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
589     for (const auto& nodePath : paths) {
590         RawLightInfo info;
591         info.id = ++nextLightId;
592         info.path = nodePath;
593         info.name = nodePath.filename();
594         info.maxBrightness = std::nullopt;
595         size_t nameStart = info.name.rfind(":");
596         if (nameStart != std::string::npos) {
597             // Trim the name to color name
598             info.name = info.name.substr(nameStart + 1);
599             // Set InputLightClass flag for colors
600             const auto it = LIGHT_CLASSES.find(info.name);
601             if (it != LIGHT_CLASSES.end()) {
602                 info.flags |= it->second;
603             }
604         }
605         // Scan the path for all the files
606         // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
607         const auto& files = allFilesInPath(nodePath);
608         for (const auto& file : files) {
609             const auto it = LIGHT_CLASSES.find(file.filename().string());
610             if (it != LIGHT_CLASSES.end()) {
611                 info.flags |= it->second;
612                 // If the node has maximum brightness, read it
613                 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
614                     std::string str;
615                     if (base::ReadFileToString(file, &str)) {
616                         info.maxBrightness = std::stoi(str);
617                     }
618                 }
619             }
620         }
621         lightInfos.insert_or_assign(info.id, info);
622         ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
623     }
624     return !lightInfos.empty();
625 }
626 
627 /**
628  * Get the capabilities for the current process.
629  * Crashes the system if unable to create / check / destroy the capabilities object.
630  */
631 class Capabilities final {
632 public:
Capabilities()633     explicit Capabilities() {
634         mCaps = cap_get_proc();
635         LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
636     }
637 
638     /**
639      * Check whether the current process has a specific capability
640      * in the set of effective capabilities.
641      * Return CAP_SET if the process has the requested capability
642      * Return CAP_CLEAR otherwise.
643      */
checkEffectiveCapability(cap_value_t capability)644     cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
645         cap_flag_value_t value;
646         const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
647         LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
648         return value;
649     }
650 
~Capabilities()651     ~Capabilities() {
652         const int result = cap_free(mCaps);
653         LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
654     }
655 
656 private:
657     cap_t mCaps;
658 };
659 
ensureProcessCanBlockSuspend()660 static void ensureProcessCanBlockSuspend() {
661     Capabilities capabilities;
662     const bool canBlockSuspend =
663             capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
664     LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
665                         "Input must be able to block suspend to properly process events");
666 }
667 
668 // --- EventHub ---
669 
670 const int EventHub::EPOLL_MAX_EVENTS;
671 
EventHub(void)672 EventHub::EventHub(void)
673       : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
674         mNextDeviceId(1),
675         mControllerNumbers(),
676         mNeedToSendFinishedDeviceScan(false),
677         mNeedToReopenDevices(false),
678         mNeedToScanDevices(true),
679         mPendingEventCount(0),
680         mPendingEventIndex(0),
681         mPendingINotify(false) {
682     ensureProcessCanBlockSuspend();
683 
684     mEpollFd = epoll_create1(EPOLL_CLOEXEC);
685     LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
686 
687     mINotifyFd = inotify_init();
688     mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
689     LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
690                         strerror(errno));
691     if (isV4lScanningEnabled()) {
692         mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
693         LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
694                             VIDEO_DEVICE_PATH, strerror(errno));
695     } else {
696         mVideoWd = -1;
697         ALOGI("Video device scanning disabled");
698     }
699 
700     struct epoll_event eventItem = {};
701     eventItem.events = EPOLLIN | EPOLLWAKEUP;
702     eventItem.data.fd = mINotifyFd;
703     int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
704     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance.  errno=%d", errno);
705 
706     int wakeFds[2];
707     result = pipe(wakeFds);
708     LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe.  errno=%d", errno);
709 
710     mWakeReadPipeFd = wakeFds[0];
711     mWakeWritePipeFd = wakeFds[1];
712 
713     result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
714     LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking.  errno=%d",
715                         errno);
716 
717     result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
718     LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking.  errno=%d",
719                         errno);
720 
721     eventItem.data.fd = mWakeReadPipeFd;
722     result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
723     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance.  errno=%d",
724                         errno);
725 }
726 
~EventHub(void)727 EventHub::~EventHub(void) {
728     closeAllDevicesLocked();
729 
730     ::close(mEpollFd);
731     ::close(mINotifyFd);
732     ::close(mWakeReadPipeFd);
733     ::close(mWakeWritePipeFd);
734 }
735 
getDeviceIdentifier(int32_t deviceId) const736 InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
737     std::scoped_lock _l(mLock);
738     Device* device = getDeviceLocked(deviceId);
739     return device != nullptr ? device->identifier : InputDeviceIdentifier();
740 }
741 
getDeviceClasses(int32_t deviceId) const742 Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
743     std::scoped_lock _l(mLock);
744     Device* device = getDeviceLocked(deviceId);
745     return device != nullptr ? device->classes : Flags<InputDeviceClass>(0);
746 }
747 
getDeviceControllerNumber(int32_t deviceId) const748 int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
749     std::scoped_lock _l(mLock);
750     Device* device = getDeviceLocked(deviceId);
751     return device != nullptr ? device->controllerNumber : 0;
752 }
753 
getConfiguration(int32_t deviceId,PropertyMap * outConfiguration) const754 void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
755     std::scoped_lock _l(mLock);
756     Device* device = getDeviceLocked(deviceId);
757     if (device != nullptr && device->configuration) {
758         *outConfiguration = *device->configuration;
759     } else {
760         outConfiguration->clear();
761     }
762 }
763 
getAbsoluteAxisInfo(int32_t deviceId,int axis,RawAbsoluteAxisInfo * outAxisInfo) const764 status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
765                                        RawAbsoluteAxisInfo* outAxisInfo) const {
766     outAxisInfo->clear();
767 
768     if (axis >= 0 && axis <= ABS_MAX) {
769         std::scoped_lock _l(mLock);
770 
771         Device* device = getDeviceLocked(deviceId);
772         if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
773             struct input_absinfo info;
774             if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
775                 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
776                       device->identifier.name.c_str(), device->fd, errno);
777                 return -errno;
778             }
779 
780             if (info.minimum != info.maximum) {
781                 outAxisInfo->valid = true;
782                 outAxisInfo->minValue = info.minimum;
783                 outAxisInfo->maxValue = info.maximum;
784                 outAxisInfo->flat = info.flat;
785                 outAxisInfo->fuzz = info.fuzz;
786                 outAxisInfo->resolution = info.resolution;
787             }
788             return OK;
789         }
790     }
791     return -1;
792 }
793 
hasRelativeAxis(int32_t deviceId,int axis) const794 bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
795     if (axis >= 0 && axis <= REL_MAX) {
796         std::scoped_lock _l(mLock);
797         Device* device = getDeviceLocked(deviceId);
798         return device != nullptr ? device->relBitmask.test(axis) : false;
799     }
800     return false;
801 }
802 
hasInputProperty(int32_t deviceId,int property) const803 bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
804     std::scoped_lock _l(mLock);
805 
806     Device* device = getDeviceLocked(deviceId);
807     return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
808             ? device->propBitmask.test(property)
809             : false;
810 }
811 
hasMscEvent(int32_t deviceId,int mscEvent) const812 bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
813     std::scoped_lock _l(mLock);
814 
815     Device* device = getDeviceLocked(deviceId);
816     return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
817             ? device->mscBitmask.test(mscEvent)
818             : false;
819 }
820 
getScanCodeState(int32_t deviceId,int32_t scanCode) const821 int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
822     if (scanCode >= 0 && scanCode <= KEY_MAX) {
823         std::scoped_lock _l(mLock);
824 
825         Device* device = getDeviceLocked(deviceId);
826         if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
827             if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
828                 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
829             }
830         }
831     }
832     return AKEY_STATE_UNKNOWN;
833 }
834 
getKeyCodeState(int32_t deviceId,int32_t keyCode) const835 int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
836     std::scoped_lock _l(mLock);
837 
838     Device* device = getDeviceLocked(deviceId);
839     if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
840         std::vector<int32_t> scanCodes;
841         device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
842         if (scanCodes.size() != 0) {
843             if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
844                 for (size_t i = 0; i < scanCodes.size(); i++) {
845                     int32_t sc = scanCodes[i];
846                     if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
847                         return AKEY_STATE_DOWN;
848                     }
849                 }
850                 return AKEY_STATE_UP;
851             }
852         }
853     }
854     return AKEY_STATE_UNKNOWN;
855 }
856 
getSwitchState(int32_t deviceId,int32_t sw) const857 int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
858     if (sw >= 0 && sw <= SW_MAX) {
859         std::scoped_lock _l(mLock);
860 
861         Device* device = getDeviceLocked(deviceId);
862         if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
863             if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
864                 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
865             }
866         }
867     }
868     return AKEY_STATE_UNKNOWN;
869 }
870 
getAbsoluteAxisValue(int32_t deviceId,int32_t axis,int32_t * outValue) const871 status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
872     *outValue = 0;
873 
874     if (axis >= 0 && axis <= ABS_MAX) {
875         std::scoped_lock _l(mLock);
876 
877         Device* device = getDeviceLocked(deviceId);
878         if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
879             struct input_absinfo info;
880             if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
881                 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
882                       device->identifier.name.c_str(), device->fd, errno);
883                 return -errno;
884             }
885 
886             *outValue = info.value;
887             return OK;
888         }
889     }
890     return -1;
891 }
892 
markSupportedKeyCodes(int32_t deviceId,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags) const893 bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
894                                      uint8_t* outFlags) const {
895     std::scoped_lock _l(mLock);
896 
897     Device* device = getDeviceLocked(deviceId);
898     if (device != nullptr && device->keyMap.haveKeyLayout()) {
899         std::vector<int32_t> scanCodes;
900         for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
901             scanCodes.clear();
902 
903             status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
904                                                                             &scanCodes);
905             if (!err) {
906                 // check the possible scan codes identified by the layout map against the
907                 // map of codes actually emitted by the driver
908                 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
909                     if (device->keyBitmask.test(scanCodes[sc])) {
910                         outFlags[codeIndex] = 1;
911                         break;
912                     }
913                 }
914             }
915         }
916         return true;
917     }
918     return false;
919 }
920 
mapKey(int32_t deviceId,int32_t scanCode,int32_t usageCode,int32_t metaState,int32_t * outKeycode,int32_t * outMetaState,uint32_t * outFlags) const921 status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
922                           int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
923     std::scoped_lock _l(mLock);
924     Device* device = getDeviceLocked(deviceId);
925     status_t status = NAME_NOT_FOUND;
926 
927     if (device != nullptr) {
928         // Check the key character map first.
929         const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
930         if (kcm) {
931             if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
932                 *outFlags = 0;
933                 status = NO_ERROR;
934             }
935         }
936 
937         // Check the key layout next.
938         if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
939             if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
940                 status = NO_ERROR;
941             }
942         }
943 
944         if (status == NO_ERROR) {
945             if (kcm) {
946                 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
947             } else {
948                 *outMetaState = metaState;
949             }
950         }
951     }
952 
953     if (status != NO_ERROR) {
954         *outKeycode = 0;
955         *outFlags = 0;
956         *outMetaState = metaState;
957     }
958 
959     return status;
960 }
961 
mapAxis(int32_t deviceId,int32_t scanCode,AxisInfo * outAxisInfo) const962 status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
963     std::scoped_lock _l(mLock);
964     Device* device = getDeviceLocked(deviceId);
965 
966     if (device != nullptr && device->keyMap.haveKeyLayout()) {
967         status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
968         if (err == NO_ERROR) {
969             return NO_ERROR;
970         }
971     }
972 
973     return NAME_NOT_FOUND;
974 }
975 
mapSensor(int32_t deviceId,int32_t absCode)976 base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
977                                                                             int32_t absCode) {
978     std::scoped_lock _l(mLock);
979     Device* device = getDeviceLocked(deviceId);
980 
981     if (device != nullptr && device->keyMap.haveKeyLayout()) {
982         return device->keyMap.keyLayoutMap->mapSensor(absCode);
983     }
984     return Errorf("Device not found or device has no key layout.");
985 }
986 
987 // Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
988 // associated with the device ID. Returns an empty map if no miscellaneous device found.
getBatteryInfoLocked(int32_t deviceId) const989 const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
990         int32_t deviceId) const {
991     static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
992     Device* device = getDeviceLocked(deviceId);
993     if (device == nullptr || !device->associatedDevice) {
994         return EMPTY_BATTERY_INFO;
995     }
996     return device->associatedDevice->batteryInfos;
997 }
998 
getRawBatteryIds(int32_t deviceId)999 const std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) {
1000     std::scoped_lock _l(mLock);
1001     std::vector<int32_t> batteryIds;
1002 
1003     for (const auto [id, info] : getBatteryInfoLocked(deviceId)) {
1004         batteryIds.push_back(id);
1005     }
1006 
1007     return batteryIds;
1008 }
1009 
getRawBatteryInfo(int32_t deviceId,int32_t batteryId)1010 std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId, int32_t batteryId) {
1011     std::scoped_lock _l(mLock);
1012 
1013     const auto infos = getBatteryInfoLocked(deviceId);
1014 
1015     auto it = infos.find(batteryId);
1016     if (it != infos.end()) {
1017         return it->second;
1018     }
1019 
1020     return std::nullopt;
1021 }
1022 
1023 // Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
1024 // with the deivice ID. Returns an empty map if no miscellaneous device found.
getLightInfoLocked(int32_t deviceId) const1025 const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1026         int32_t deviceId) const {
1027     static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1028     Device* device = getDeviceLocked(deviceId);
1029     if (device == nullptr || !device->associatedDevice) {
1030         return EMPTY_LIGHT_INFO;
1031     }
1032     return device->associatedDevice->lightInfos;
1033 }
1034 
getRawLightIds(int32_t deviceId)1035 const std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) {
1036     std::scoped_lock _l(mLock);
1037     std::vector<int32_t> lightIds;
1038 
1039     for (const auto [id, info] : getLightInfoLocked(deviceId)) {
1040         lightIds.push_back(id);
1041     }
1042 
1043     return lightIds;
1044 }
1045 
getRawLightInfo(int32_t deviceId,int32_t lightId)1046 std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) {
1047     std::scoped_lock _l(mLock);
1048 
1049     const auto infos = getLightInfoLocked(deviceId);
1050 
1051     auto it = infos.find(lightId);
1052     if (it != infos.end()) {
1053         return it->second;
1054     }
1055 
1056     return std::nullopt;
1057 }
1058 
getLightBrightness(int32_t deviceId,int32_t lightId)1059 std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) {
1060     std::scoped_lock _l(mLock);
1061 
1062     const auto infos = getLightInfoLocked(deviceId);
1063     auto it = infos.find(lightId);
1064     if (it == infos.end()) {
1065         return std::nullopt;
1066     }
1067     std::string buffer;
1068     if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1069                                 &buffer)) {
1070         return std::nullopt;
1071     }
1072     return std::stoi(buffer);
1073 }
1074 
getLightIntensities(int32_t deviceId,int32_t lightId)1075 std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1076         int32_t deviceId, int32_t lightId) {
1077     std::scoped_lock _l(mLock);
1078 
1079     const auto infos = getLightInfoLocked(deviceId);
1080     auto lightIt = infos.find(lightId);
1081     if (lightIt == infos.end()) {
1082         return std::nullopt;
1083     }
1084 
1085     auto ret =
1086             getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1087 
1088     if (!ret.has_value()) {
1089         return std::nullopt;
1090     }
1091     std::array<LightColor, COLOR_NUM> colors = ret.value();
1092 
1093     std::string intensityStr;
1094     if (!base::ReadFileToString(lightIt->second.path /
1095                                         LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1096                                 &intensityStr)) {
1097         return std::nullopt;
1098     }
1099 
1100     // Intensity node outputs 3 color values
1101     std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1102     std::smatch results;
1103 
1104     if (!std::regex_match(intensityStr, results, intensityPattern)) {
1105         return std::nullopt;
1106     }
1107     std::unordered_map<LightColor, int32_t> intensities;
1108     for (size_t i = 1; i < results.size(); i++) {
1109         int value = std::stoi(results[i].str());
1110         intensities.emplace(colors[i - 1], value);
1111     }
1112     return intensities;
1113 }
1114 
setLightBrightness(int32_t deviceId,int32_t lightId,int32_t brightness)1115 void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1116     std::scoped_lock _l(mLock);
1117 
1118     const auto infos = getLightInfoLocked(deviceId);
1119     auto lightIt = infos.find(lightId);
1120     if (lightIt == infos.end()) {
1121         ALOGE("%s lightId %d not found ", __func__, lightId);
1122         return;
1123     }
1124 
1125     if (!base::WriteStringToFile(std::to_string(brightness),
1126                                  lightIt->second.path /
1127                                          LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1128         ALOGE("Can not write to file, error: %s", strerror(errno));
1129     }
1130 }
1131 
setLightIntensities(int32_t deviceId,int32_t lightId,std::unordered_map<LightColor,int32_t> intensities)1132 void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1133                                    std::unordered_map<LightColor, int32_t> intensities) {
1134     std::scoped_lock _l(mLock);
1135 
1136     const auto infos = getLightInfoLocked(deviceId);
1137     auto lightIt = infos.find(lightId);
1138     if (lightIt == infos.end()) {
1139         ALOGE("Light Id %d does not exist.", lightId);
1140         return;
1141     }
1142 
1143     auto ret =
1144             getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1145 
1146     if (!ret.has_value()) {
1147         return;
1148     }
1149     std::array<LightColor, COLOR_NUM> colors = ret.value();
1150 
1151     std::string rgbStr;
1152     for (size_t i = 0; i < COLOR_NUM; i++) {
1153         auto it = intensities.find(colors[i]);
1154         if (it != intensities.end()) {
1155             rgbStr += std::to_string(it->second);
1156             // Insert space between colors
1157             if (i < COLOR_NUM - 1) {
1158                 rgbStr += " ";
1159             }
1160         }
1161     }
1162     // Append new line
1163     rgbStr += "\n";
1164 
1165     if (!base::WriteStringToFile(rgbStr,
1166                                  lightIt->second.path /
1167                                          LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1168         ALOGE("Can not write to file, error: %s", strerror(errno));
1169     }
1170 }
1171 
setExcludedDevices(const std::vector<std::string> & devices)1172 void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
1173     std::scoped_lock _l(mLock);
1174 
1175     mExcludedDevices = devices;
1176 }
1177 
hasScanCode(int32_t deviceId,int32_t scanCode) const1178 bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
1179     std::scoped_lock _l(mLock);
1180     Device* device = getDeviceLocked(deviceId);
1181     if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1182         return device->keyBitmask.test(scanCode);
1183     }
1184     return false;
1185 }
1186 
hasLed(int32_t deviceId,int32_t led) const1187 bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
1188     std::scoped_lock _l(mLock);
1189     Device* device = getDeviceLocked(deviceId);
1190     int32_t sc;
1191     if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
1192         return device->ledBitmask.test(sc);
1193     }
1194     return false;
1195 }
1196 
setLedState(int32_t deviceId,int32_t led,bool on)1197 void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
1198     std::scoped_lock _l(mLock);
1199     Device* device = getDeviceLocked(deviceId);
1200     if (device != nullptr && device->hasValidFd()) {
1201         device->setLedStateLocked(led, on);
1202     }
1203 }
1204 
getVirtualKeyDefinitions(int32_t deviceId,std::vector<VirtualKeyDefinition> & outVirtualKeys) const1205 void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
1206                                         std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
1207     outVirtualKeys.clear();
1208 
1209     std::scoped_lock _l(mLock);
1210     Device* device = getDeviceLocked(deviceId);
1211     if (device != nullptr && device->virtualKeyMap) {
1212         const std::vector<VirtualKeyDefinition> virtualKeys =
1213                 device->virtualKeyMap->getVirtualKeys();
1214         outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
1215     }
1216 }
1217 
getKeyCharacterMap(int32_t deviceId) const1218 const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
1219     std::scoped_lock _l(mLock);
1220     Device* device = getDeviceLocked(deviceId);
1221     if (device != nullptr) {
1222         return device->getKeyCharacterMap();
1223     }
1224     return nullptr;
1225 }
1226 
setKeyboardLayoutOverlay(int32_t deviceId,std::shared_ptr<KeyCharacterMap> map)1227 bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
1228     std::scoped_lock _l(mLock);
1229     Device* device = getDeviceLocked(deviceId);
1230     if (device != nullptr && map != nullptr && device->keyMap.keyCharacterMap != nullptr) {
1231         device->keyMap.keyCharacterMap->combine(*map);
1232         device->keyMap.keyCharacterMapFile = device->keyMap.keyCharacterMap->getLoadFileName();
1233         return true;
1234     }
1235     return false;
1236 }
1237 
generateDescriptor(InputDeviceIdentifier & identifier)1238 static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1239     std::string rawDescriptor;
1240     rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
1241     // TODO add handling for USB devices to not uniqueify kbs that show up twice
1242     if (!identifier.uniqueId.empty()) {
1243         rawDescriptor += "uniqueId:";
1244         rawDescriptor += identifier.uniqueId;
1245     } else if (identifier.nonce != 0) {
1246         rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
1247     }
1248 
1249     if (identifier.vendor == 0 && identifier.product == 0) {
1250         // If we don't know the vendor and product id, then the device is probably
1251         // built-in so we need to rely on other information to uniquely identify
1252         // the input device.  Usually we try to avoid relying on the device name or
1253         // location but for built-in input device, they are unlikely to ever change.
1254         if (!identifier.name.empty()) {
1255             rawDescriptor += "name:";
1256             rawDescriptor += identifier.name;
1257         } else if (!identifier.location.empty()) {
1258             rawDescriptor += "location:";
1259             rawDescriptor += identifier.location;
1260         }
1261     }
1262     identifier.descriptor = sha1(rawDescriptor);
1263     return rawDescriptor;
1264 }
1265 
assignDescriptorLocked(InputDeviceIdentifier & identifier)1266 void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1267     // Compute a device descriptor that uniquely identifies the device.
1268     // The descriptor is assumed to be a stable identifier.  Its value should not
1269     // change between reboots, reconnections, firmware updates or new releases
1270     // of Android. In practice we sometimes get devices that cannot be uniquely
1271     // identified. In this case we enforce uniqueness between connected devices.
1272     // Ideally, we also want the descriptor to be short and relatively opaque.
1273 
1274     identifier.nonce = 0;
1275     std::string rawDescriptor = generateDescriptor(identifier);
1276     if (identifier.uniqueId.empty()) {
1277         // If it didn't have a unique id check for conflicts and enforce
1278         // uniqueness if necessary.
1279         while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
1280             identifier.nonce++;
1281             rawDescriptor = generateDescriptor(identifier);
1282         }
1283     }
1284     ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
1285           identifier.descriptor.c_str());
1286 }
1287 
vibrate(int32_t deviceId,const VibrationElement & element)1288 void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
1289     std::scoped_lock _l(mLock);
1290     Device* device = getDeviceLocked(deviceId);
1291     if (device != nullptr && device->hasValidFd()) {
1292         ff_effect effect;
1293         memset(&effect, 0, sizeof(effect));
1294         effect.type = FF_RUMBLE;
1295         effect.id = device->ffEffectId;
1296         // evdev FF_RUMBLE effect only supports two channels of vibration.
1297         effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1298         effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1299         effect.replay.length = element.duration.count();
1300         effect.replay.delay = 0;
1301         if (ioctl(device->fd, EVIOCSFF, &effect)) {
1302             ALOGW("Could not upload force feedback effect to device %s due to error %d.",
1303                   device->identifier.name.c_str(), errno);
1304             return;
1305         }
1306         device->ffEffectId = effect.id;
1307 
1308         struct input_event ev;
1309         ev.time.tv_sec = 0;
1310         ev.time.tv_usec = 0;
1311         ev.type = EV_FF;
1312         ev.code = device->ffEffectId;
1313         ev.value = 1;
1314         if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1315             ALOGW("Could not start force feedback effect on device %s due to error %d.",
1316                   device->identifier.name.c_str(), errno);
1317             return;
1318         }
1319         device->ffEffectPlaying = true;
1320     }
1321 }
1322 
cancelVibrate(int32_t deviceId)1323 void EventHub::cancelVibrate(int32_t deviceId) {
1324     std::scoped_lock _l(mLock);
1325     Device* device = getDeviceLocked(deviceId);
1326     if (device != nullptr && device->hasValidFd()) {
1327         if (device->ffEffectPlaying) {
1328             device->ffEffectPlaying = false;
1329 
1330             struct input_event ev;
1331             ev.time.tv_sec = 0;
1332             ev.time.tv_usec = 0;
1333             ev.type = EV_FF;
1334             ev.code = device->ffEffectId;
1335             ev.value = 0;
1336             if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1337                 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
1338                       device->identifier.name.c_str(), errno);
1339                 return;
1340             }
1341         }
1342     }
1343 }
1344 
getVibratorIds(int32_t deviceId)1345 std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) {
1346     std::scoped_lock _l(mLock);
1347     std::vector<int32_t> vibrators;
1348     Device* device = getDeviceLocked(deviceId);
1349     if (device != nullptr && device->hasValidFd() &&
1350         device->classes.test(InputDeviceClass::VIBRATOR)) {
1351         vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1352         vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1353     }
1354     return vibrators;
1355 }
1356 
getDeviceByDescriptorLocked(const std::string & descriptor) const1357 EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
1358     for (const auto& [id, device] : mDevices) {
1359         if (descriptor == device->identifier.descriptor) {
1360             return device.get();
1361         }
1362     }
1363     return nullptr;
1364 }
1365 
getDeviceLocked(int32_t deviceId) const1366 EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
1367     if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
1368         deviceId = mBuiltInKeyboardId;
1369     }
1370     const auto& it = mDevices.find(deviceId);
1371     return it != mDevices.end() ? it->second.get() : nullptr;
1372 }
1373 
getDeviceByPathLocked(const std::string & devicePath) const1374 EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
1375     for (const auto& [id, device] : mDevices) {
1376         if (device->path == devicePath) {
1377             return device.get();
1378         }
1379     }
1380     return nullptr;
1381 }
1382 
1383 /**
1384  * The file descriptor could be either input device, or a video device (associated with a
1385  * specific input device). Check both cases here, and return the device that this event
1386  * belongs to. Caller can compare the fd's once more to determine event type.
1387  * Looks through all input devices, and only attached video devices. Unattached video
1388  * devices are ignored.
1389  */
getDeviceByFdLocked(int fd) const1390 EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
1391     for (const auto& [id, device] : mDevices) {
1392         if (device->fd == fd) {
1393             // This is an input device event
1394             return device.get();
1395         }
1396         if (device->videoDevice && device->videoDevice->getFd() == fd) {
1397             // This is a video device event
1398             return device.get();
1399         }
1400     }
1401     // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1402     // and therefore should never be looked up by fd.
1403     return nullptr;
1404 }
1405 
getBatteryCapacity(int32_t deviceId,int32_t batteryId) const1406 std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
1407     std::scoped_lock _l(mLock);
1408 
1409     const auto infos = getBatteryInfoLocked(deviceId);
1410     auto it = infos.find(batteryId);
1411     if (it == infos.end()) {
1412         return std::nullopt;
1413     }
1414     std::string buffer;
1415 
1416     // Some devices report battery capacity as an integer through the "capacity" file
1417     if (base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
1418                                &buffer)) {
1419         return std::stoi(base::Trim(buffer));
1420     }
1421 
1422     // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1423     // These values are taken from kernel source code include/linux/power_supply.h
1424     if (base::ReadFileToString(it->second.path /
1425                                        BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
1426                                &buffer)) {
1427         // Remove any white space such as trailing new line
1428         const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1429         if (levelIt != BATTERY_LEVEL.end()) {
1430             return levelIt->second;
1431         }
1432     }
1433 
1434     return std::nullopt;
1435 }
1436 
getBatteryStatus(int32_t deviceId,int32_t batteryId) const1437 std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
1438     std::scoped_lock _l(mLock);
1439     const auto infos = getBatteryInfoLocked(deviceId);
1440     auto it = infos.find(batteryId);
1441     if (it == infos.end()) {
1442         return std::nullopt;
1443     }
1444     std::string buffer;
1445 
1446     if (!base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::STATUS),
1447                                 &buffer)) {
1448         ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1449         return std::nullopt;
1450     }
1451 
1452     // Remove white space like trailing new line
1453     const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1454     if (statusIt != BATTERY_STATUS.end()) {
1455         return statusIt->second;
1456     }
1457 
1458     return std::nullopt;
1459 }
1460 
getEvents(int timeoutMillis,RawEvent * buffer,size_t bufferSize)1461 size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1462     ALOG_ASSERT(bufferSize >= 1);
1463 
1464     std::scoped_lock _l(mLock);
1465 
1466     struct input_event readBuffer[bufferSize];
1467 
1468     RawEvent* event = buffer;
1469     size_t capacity = bufferSize;
1470     bool awoken = false;
1471     for (;;) {
1472         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1473 
1474         // Reopen input devices if needed.
1475         if (mNeedToReopenDevices) {
1476             mNeedToReopenDevices = false;
1477 
1478             ALOGI("Reopening all input devices due to a configuration change.");
1479 
1480             closeAllDevicesLocked();
1481             mNeedToScanDevices = true;
1482             break; // return to the caller before we actually rescan
1483         }
1484 
1485         // Report any devices that had last been added/removed.
1486         for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1487             std::unique_ptr<Device> device = std::move(*it);
1488             ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
1489             event->when = now;
1490             event->deviceId = (device->id == mBuiltInKeyboardId)
1491                     ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1492                     : device->id;
1493             event->type = DEVICE_REMOVED;
1494             event += 1;
1495             it = mClosingDevices.erase(it);
1496             mNeedToSendFinishedDeviceScan = true;
1497             if (--capacity == 0) {
1498                 break;
1499             }
1500         }
1501 
1502         if (mNeedToScanDevices) {
1503             mNeedToScanDevices = false;
1504             scanDevicesLocked();
1505             mNeedToSendFinishedDeviceScan = true;
1506         }
1507 
1508         while (!mOpeningDevices.empty()) {
1509             std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1510             mOpeningDevices.pop_back();
1511             ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
1512             event->when = now;
1513             event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1514             event->type = DEVICE_ADDED;
1515             event += 1;
1516 
1517             // Try to find a matching video device by comparing device names
1518             for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1519                  it++) {
1520                 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
1521                 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
1522                     // videoDevice was transferred to 'device'
1523                     it = mUnattachedVideoDevices.erase(it);
1524                     break;
1525                 }
1526             }
1527 
1528             auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1529             if (!inserted) {
1530                 ALOGW("Device id %d exists, replaced.", device->id);
1531             }
1532             mNeedToSendFinishedDeviceScan = true;
1533             if (--capacity == 0) {
1534                 break;
1535             }
1536         }
1537 
1538         if (mNeedToSendFinishedDeviceScan) {
1539             mNeedToSendFinishedDeviceScan = false;
1540             event->when = now;
1541             event->type = FINISHED_DEVICE_SCAN;
1542             event += 1;
1543             if (--capacity == 0) {
1544                 break;
1545             }
1546         }
1547 
1548         // Grab the next input event.
1549         bool deviceChanged = false;
1550         while (mPendingEventIndex < mPendingEventCount) {
1551             const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
1552             if (eventItem.data.fd == mINotifyFd) {
1553                 if (eventItem.events & EPOLLIN) {
1554                     mPendingINotify = true;
1555                 } else {
1556                     ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1557                 }
1558                 continue;
1559             }
1560 
1561             if (eventItem.data.fd == mWakeReadPipeFd) {
1562                 if (eventItem.events & EPOLLIN) {
1563                     ALOGV("awoken after wake()");
1564                     awoken = true;
1565                     char wakeReadBuffer[16];
1566                     ssize_t nRead;
1567                     do {
1568                         nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1569                     } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
1570                 } else {
1571                     ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
1572                           eventItem.events);
1573                 }
1574                 continue;
1575             }
1576 
1577             Device* device = getDeviceByFdLocked(eventItem.data.fd);
1578             if (device == nullptr) {
1579                 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1580                       eventItem.data.fd);
1581                 ALOG_ASSERT(!DEBUG);
1582                 continue;
1583             }
1584             if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1585                 if (eventItem.events & EPOLLIN) {
1586                     size_t numFrames = device->videoDevice->readAndQueueFrames();
1587                     if (numFrames == 0) {
1588                         ALOGE("Received epoll event for video device %s, but could not read frame",
1589                               device->videoDevice->getName().c_str());
1590                     }
1591                 } else if (eventItem.events & EPOLLHUP) {
1592                     // TODO(b/121395353) - consider adding EPOLLRDHUP
1593                     ALOGI("Removing video device %s due to epoll hang-up event.",
1594                           device->videoDevice->getName().c_str());
1595                     unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1596                     device->videoDevice = nullptr;
1597                 } else {
1598                     ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1599                           device->videoDevice->getName().c_str());
1600                     ALOG_ASSERT(!DEBUG);
1601                 }
1602                 continue;
1603             }
1604             // This must be an input event
1605             if (eventItem.events & EPOLLIN) {
1606                 int32_t readSize =
1607                         read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
1608                 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1609                     // Device was removed before INotify noticed.
1610                     ALOGW("could not get event, removed? (fd: %d size: %" PRId32
1611                           " bufferSize: %zu capacity: %zu errno: %d)\n",
1612                           device->fd, readSize, bufferSize, capacity, errno);
1613                     deviceChanged = true;
1614                     closeDeviceLocked(*device);
1615                 } else if (readSize < 0) {
1616                     if (errno != EAGAIN && errno != EINTR) {
1617                         ALOGW("could not get event (errno=%d)", errno);
1618                     }
1619                 } else if ((readSize % sizeof(struct input_event)) != 0) {
1620                     ALOGE("could not get event (wrong size: %d)", readSize);
1621                 } else {
1622                     int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1623 
1624                     size_t count = size_t(readSize) / sizeof(struct input_event);
1625                     for (size_t i = 0; i < count; i++) {
1626                         struct input_event& iev = readBuffer[i];
1627                         event->when = processEventTimestamp(iev);
1628                         event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
1629                         event->deviceId = deviceId;
1630                         event->type = iev.type;
1631                         event->code = iev.code;
1632                         event->value = iev.value;
1633                         event += 1;
1634                         capacity -= 1;
1635                     }
1636                     if (capacity == 0) {
1637                         // The result buffer is full.  Reset the pending event index
1638                         // so we will try to read the device again on the next iteration.
1639                         mPendingEventIndex -= 1;
1640                         break;
1641                     }
1642                 }
1643             } else if (eventItem.events & EPOLLHUP) {
1644                 ALOGI("Removing device %s due to epoll hang-up event.",
1645                       device->identifier.name.c_str());
1646                 deviceChanged = true;
1647                 closeDeviceLocked(*device);
1648             } else {
1649                 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1650                       device->identifier.name.c_str());
1651             }
1652         }
1653 
1654         // readNotify() will modify the list of devices so this must be done after
1655         // processing all other events to ensure that we read all remaining events
1656         // before closing the devices.
1657         if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1658             mPendingINotify = false;
1659             readNotifyLocked();
1660             deviceChanged = true;
1661         }
1662 
1663         // Report added or removed devices immediately.
1664         if (deviceChanged) {
1665             continue;
1666         }
1667 
1668         // Return now if we have collected any events or if we were explicitly awoken.
1669         if (event != buffer || awoken) {
1670             break;
1671         }
1672 
1673         // Poll for events.
1674         // When a device driver has pending (unread) events, it acquires
1675         // a kernel wake lock.  Once the last pending event has been read, the device
1676         // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1677         // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1678         // is called again for the same fd that produced the event.
1679         // Thus the system can only sleep if there are no events pending or
1680         // currently being processed.
1681         //
1682         // The timeout is advisory only.  If the device is asleep, it will not wake just to
1683         // service the timeout.
1684         mPendingEventIndex = 0;
1685 
1686         mLock.unlock(); // release lock before poll
1687 
1688         int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1689 
1690         mLock.lock(); // reacquire lock after poll
1691 
1692         if (pollResult == 0) {
1693             // Timed out.
1694             mPendingEventCount = 0;
1695             break;
1696         }
1697 
1698         if (pollResult < 0) {
1699             // An error occurred.
1700             mPendingEventCount = 0;
1701 
1702             // Sleep after errors to avoid locking up the system.
1703             // Hopefully the error is transient.
1704             if (errno != EINTR) {
1705                 ALOGW("poll failed (errno=%d)\n", errno);
1706                 usleep(100000);
1707             }
1708         } else {
1709             // Some events occurred.
1710             mPendingEventCount = size_t(pollResult);
1711         }
1712     }
1713 
1714     // All done, return the number of events we read.
1715     return event - buffer;
1716 }
1717 
getVideoFrames(int32_t deviceId)1718 std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1719     std::scoped_lock _l(mLock);
1720 
1721     Device* device = getDeviceLocked(deviceId);
1722     if (device == nullptr || !device->videoDevice) {
1723         return {};
1724     }
1725     return device->videoDevice->consumeFrames();
1726 }
1727 
wake()1728 void EventHub::wake() {
1729     ALOGV("wake() called");
1730 
1731     ssize_t nWrite;
1732     do {
1733         nWrite = write(mWakeWritePipeFd, "W", 1);
1734     } while (nWrite == -1 && errno == EINTR);
1735 
1736     if (nWrite != 1 && errno != EAGAIN) {
1737         ALOGW("Could not write wake signal: %s", strerror(errno));
1738     }
1739 }
1740 
scanDevicesLocked()1741 void EventHub::scanDevicesLocked() {
1742     status_t result = scanDirLocked(DEVICE_PATH);
1743     if (result < 0) {
1744         ALOGE("scan dir failed for %s", DEVICE_PATH);
1745     }
1746     if (isV4lScanningEnabled()) {
1747         result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1748         if (result != OK) {
1749             ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1750         }
1751     }
1752     if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
1753         createVirtualKeyboardLocked();
1754     }
1755 }
1756 
1757 // ----------------------------------------------------------------------------
1758 
1759 static const int32_t GAMEPAD_KEYCODES[] = {
1760         AKEYCODE_BUTTON_A,      AKEYCODE_BUTTON_B,      AKEYCODE_BUTTON_C,    //
1761         AKEYCODE_BUTTON_X,      AKEYCODE_BUTTON_Y,      AKEYCODE_BUTTON_Z,    //
1762         AKEYCODE_BUTTON_L1,     AKEYCODE_BUTTON_R1,                           //
1763         AKEYCODE_BUTTON_L2,     AKEYCODE_BUTTON_R2,                           //
1764         AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,                       //
1765         AKEYCODE_BUTTON_START,  AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
1766 };
1767 
registerFdForEpoll(int fd)1768 status_t EventHub::registerFdForEpoll(int fd) {
1769     // TODO(b/121395353) - consider adding EPOLLRDHUP
1770     struct epoll_event eventItem = {};
1771     eventItem.events = EPOLLIN | EPOLLWAKEUP;
1772     eventItem.data.fd = fd;
1773     if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1774         ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
1775         return -errno;
1776     }
1777     return OK;
1778 }
1779 
unregisterFdFromEpoll(int fd)1780 status_t EventHub::unregisterFdFromEpoll(int fd) {
1781     if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1782         ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1783         return -errno;
1784     }
1785     return OK;
1786 }
1787 
registerDeviceForEpollLocked(Device & device)1788 status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1789     status_t result = registerFdForEpoll(device.fd);
1790     if (result != OK) {
1791         ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
1792         return result;
1793     }
1794     if (device.videoDevice) {
1795         registerVideoDeviceForEpollLocked(*device.videoDevice);
1796     }
1797     return result;
1798 }
1799 
registerVideoDeviceForEpollLocked(const TouchVideoDevice & videoDevice)1800 void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1801     status_t result = registerFdForEpoll(videoDevice.getFd());
1802     if (result != OK) {
1803         ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1804     }
1805 }
1806 
unregisterDeviceFromEpollLocked(Device & device)1807 status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1808     if (device.hasValidFd()) {
1809         status_t result = unregisterFdFromEpoll(device.fd);
1810         if (result != OK) {
1811             ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
1812             return result;
1813         }
1814     }
1815     if (device.videoDevice) {
1816         unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
1817     }
1818     return OK;
1819 }
1820 
unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice & videoDevice)1821 void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1822     if (videoDevice.hasValidFd()) {
1823         status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1824         if (result != OK) {
1825             ALOGW("Could not remove video device fd from epoll for device: %s",
1826                   videoDevice.getName().c_str());
1827         }
1828     }
1829 }
1830 
reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier & identifier,Flags<InputDeviceClass> classes)1831 void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
1832                                                     Flags<InputDeviceClass> classes) {
1833     SHA256_CTX ctx;
1834     SHA256_Init(&ctx);
1835     SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
1836                   identifier.uniqueId.size());
1837     std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
1838     SHA256_Final(digest.data(), &ctx);
1839 
1840     std::string obfuscatedId;
1841     for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
1842         obfuscatedId += StringPrintf("%02x", digest[i]);
1843     }
1844 
1845     android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
1846                                identifier.vendor, identifier.product, identifier.version,
1847                                identifier.bus, obfuscatedId.c_str(), classes.get());
1848 }
1849 
openDeviceLocked(const std::string & devicePath)1850 void EventHub::openDeviceLocked(const std::string& devicePath) {
1851     // If an input device happens to register around the time when EventHub's constructor runs, it
1852     // is possible that the same input event node (for example, /dev/input/event3) will be noticed
1853     // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
1854     // from getting registered, ensure that this path is not already covered by an existing device.
1855     for (const auto& [deviceId, device] : mDevices) {
1856         if (device->path == devicePath) {
1857             return; // device was already registered
1858         }
1859     }
1860 
1861     char buffer[80];
1862 
1863     ALOGV("Opening device: %s", devicePath.c_str());
1864 
1865     int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
1866     if (fd < 0) {
1867         ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
1868         return;
1869     }
1870 
1871     InputDeviceIdentifier identifier;
1872 
1873     // Get device name.
1874     if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1875         ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
1876     } else {
1877         buffer[sizeof(buffer) - 1] = '\0';
1878         identifier.name = buffer;
1879     }
1880 
1881     // Check to see if the device is on our excluded list
1882     for (size_t i = 0; i < mExcludedDevices.size(); i++) {
1883         const std::string& item = mExcludedDevices[i];
1884         if (identifier.name == item) {
1885             ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
1886             close(fd);
1887             return;
1888         }
1889     }
1890 
1891     // Get device driver version.
1892     int driverVersion;
1893     if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1894         ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
1895         close(fd);
1896         return;
1897     }
1898 
1899     // Get device identifier.
1900     struct input_id inputId;
1901     if (ioctl(fd, EVIOCGID, &inputId)) {
1902         ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
1903         close(fd);
1904         return;
1905     }
1906     identifier.bus = inputId.bustype;
1907     identifier.product = inputId.product;
1908     identifier.vendor = inputId.vendor;
1909     identifier.version = inputId.version;
1910 
1911     // Get device physical location.
1912     if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1913         // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1914     } else {
1915         buffer[sizeof(buffer) - 1] = '\0';
1916         identifier.location = buffer;
1917     }
1918 
1919     // Get device unique id.
1920     if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1921         // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1922     } else {
1923         buffer[sizeof(buffer) - 1] = '\0';
1924         identifier.uniqueId = buffer;
1925     }
1926 
1927     // Fill in the descriptor.
1928     assignDescriptorLocked(identifier);
1929 
1930     // Allocate device.  (The device object takes ownership of the fd at this point.)
1931     int32_t deviceId = mNextDeviceId++;
1932     std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
1933 
1934     ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
1935     ALOGV("  bus:        %04x\n"
1936           "  vendor      %04x\n"
1937           "  product     %04x\n"
1938           "  version     %04x\n",
1939           identifier.bus, identifier.vendor, identifier.product, identifier.version);
1940     ALOGV("  name:       \"%s\"\n", identifier.name.c_str());
1941     ALOGV("  location:   \"%s\"\n", identifier.location.c_str());
1942     ALOGV("  unique id:  \"%s\"\n", identifier.uniqueId.c_str());
1943     ALOGV("  descriptor: \"%s\"\n", identifier.descriptor.c_str());
1944     ALOGV("  driver:     v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1945           driverVersion & 0xff);
1946 
1947     // Load the configuration file for the device.
1948     device->loadConfigurationLocked();
1949 
1950     bool hasBattery = false;
1951     bool hasLights = false;
1952     // Check the sysfs root path
1953     std::optional<std::filesystem::path> sysfsRootPath = getSysfsRootPath(devicePath.c_str());
1954     if (sysfsRootPath.has_value()) {
1955         std::shared_ptr<AssociatedDevice> associatedDevice;
1956         for (const auto& [id, dev] : mDevices) {
1957             if (device->identifier.descriptor == dev->identifier.descriptor &&
1958                 !dev->associatedDevice) {
1959                 associatedDevice = dev->associatedDevice;
1960             }
1961         }
1962         if (!associatedDevice) {
1963             associatedDevice = std::make_shared<AssociatedDevice>(sysfsRootPath.value());
1964         }
1965         hasBattery = associatedDevice->configureBatteryLocked();
1966         hasLights = associatedDevice->configureLightsLocked();
1967 
1968         device->associatedDevice = associatedDevice;
1969     }
1970 
1971     // Figure out the kinds of events the device reports.
1972     device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
1973     device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
1974     device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
1975     device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
1976     device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
1977     device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
1978     device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
1979     device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
1980 
1981     // See if this is a keyboard.  Ignore everything in the button range except for
1982     // joystick and gamepad buttons which are handled like keyboards for the most part.
1983     bool haveKeyboardKeys =
1984             device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
1985     bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
1986             device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
1987     if (haveKeyboardKeys || haveGamepadButtons) {
1988         device->classes |= InputDeviceClass::KEYBOARD;
1989     }
1990 
1991     // See if this is a cursor device such as a trackball or mouse.
1992     if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
1993         device->relBitmask.test(REL_Y)) {
1994         device->classes |= InputDeviceClass::CURSOR;
1995     }
1996 
1997     // See if this is a rotary encoder type device.
1998     String8 deviceType = String8();
1999     if (device->configuration &&
2000         device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
2001         if (!deviceType.compare(String8("rotaryEncoder"))) {
2002             device->classes |= InputDeviceClass::ROTARY_ENCODER;
2003         }
2004     }
2005 
2006     // See if this is a touch pad.
2007     // Is this a new modern multi-touch driver?
2008     if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
2009         // Some joysticks such as the PS3 controller report axes that conflict
2010         // with the ABS_MT range.  Try to confirm that the device really is
2011         // a touch screen.
2012         if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
2013             device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
2014         }
2015         // Is this an old style single-touch driver?
2016     } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2017                device->absBitmask.test(ABS_Y)) {
2018         device->classes |= InputDeviceClass::TOUCH;
2019         // Is this a BT stylus?
2020     } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2021                !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
2022         device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2023         // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2024         // can fuse it with the touch screen data, so just take them back. Note this means an
2025         // external stylus cannot also be a keyboard device.
2026         device->classes &= ~InputDeviceClass::KEYBOARD;
2027     }
2028 
2029     // See if this device is a joystick.
2030     // Assumes that joysticks always have gamepad buttons in order to distinguish them
2031     // from other devices such as accelerometers that also have absolute axes.
2032     if (haveGamepadButtons) {
2033         auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
2034         for (int i = 0; i <= ABS_MAX; i++) {
2035             if (device->absBitmask.test(i) &&
2036                 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
2037                 device->classes = assumedClasses;
2038                 break;
2039             }
2040         }
2041     }
2042 
2043     // Check whether this device is an accelerometer.
2044     if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2045         device->classes |= InputDeviceClass::SENSOR;
2046     }
2047 
2048     // Check whether this device has switches.
2049     for (int i = 0; i <= SW_MAX; i++) {
2050         if (device->swBitmask.test(i)) {
2051             device->classes |= InputDeviceClass::SWITCH;
2052             break;
2053         }
2054     }
2055 
2056     // Check whether this device supports the vibrator.
2057     if (device->ffBitmask.test(FF_RUMBLE)) {
2058         device->classes |= InputDeviceClass::VIBRATOR;
2059     }
2060 
2061     // Configure virtual keys.
2062     if ((device->classes.test(InputDeviceClass::TOUCH))) {
2063         // Load the virtual keys for the touch screen, if any.
2064         // We do this now so that we can make sure to load the keymap if necessary.
2065         bool success = device->loadVirtualKeyMapLocked();
2066         if (success) {
2067             device->classes |= InputDeviceClass::KEYBOARD;
2068         }
2069     }
2070 
2071     // Load the key map.
2072     // We need to do this for joysticks too because the key layout may specify axes, and for
2073     // sensor as well because the key layout may specify the axes to sensor data mapping.
2074     status_t keyMapStatus = NAME_NOT_FOUND;
2075     if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2076                             InputDeviceClass::SENSOR)) {
2077         // Load the keymap for the device.
2078         keyMapStatus = device->loadKeyMapLocked();
2079     }
2080 
2081     // Configure the keyboard, gamepad or virtual keyboard.
2082     if (device->classes.test(InputDeviceClass::KEYBOARD)) {
2083         // Register the keyboard as a built-in keyboard if it is eligible.
2084         if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
2085             isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2086                                       &device->keyMap)) {
2087             mBuiltInKeyboardId = device->id;
2088         }
2089 
2090         // 'Q' key support = cheap test of whether this is an alpha-capable kbd
2091         if (device->hasKeycodeLocked(AKEYCODE_Q)) {
2092             device->classes |= InputDeviceClass::ALPHAKEY;
2093         }
2094 
2095         // See if this device has a DPAD.
2096         if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2097             device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2098             device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2099             device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2100             device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
2101             device->classes |= InputDeviceClass::DPAD;
2102         }
2103 
2104         // See if this device has a gamepad.
2105         for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
2106             if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
2107                 device->classes |= InputDeviceClass::GAMEPAD;
2108                 break;
2109             }
2110         }
2111     }
2112 
2113     // If the device isn't recognized as something we handle, don't monitor it.
2114     if (device->classes == Flags<InputDeviceClass>(0)) {
2115         ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
2116               device->identifier.name.c_str());
2117         return;
2118     }
2119 
2120     // Classify InputDeviceClass::BATTERY.
2121     if (hasBattery) {
2122         device->classes |= InputDeviceClass::BATTERY;
2123     }
2124 
2125     // Classify InputDeviceClass::LIGHT.
2126     if (hasLights) {
2127         device->classes |= InputDeviceClass::LIGHT;
2128     }
2129 
2130     // Determine whether the device has a mic.
2131     if (device->deviceHasMicLocked()) {
2132         device->classes |= InputDeviceClass::MIC;
2133     }
2134 
2135     // Determine whether the device is external or internal.
2136     if (device->isExternalDeviceLocked()) {
2137         device->classes |= InputDeviceClass::EXTERNAL;
2138     }
2139 
2140     if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2141         device->classes.test(InputDeviceClass::GAMEPAD)) {
2142         device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2143         device->setLedForControllerLocked();
2144     }
2145 
2146     if (registerDeviceForEpollLocked(*device) != OK) {
2147         return;
2148     }
2149 
2150     device->configureFd();
2151 
2152     ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
2153           "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
2154           deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2155           device->classes.string().c_str(), device->configurationFile.c_str(),
2156           device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2157           toString(mBuiltInKeyboardId == deviceId));
2158 
2159     addDeviceLocked(std::move(device));
2160 }
2161 
openVideoDeviceLocked(const std::string & devicePath)2162 void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2163     std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2164     if (!videoDevice) {
2165         ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2166         return;
2167     }
2168     // Transfer ownership of this video device to a matching input device
2169     for (const auto& [id, device] : mDevices) {
2170         if (tryAddVideoDeviceLocked(*device, videoDevice)) {
2171             return; // 'device' now owns 'videoDevice'
2172         }
2173     }
2174 
2175     // Couldn't find a matching input device, so just add it to a temporary holding queue.
2176     // A matching input device may appear later.
2177     ALOGI("Adding video device %s to list of unattached video devices",
2178           videoDevice->getName().c_str());
2179     mUnattachedVideoDevices.push_back(std::move(videoDevice));
2180 }
2181 
tryAddVideoDeviceLocked(EventHub::Device & device,std::unique_ptr<TouchVideoDevice> & videoDevice)2182 bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2183                                        std::unique_ptr<TouchVideoDevice>& videoDevice) {
2184     if (videoDevice->getName() != device.identifier.name) {
2185         return false;
2186     }
2187     device.videoDevice = std::move(videoDevice);
2188     if (device.enabled) {
2189         registerVideoDeviceForEpollLocked(*device.videoDevice);
2190     }
2191     return true;
2192 }
2193 
isDeviceEnabled(int32_t deviceId)2194 bool EventHub::isDeviceEnabled(int32_t deviceId) {
2195     std::scoped_lock _l(mLock);
2196     Device* device = getDeviceLocked(deviceId);
2197     if (device == nullptr) {
2198         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2199         return false;
2200     }
2201     return device->enabled;
2202 }
2203 
enableDevice(int32_t deviceId)2204 status_t EventHub::enableDevice(int32_t deviceId) {
2205     std::scoped_lock _l(mLock);
2206     Device* device = getDeviceLocked(deviceId);
2207     if (device == nullptr) {
2208         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2209         return BAD_VALUE;
2210     }
2211     if (device->enabled) {
2212         ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2213         return OK;
2214     }
2215     status_t result = device->enable();
2216     if (result != OK) {
2217         ALOGE("Failed to enable device %" PRId32, deviceId);
2218         return result;
2219     }
2220 
2221     device->configureFd();
2222 
2223     return registerDeviceForEpollLocked(*device);
2224 }
2225 
disableDevice(int32_t deviceId)2226 status_t EventHub::disableDevice(int32_t deviceId) {
2227     std::scoped_lock _l(mLock);
2228     Device* device = getDeviceLocked(deviceId);
2229     if (device == nullptr) {
2230         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2231         return BAD_VALUE;
2232     }
2233     if (!device->enabled) {
2234         ALOGW("Duplicate call to %s, input device already disabled", __func__);
2235         return OK;
2236     }
2237     unregisterDeviceFromEpollLocked(*device);
2238     return device->disable();
2239 }
2240 
createVirtualKeyboardLocked()2241 void EventHub::createVirtualKeyboardLocked() {
2242     InputDeviceIdentifier identifier;
2243     identifier.name = "Virtual";
2244     identifier.uniqueId = "<virtual>";
2245     assignDescriptorLocked(identifier);
2246 
2247     std::unique_ptr<Device> device =
2248             std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2249                                      identifier);
2250     device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2251             InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
2252     device->loadKeyMapLocked();
2253     addDeviceLocked(std::move(device));
2254 }
2255 
addDeviceLocked(std::unique_ptr<Device> device)2256 void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
2257     reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
2258     mOpeningDevices.push_back(std::move(device));
2259 }
2260 
getNextControllerNumberLocked(const std::string & name)2261 int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
2262     if (mControllerNumbers.isFull()) {
2263         ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
2264               name.c_str());
2265         return 0;
2266     }
2267     // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2268     // one
2269     return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2270 }
2271 
releaseControllerNumberLocked(int32_t num)2272 void EventHub::releaseControllerNumberLocked(int32_t num) {
2273     if (num > 0) {
2274         mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
2275     }
2276 }
2277 
closeDeviceByPathLocked(const std::string & devicePath)2278 void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
2279     Device* device = getDeviceByPathLocked(devicePath);
2280     if (device != nullptr) {
2281         closeDeviceLocked(*device);
2282         return;
2283     }
2284     ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
2285 }
2286 
2287 /**
2288  * Find the video device by filename, and close it.
2289  * The video device is closed by path during an inotify event, where we don't have the
2290  * additional context about the video device fd, or the associated input device.
2291  */
closeVideoDeviceByPathLocked(const std::string & devicePath)2292 void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
2293     // A video device may be owned by an existing input device, or it may be stored in
2294     // the mUnattachedVideoDevices queue. Check both locations.
2295     for (const auto& [id, device] : mDevices) {
2296         if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
2297             unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
2298             device->videoDevice = nullptr;
2299             return;
2300         }
2301     }
2302     mUnattachedVideoDevices
2303             .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
2304                                   [&devicePath](
2305                                           const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2306                                       return videoDevice->getPath() == devicePath;
2307                                   }),
2308                    mUnattachedVideoDevices.end());
2309 }
2310 
closeAllDevicesLocked()2311 void EventHub::closeAllDevicesLocked() {
2312     mUnattachedVideoDevices.clear();
2313     while (!mDevices.empty()) {
2314         closeDeviceLocked(*(mDevices.begin()->second));
2315     }
2316 }
2317 
closeDeviceLocked(Device & device)2318 void EventHub::closeDeviceLocked(Device& device) {
2319     ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2320           device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
2321 
2322     if (device.id == mBuiltInKeyboardId) {
2323         ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
2324               device.path.c_str(), mBuiltInKeyboardId);
2325         mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2326     }
2327 
2328     unregisterDeviceFromEpollLocked(device);
2329     if (device.videoDevice) {
2330         // This must be done after the video device is removed from epoll
2331         mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
2332     }
2333 
2334     releaseControllerNumberLocked(device.controllerNumber);
2335     device.controllerNumber = 0;
2336     device.close();
2337     mClosingDevices.push_back(std::move(mDevices[device.id]));
2338 
2339     mDevices.erase(device.id);
2340 }
2341 
readNotifyLocked()2342 status_t EventHub::readNotifyLocked() {
2343     int res;
2344     char event_buf[512];
2345     int event_size;
2346     int event_pos = 0;
2347     struct inotify_event* event;
2348 
2349     ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2350     res = read(mINotifyFd, event_buf, sizeof(event_buf));
2351     if (res < (int)sizeof(*event)) {
2352         if (errno == EINTR) return 0;
2353         ALOGW("could not get event, %s\n", strerror(errno));
2354         return -1;
2355     }
2356 
2357     while (res >= (int)sizeof(*event)) {
2358         event = (struct inotify_event*)(event_buf + event_pos);
2359         if (event->len) {
2360             if (event->wd == mInputWd) {
2361                 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
2362                 if (event->mask & IN_CREATE) {
2363                     openDeviceLocked(filename);
2364                 } else {
2365                     ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2366                     closeDeviceByPathLocked(filename);
2367                 }
2368             } else if (event->wd == mVideoWd) {
2369                 if (isV4lTouchNode(event->name)) {
2370                     std::string filename = std::string(VIDEO_DEVICE_PATH) + "/" + event->name;
2371                     if (event->mask & IN_CREATE) {
2372                         openVideoDeviceLocked(filename);
2373                     } else {
2374                         ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2375                         closeVideoDeviceByPathLocked(filename);
2376                     }
2377                 }
2378             } else {
2379                 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
2380             }
2381         }
2382         event_size = sizeof(*event) + event->len;
2383         res -= event_size;
2384         event_pos += event_size;
2385     }
2386     return 0;
2387 }
2388 
scanDirLocked(const std::string & dirname)2389 status_t EventHub::scanDirLocked(const std::string& dirname) {
2390     for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2391         openDeviceLocked(entry.path());
2392     }
2393     return 0;
2394 }
2395 
2396 /**
2397  * Look for all dirname/v4l-touch* devices, and open them.
2398  */
scanVideoDirLocked(const std::string & dirname)2399 status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
2400     for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2401         if (isV4lTouchNode(entry.path())) {
2402             ALOGI("Found touch video device %s", entry.path().c_str());
2403             openVideoDeviceLocked(entry.path());
2404         }
2405     }
2406     return OK;
2407 }
2408 
requestReopenDevices()2409 void EventHub::requestReopenDevices() {
2410     ALOGV("requestReopenDevices() called");
2411 
2412     std::scoped_lock _l(mLock);
2413     mNeedToReopenDevices = true;
2414 }
2415 
dump(std::string & dump)2416 void EventHub::dump(std::string& dump) {
2417     dump += "Event Hub State:\n";
2418 
2419     { // acquire lock
2420         std::scoped_lock _l(mLock);
2421 
2422         dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
2423 
2424         dump += INDENT "Devices:\n";
2425 
2426         for (const auto& [id, device] : mDevices) {
2427             if (mBuiltInKeyboardId == device->id) {
2428                 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
2429                                      device->id, device->identifier.name.c_str());
2430             } else {
2431                 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
2432                                      device->identifier.name.c_str());
2433             }
2434             dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
2435             dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
2436             dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
2437             dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2438             dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
2439             dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
2440             dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
2441             dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
2442                                          "product=0x%04x, version=0x%04x\n",
2443                                  device->identifier.bus, device->identifier.vendor,
2444                                  device->identifier.product, device->identifier.version);
2445             dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
2446                                  device->keyMap.keyLayoutFile.c_str());
2447             dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
2448                                  device->keyMap.keyCharacterMapFile.c_str());
2449             dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
2450                                  device->configurationFile.c_str());
2451             dump += INDENT3 "VideoDevice: ";
2452             if (device->videoDevice) {
2453                 dump += device->videoDevice->dump() + "\n";
2454             } else {
2455                 dump += "<none>\n";
2456             }
2457         }
2458 
2459         dump += INDENT "Unattached video devices:\n";
2460         for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2461             dump += INDENT2 + videoDevice->dump() + "\n";
2462         }
2463         if (mUnattachedVideoDevices.empty()) {
2464             dump += INDENT2 "<none>\n";
2465         }
2466     } // release lock
2467 }
2468 
monitor()2469 void EventHub::monitor() {
2470     // Acquire and release the lock to ensure that the event hub has not deadlocked.
2471     std::unique_lock<std::mutex> lock(mLock);
2472 }
2473 
2474 }; // namespace android
2475