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 <linux/ioctl.h>
23 #include <memory.h>
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/capability.h>
29 #include <sys/epoll.h>
30 #include <sys/inotify.h>
31 #include <sys/ioctl.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 <ftl/enum.h>
44 #include <input/KeyCharacterMap.h>
45 #include <input/KeyLayoutMap.h>
46 #include <input/PrintTools.h>
47 #include <input/VirtualKeyMap.h>
48 #include <openssl/sha.h>
49 #include <statslog.h>
50 #include <utils/Errors.h>
51 #include <utils/Log.h>
52 #include <utils/Timers.h>
53 
54 #include <filesystem>
55 #include <optional>
56 #include <regex>
57 #include <utility>
58 
59 #include "EventHub.h"
60 
61 #include "KeyCodeClassifications.h"
62 
63 #define INDENT "  "
64 #define INDENT2 "    "
65 #define INDENT3 "      "
66 
67 using android::base::StringPrintf;
68 
69 namespace android {
70 
71 using namespace ftl::flag_operators;
72 
73 static const char* DEVICE_INPUT_PATH = "/dev/input";
74 // v4l2 devices go directly into /dev
75 static const char* DEVICE_PATH = "/dev";
76 
77 static constexpr size_t OBFUSCATED_LENGTH = 8;
78 
79 static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
80 static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
81 
82 static constexpr size_t EVENT_BUFFER_SIZE = 256;
83 
84 // Mapping for input battery class node IDs lookup.
85 // https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
86 static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
87         {{"capacity", InputBatteryClass::CAPACITY},
88          {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
89          {"status", InputBatteryClass::STATUS}};
90 
91 // Mapping for input battery class node names lookup.
92 // https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
93 static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
94         {{InputBatteryClass::CAPACITY, "capacity"},
95          {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
96          {InputBatteryClass::STATUS, "status"}};
97 
98 // must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
99 static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
100         {{"Unknown", BATTERY_STATUS_UNKNOWN},
101          {"Charging", BATTERY_STATUS_CHARGING},
102          {"Discharging", BATTERY_STATUS_DISCHARGING},
103          {"Not charging", BATTERY_STATUS_NOT_CHARGING},
104          {"Full", BATTERY_STATUS_FULL}};
105 
106 // Mapping taken from
107 // https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
108 static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
109                                                                        {"Low", 10},
110                                                                        {"Normal", 55},
111                                                                        {"High", 70},
112                                                                        {"Full", 100},
113                                                                        {"Unknown", 50}};
114 
115 // Mapping for input led class node names lookup.
116 // https://www.kernel.org/doc/html/latest/leds/leds-class.html
117 static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
118         {{"red", InputLightClass::RED},
119          {"green", InputLightClass::GREEN},
120          {"blue", InputLightClass::BLUE},
121          {"global", InputLightClass::GLOBAL},
122          {"brightness", InputLightClass::BRIGHTNESS},
123          {"multi_index", InputLightClass::MULTI_INDEX},
124          {"multi_intensity", InputLightClass::MULTI_INTENSITY},
125          {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
126          {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT},
127          {"mic_mute", InputLightClass::KEYBOARD_MIC_MUTE}};
128 
129 // Mapping for input multicolor led class node names.
130 // https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
131 static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
132         {{InputLightClass::BRIGHTNESS, "brightness"},
133          {InputLightClass::MULTI_INDEX, "multi_index"},
134          {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
135 
136 // Mapping for light color name and the light color
137 const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
138                                                                   {"green", LightColor::GREEN},
139                                                                   {"blue", LightColor::BLUE}};
140 
141 // Mapping for country code to Layout info.
142 // See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
143 const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
144         {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}},             // NOT_SUPPORTED
145          {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}},      // ARABIC
146          {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}},        // BELGIAN
147          {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}},        // CANADIAN_BILINGUAL
148          {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}},        // CANADIAN_FRENCH
149          {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}},           // CZECH_REPUBLIC
150          {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}},           // DANISH
151          {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}},           // FINNISH
152          {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}},        // FRENCH
153          {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}},           // GERMAN
154          {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}},          // GREEK
155          {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}},          // HEBREW
156          {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}},          // HUNGARY
157          {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}},  // INTERNATIONAL (ISO)
158          {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}},          // ITALIAN
159          {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}},          // JAPAN
160          {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}},          // KOREAN
161          {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}},      // LATIN_AMERICA
162          {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}},          // DUTCH
163          {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}},          // NORWEGIAN
164          {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}},          // PERSIAN
165          {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}},          // POLAND
166          {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}},          // PORTUGUESE
167          {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}},          // RUSSIA
168          {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}},          // SLOVAKIA
169          {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}},       // SPANISH
170          {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}},          // SWEDISH
171          {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}},       // SWISS_FRENCH
172          {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}},       // SWISS_GERMAN
173          {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}},       // SWITZERLAND
174          {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}},       // TAIWAN
175          {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
176          {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}},       // UK
177          {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}},       // US
178          {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}},            // YUGOSLAVIA
179          {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
180 
sha1(const std::string & in)181 static std::string sha1(const std::string& in) {
182     SHA_CTX ctx;
183     SHA1_Init(&ctx);
184     SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
185     u_char digest[SHA_DIGEST_LENGTH];
186     SHA1_Final(digest, &ctx);
187 
188     std::string out;
189     for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
190         out += StringPrintf("%02x", digest[i]);
191     }
192     return out;
193 }
194 
195 /**
196  * Return true if name matches "v4l-touch*"
197  */
isV4lTouchNode(std::string name)198 static bool isV4lTouchNode(std::string name) {
199     return name.find("v4l-touch") != std::string::npos;
200 }
201 
202 /**
203  * Returns true if V4L devices should be scanned.
204  *
205  * The system property ro.input.video_enabled can be used to control whether
206  * EventHub scans and opens V4L devices. As V4L does not support multiple
207  * clients, EventHub effectively blocks access to these devices when it opens
208  * them.
209  *
210  * Setting this to "false" would prevent any video devices from being discovered and
211  * associated with input devices.
212  *
213  * This property can be used as follows:
214  * 1. To turn off features that are dependent on video device presence.
215  * 2. During testing and development, to allow other clients to read video devices
216  * directly from /dev.
217  */
isV4lScanningEnabled()218 static bool isV4lScanningEnabled() {
219     return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
220 }
221 
processEventTimestamp(const struct input_event & event)222 static nsecs_t processEventTimestamp(const struct input_event& event) {
223     // Use the time specified in the event instead of the current time
224     // so that downstream code can get more accurate estimates of
225     // event dispatch latency from the time the event is enqueued onto
226     // the evdev client buffer.
227     //
228     // The event's timestamp fortuitously uses the same monotonic clock
229     // time base as the rest of Android. The kernel event device driver
230     // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
231     // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
232     // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
233     // system call that also queries ktime_get_ts().
234 
235     const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
236             microseconds_to_nanoseconds(event.input_event_usec);
237     return inputEventTime;
238 }
239 
240 /**
241  * Returns the sysfs root path of the input device.
242  */
getSysfsRootPath(const char * devicePath)243 static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
244     std::error_code errorCode;
245 
246     // Stat the device path to get the major and minor number of the character file
247     struct stat statbuf;
248     if (stat(devicePath, &statbuf) == -1) {
249         ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
250         return std::nullopt;
251     }
252 
253     unsigned int major_num = major(statbuf.st_rdev);
254     unsigned int minor_num = minor(statbuf.st_rdev);
255 
256     // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
257     auto sysfsPath = std::filesystem::path("/sys/dev/char/");
258     sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
259     sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
260 
261     // Make sure nothing went wrong in call to canonical()
262     if (errorCode) {
263         ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
264               errorCode.message().c_str());
265         return std::nullopt;
266     }
267 
268     // Continue to go up a directory until we reach a directory named "input"
269     while (sysfsPath != "/" && sysfsPath.filename() != "input") {
270         sysfsPath = sysfsPath.parent_path();
271     }
272 
273     // Then go up one more and you will be at the sysfs root of the device
274     sysfsPath = sysfsPath.parent_path();
275 
276     // Make sure we didn't reach root path and that directory actually exists
277     if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
278         if (errorCode) {
279             ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
280                   errorCode.message().c_str());
281         }
282 
283         // Not found
284         return std::nullopt;
285     }
286 
287     return sysfsPath;
288 }
289 
290 /**
291  * Returns the list of files under a specified path.
292  */
allFilesInPath(const std::filesystem::path & path)293 static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
294     std::vector<std::filesystem::path> nodes;
295     std::error_code errorCode;
296     auto iter = std::filesystem::directory_iterator(path, errorCode);
297     while (!errorCode && iter != std::filesystem::directory_iterator()) {
298         nodes.push_back(iter->path());
299         iter++;
300     }
301     return nodes;
302 }
303 
304 /**
305  * Returns the list of files under a specified directory in a sysfs path.
306  * Example:
307  * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
308  * in the sysfs path.
309  */
findSysfsNodes(const std::filesystem::path & sysfsRoot,SysfsClass clazz)310 static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
311                                                          SysfsClass clazz) {
312     std::string nodeStr = ftl::enum_string(clazz);
313     std::for_each(nodeStr.begin(), nodeStr.end(),
314                   [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
315     std::vector<std::filesystem::path> nodes;
316     for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
317         nodes = allFilesInPath(path / nodeStr);
318     }
319     return nodes;
320 }
321 
getColorIndexArray(std::filesystem::path path)322 static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
323         std::filesystem::path path) {
324     std::string indexStr;
325     if (!base::ReadFileToString(path, &indexStr)) {
326         return std::nullopt;
327     }
328 
329     // Parse the multi color LED index file, refer to kernel docs
330     // leds/leds-class-multicolor.html
331     std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
332     std::smatch results;
333     std::array<LightColor, COLOR_NUM> colors;
334     if (!std::regex_match(indexStr, results, indexPattern)) {
335         return std::nullopt;
336     }
337 
338     for (size_t i = 1; i < results.size(); i++) {
339         const auto it = LIGHT_COLORS.find(results[i].str());
340         if (it != LIGHT_COLORS.end()) {
341             // intensities.emplace(it->second, 0);
342             colors[i - 1] = it->second;
343         }
344     }
345     return colors;
346 }
347 
348 /**
349  * Read country code information exposed through the sysfs path and convert it to Layout info.
350  */
readLayoutConfiguration(const std::filesystem::path & sysfsRootPath)351 static std::optional<RawLayoutInfo> readLayoutConfiguration(
352         const std::filesystem::path& sysfsRootPath) {
353     // Check the sysfs root path
354     int32_t hidCountryCode = -1;
355     std::string str;
356     if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
357         hidCountryCode = std::stoi(str, nullptr, 16);
358         // Update this condition if new supported country codes are added to HID spec.
359         if (hidCountryCode > 35 || hidCountryCode < 0) {
360             ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
361                   sysfsRootPath.c_str(), hidCountryCode);
362         }
363     }
364     const auto it = LAYOUT_INFOS.find(hidCountryCode);
365     if (it != LAYOUT_INFOS.end()) {
366         return it->second;
367     }
368 
369     return std::nullopt;
370 }
371 
372 /**
373  * Read information about batteries exposed through the sysfs path.
374  */
readBatteryConfiguration(const std::filesystem::path & sysfsRootPath)375 static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
376         const std::filesystem::path& sysfsRootPath) {
377     std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
378     int32_t nextBatteryId = 0;
379     // Check if device has any battery.
380     const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
381     for (const auto& nodePath : paths) {
382         RawBatteryInfo info;
383         info.id = ++nextBatteryId;
384         info.path = nodePath;
385         info.name = nodePath.filename();
386 
387         // Scan the path for all the files
388         // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
389         const auto& files = allFilesInPath(nodePath);
390         for (const auto& file : files) {
391             const auto it = BATTERY_CLASSES.find(file.filename().string());
392             if (it != BATTERY_CLASSES.end()) {
393                 info.flags |= it->second;
394             }
395         }
396         batteryInfos.insert_or_assign(info.id, info);
397         ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
398     }
399     return batteryInfos;
400 }
401 
402 /**
403  *  Read information about lights exposed through the sysfs path.
404  */
readLightsConfiguration(const std::filesystem::path & sysfsRootPath)405 static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
406         const std::filesystem::path& sysfsRootPath) {
407     std::unordered_map<int32_t, RawLightInfo> lightInfos;
408     int32_t nextLightId = 0;
409     // Check if device has any lights.
410     const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
411     for (const auto& nodePath : paths) {
412         RawLightInfo info;
413         info.id = ++nextLightId;
414         info.path = nodePath;
415         info.name = nodePath.filename();
416         info.maxBrightness = std::nullopt;
417 
418         // Light name should follow the naming pattern <name>:<color>:<function>
419         // Refer kernel docs /leds/leds-class.html for valid supported LED names.
420         std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
421         std::smatch results;
422 
423         if (std::regex_match(info.name, results, indexPattern)) {
424             // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
425             // we only care about sections <color> and <function> which will be at index 2 and 3.
426             for (int i = 2; i <= 3; i++) {
427                 const auto it = LIGHT_CLASSES.find(results.str(i));
428                 if (it != LIGHT_CLASSES.end()) {
429                     info.flags |= it->second;
430                 }
431             }
432 
433             // Set name of the raw light to <function> which represents playerIDs for LEDs that
434             // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
435             // player ID logic)
436             info.name = results.str(3);
437         }
438         // Scan the path for all the files
439         // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
440         const auto& files = allFilesInPath(nodePath);
441         for (const auto& file : files) {
442             const auto it = LIGHT_CLASSES.find(file.filename().string());
443             if (it != LIGHT_CLASSES.end()) {
444                 info.flags |= it->second;
445                 // If the node has maximum brightness, read it
446                 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
447                     std::string str;
448                     if (base::ReadFileToString(file, &str)) {
449                         info.maxBrightness = std::stoi(str);
450                     }
451                 }
452             }
453         }
454         lightInfos.insert_or_assign(info.id, info);
455         ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
456     }
457     return lightInfos;
458 }
459 
460 // --- Global Functions ---
461 
getAbsAxisUsage(int32_t axis,ftl::Flags<InputDeviceClass> deviceClasses)462 ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
463                                              ftl::Flags<InputDeviceClass> deviceClasses) {
464     // Touch devices get dibs on touch-related axes.
465     if (deviceClasses.test(InputDeviceClass::TOUCH)) {
466         switch (axis) {
467             case ABS_X:
468             case ABS_Y:
469             case ABS_PRESSURE:
470             case ABS_TOOL_WIDTH:
471             case ABS_DISTANCE:
472             case ABS_TILT_X:
473             case ABS_TILT_Y:
474             case ABS_MT_SLOT:
475             case ABS_MT_TOUCH_MAJOR:
476             case ABS_MT_TOUCH_MINOR:
477             case ABS_MT_WIDTH_MAJOR:
478             case ABS_MT_WIDTH_MINOR:
479             case ABS_MT_ORIENTATION:
480             case ABS_MT_POSITION_X:
481             case ABS_MT_POSITION_Y:
482             case ABS_MT_TOOL_TYPE:
483             case ABS_MT_BLOB_ID:
484             case ABS_MT_TRACKING_ID:
485             case ABS_MT_PRESSURE:
486             case ABS_MT_DISTANCE:
487                 return InputDeviceClass::TOUCH;
488         }
489     }
490 
491     if (deviceClasses.test(InputDeviceClass::SENSOR)) {
492         switch (axis) {
493             case ABS_X:
494             case ABS_Y:
495             case ABS_Z:
496             case ABS_RX:
497             case ABS_RY:
498             case ABS_RZ:
499                 return InputDeviceClass::SENSOR;
500         }
501     }
502 
503     // External stylus gets the pressure axis
504     if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
505         if (axis == ABS_PRESSURE) {
506             return InputDeviceClass::EXTERNAL_STYLUS;
507         }
508     }
509 
510     // Joystick devices get the rest.
511     return deviceClasses & InputDeviceClass::JOYSTICK;
512 }
513 
514 // --- RawAbsoluteAxisInfo ---
515 
operator <<(std::ostream & out,const RawAbsoluteAxisInfo & info)516 std::ostream& operator<<(std::ostream& out, const RawAbsoluteAxisInfo& info) {
517     if (info.valid) {
518         out << "min=" << info.minValue << ", max=" << info.maxValue << ", flat=" << info.flat
519             << ", fuzz=" << info.fuzz << ", resolution=" << info.resolution;
520     } else {
521         out << "unknown range";
522     }
523     return out;
524 }
525 
526 // --- EventHub::Device ---
527 
Device(int fd,int32_t id,std::string path,InputDeviceIdentifier identifier,std::shared_ptr<const AssociatedDevice> assocDev)528 EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
529                          std::shared_ptr<const AssociatedDevice> assocDev)
530       : fd(fd),
531         id(id),
532         path(std::move(path)),
533         identifier(std::move(identifier)),
534         classes(0),
535         configuration(nullptr),
536         virtualKeyMap(nullptr),
537         ffEffectPlaying(false),
538         ffEffectId(-1),
539         associatedDevice(std::move(assocDev)),
540         controllerNumber(0),
541         enabled(true),
542         isVirtual(fd < 0),
543         currentFrameDropped(false) {}
544 
~Device()545 EventHub::Device::~Device() {
546     close();
547 }
548 
close()549 void EventHub::Device::close() {
550     if (fd >= 0) {
551         ::close(fd);
552         fd = -1;
553     }
554 }
555 
enable()556 status_t EventHub::Device::enable() {
557     fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
558     if (fd < 0) {
559         ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
560         return -errno;
561     }
562     enabled = true;
563     return OK;
564 }
565 
disable()566 status_t EventHub::Device::disable() {
567     close();
568     enabled = false;
569     return OK;
570 }
571 
hasValidFd() const572 bool EventHub::Device::hasValidFd() const {
573     return !isVirtual && enabled;
574 }
575 
getKeyCharacterMap() const576 const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
577     return keyMap.keyCharacterMap;
578 }
579 
580 template <std::size_t N>
readDeviceBitMask(unsigned long ioctlCode,BitArray<N> & bitArray)581 status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
582     if (!hasValidFd()) {
583         return BAD_VALUE;
584     }
585     if ((_IOC_SIZE(ioctlCode) == 0)) {
586         ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
587     }
588 
589     typename BitArray<N>::Buffer buffer;
590     status_t ret = ioctl(fd, ioctlCode, buffer.data());
591     bitArray.loadFromBuffer(buffer);
592     return ret;
593 }
594 
configureFd()595 void EventHub::Device::configureFd() {
596     // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
597     if (classes.test(InputDeviceClass::KEYBOARD)) {
598         // Disable kernel key repeat since we handle it ourselves
599         unsigned int repeatRate[] = {0, 0};
600         if (ioctl(fd, EVIOCSREP, repeatRate)) {
601             ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
602         }
603     }
604 
605     // Tell the kernel that we want to use the monotonic clock for reporting timestamps
606     // associated with input events.  This is important because the input system
607     // uses the timestamps extensively and assumes they were recorded using the monotonic
608     // clock.
609     int clockId = CLOCK_MONOTONIC;
610     if (classes.test(InputDeviceClass::SENSOR)) {
611         // Each new sensor event should use the same time base as
612         // SystemClock.elapsedRealtimeNanos().
613         clockId = CLOCK_BOOTTIME;
614     }
615     bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
616     ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
617 
618     // Query the initial state of keys and switches, which is tracked by EventHub.
619     readDeviceState();
620 }
621 
readDeviceState()622 void EventHub::Device::readDeviceState() {
623     if (readDeviceBitMask(EVIOCGKEY(0), keyState) < 0) {
624         ALOGD("Unable to query the global key state for %s: %s", path.c_str(), strerror(errno));
625     }
626     if (readDeviceBitMask(EVIOCGSW(0), swState) < 0) {
627         ALOGD("Unable to query the global switch state for %s: %s", path.c_str(), strerror(errno));
628     }
629 
630     // Read absolute axis info and values for all available axes for the device.
631     populateAbsoluteAxisStates();
632 }
633 
populateAbsoluteAxisStates()634 void EventHub::Device::populateAbsoluteAxisStates() {
635     absState.clear();
636 
637     for (int axis = 0; axis <= ABS_MAX; axis++) {
638         if (!absBitmask.test(axis)) {
639             continue;
640         }
641         struct input_absinfo info {};
642         if (ioctl(fd, EVIOCGABS(axis), &info)) {
643             ALOGE("Error reading absolute controller %d for device %s fd %d: %s", axis,
644                   identifier.name.c_str(), fd, strerror(errno));
645             continue;
646         }
647         auto& [axisInfo, value] = absState[axis];
648         axisInfo.valid = true;
649         axisInfo.minValue = info.minimum;
650         axisInfo.maxValue = info.maximum;
651         axisInfo.flat = info.flat;
652         axisInfo.fuzz = info.fuzz;
653         axisInfo.resolution = info.resolution;
654         value = info.value;
655     }
656 }
657 
hasKeycodeLocked(int keycode) const658 bool EventHub::Device::hasKeycodeLocked(int keycode) const {
659     if (!keyMap.haveKeyLayout()) {
660         return false;
661     }
662 
663     std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
664     const size_t N = scanCodes.size();
665     for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
666         int32_t sc = scanCodes[i];
667         if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
668             return true;
669         }
670     }
671 
672     std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
673     if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
674         return true;
675     }
676 
677     return false;
678 }
679 
loadConfigurationLocked()680 void EventHub::Device::loadConfigurationLocked() {
681     configurationFile =
682             getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
683                                                                   InputDeviceConfigurationFileType::
684                                                                           CONFIGURATION);
685     if (configurationFile.empty()) {
686         ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
687     } else {
688         android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
689                 PropertyMap::load(configurationFile.c_str());
690         if (!propertyMap.ok()) {
691             ALOGE("Error loading input device configuration file for device '%s'.  "
692                   "Using default configuration.",
693                   identifier.name.c_str());
694         } else {
695             configuration = std::move(*propertyMap);
696         }
697     }
698 }
699 
loadVirtualKeyMapLocked()700 bool EventHub::Device::loadVirtualKeyMapLocked() {
701     // The virtual key map is supplied by the kernel as a system board property file.
702     std::string propPath = "/sys/board_properties/virtualkeys.";
703     propPath += identifier.getCanonicalName();
704     if (access(propPath.c_str(), R_OK)) {
705         return false;
706     }
707     virtualKeyMap = VirtualKeyMap::load(propPath);
708     return virtualKeyMap != nullptr;
709 }
710 
loadKeyMapLocked()711 status_t EventHub::Device::loadKeyMapLocked() {
712     return keyMap.load(identifier, configuration.get());
713 }
714 
isExternalDeviceLocked()715 bool EventHub::Device::isExternalDeviceLocked() {
716     if (configuration) {
717         std::optional<bool> isInternal = configuration->getBool("device.internal");
718         if (isInternal.has_value()) {
719             return !isInternal.value();
720         }
721     }
722     return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
723 }
724 
deviceHasMicLocked()725 bool EventHub::Device::deviceHasMicLocked() {
726     if (configuration) {
727         std::optional<bool> hasMic = configuration->getBool("audio.mic");
728         if (hasMic.has_value()) {
729             return hasMic.value();
730         }
731     }
732     return false;
733 }
734 
setLedStateLocked(int32_t led,bool on)735 void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
736     int32_t sc;
737     if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
738         struct input_event ev;
739         ev.input_event_sec = 0;
740         ev.input_event_usec = 0;
741         ev.type = EV_LED;
742         ev.code = sc;
743         ev.value = on ? 1 : 0;
744 
745         ssize_t nWrite;
746         do {
747             nWrite = write(fd, &ev, sizeof(struct input_event));
748         } while (nWrite == -1 && errno == EINTR);
749     }
750 }
751 
setLedForControllerLocked()752 void EventHub::Device::setLedForControllerLocked() {
753     for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
754         setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
755     }
756 }
757 
mapLed(int32_t led,int32_t * outScanCode) const758 status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
759     if (!keyMap.haveKeyLayout()) {
760         return NAME_NOT_FOUND;
761     }
762 
763     std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
764     if (scanCode.has_value()) {
765         if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
766             *outScanCode = *scanCode;
767             return NO_ERROR;
768         }
769     }
770     return NAME_NOT_FOUND;
771 }
772 
trackInputEvent(const struct input_event & event)773 void EventHub::Device::trackInputEvent(const struct input_event& event) {
774     switch (event.type) {
775         case EV_KEY: {
776             LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
777                                         !keyState.set(static_cast<size_t>(event.code),
778                                                       event.value != 0),
779                                 "%s: device '%s' received invalid EV_KEY event code: %s value: %d",
780                                 __func__, identifier.name.c_str(),
781                                 InputEventLookup::getLinuxEvdevLabel(EV_KEY, event.code, 1)
782                                         .code.c_str(),
783                                 event.value);
784             break;
785         }
786         case EV_SW: {
787             LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
788                                         !swState.set(static_cast<size_t>(event.code),
789                                                      event.value != 0),
790                                 "%s: device '%s' received invalid EV_SW event code: %s value: %d",
791                                 __func__, identifier.name.c_str(),
792                                 InputEventLookup::getLinuxEvdevLabel(EV_SW, event.code, 1)
793                                         .code.c_str(),
794                                 event.value);
795             break;
796         }
797         case EV_ABS: {
798             if (currentFrameDropped) {
799                 break;
800             }
801             auto it = absState.find(event.code);
802             LOG_ALWAYS_FATAL_IF(it == absState.end(),
803                                 "%s: device '%s' received invalid EV_ABS event code: %s value: %d",
804                                 __func__, identifier.name.c_str(),
805                                 InputEventLookup::getLinuxEvdevLabel(EV_ABS, event.code, 0)
806                                         .code.c_str(),
807                                 event.value);
808             it->second.value = event.value;
809             break;
810         }
811         case EV_SYN: {
812             switch (event.code) {
813                 case SYN_REPORT:
814                     if (currentFrameDropped) {
815                         // To recover after a SYN_DROPPED, we need to query the state of the device
816                         // to synchronize our device state with the kernel's to account for the
817                         // dropped events on receiving the next SYN_REPORT.
818                         // Note we don't drop the SYN_REPORT at this point but it is used by the
819                         // InputDevice to reset and repopulate mapper state
820                         readDeviceState();
821                         currentFrameDropped = false;
822                     }
823                     break;
824                 case SYN_DROPPED:
825                     // When we receive SYN_DROPPED, all events in the current frame should be
826                     // dropped up to and including next SYN_REPORT
827                     currentFrameDropped = true;
828                     break;
829                 default:
830                     break;
831             }
832             break;
833         }
834         default:
835             break;
836     }
837 }
838 
839 /**
840  * Get the capabilities for the current process.
841  * Crashes the system if unable to create / check / destroy the capabilities object.
842  */
843 class Capabilities final {
844 public:
Capabilities()845     explicit Capabilities() {
846         mCaps = cap_get_proc();
847         LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
848     }
849 
850     /**
851      * Check whether the current process has a specific capability
852      * in the set of effective capabilities.
853      * Return CAP_SET if the process has the requested capability
854      * Return CAP_CLEAR otherwise.
855      */
checkEffectiveCapability(cap_value_t capability)856     cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
857         cap_flag_value_t value;
858         const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
859         LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
860         return value;
861     }
862 
~Capabilities()863     ~Capabilities() {
864         const int result = cap_free(mCaps);
865         LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
866     }
867 
868 private:
869     cap_t mCaps;
870 };
871 
ensureProcessCanBlockSuspend()872 static void ensureProcessCanBlockSuspend() {
873     Capabilities capabilities;
874     const bool canBlockSuspend =
875             capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
876     LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
877                         "Input must be able to block suspend to properly process events");
878 }
879 
880 // --- EventHub ---
881 
882 const int EventHub::EPOLL_MAX_EVENTS;
883 
EventHub(void)884 EventHub::EventHub(void)
885       : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
886         mNextDeviceId(1),
887         mControllerNumbers(),
888         mNeedToSendFinishedDeviceScan(false),
889         mNeedToReopenDevices(false),
890         mNeedToScanDevices(true),
891         mPendingEventCount(0),
892         mPendingEventIndex(0),
893         mPendingINotify(false) {
894     ensureProcessCanBlockSuspend();
895 
896     mEpollFd = epoll_create1(EPOLL_CLOEXEC);
897     LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
898 
899     mINotifyFd = inotify_init1(IN_CLOEXEC);
900     LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
901 
902     std::error_code errorCode;
903     bool isDeviceInotifyAdded = false;
904     if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
905         addDeviceInputInotify();
906     } else {
907         addDeviceInotify();
908         isDeviceInotifyAdded = true;
909         if (errorCode) {
910             ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
911                   errorCode.message().c_str());
912         }
913     }
914 
915     if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
916         addDeviceInotify();
917     } else {
918         ALOGI("Video device scanning disabled");
919     }
920 
921     struct epoll_event eventItem = {};
922     eventItem.events = EPOLLIN | EPOLLWAKEUP;
923     eventItem.data.fd = mINotifyFd;
924     int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
925     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance.  errno=%d", errno);
926 
927     int wakeFds[2];
928     result = pipe2(wakeFds, O_CLOEXEC);
929     LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe.  errno=%d", errno);
930 
931     mWakeReadPipeFd = wakeFds[0];
932     mWakeWritePipeFd = wakeFds[1];
933 
934     result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
935     LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking.  errno=%d",
936                         errno);
937 
938     result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
939     LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking.  errno=%d",
940                         errno);
941 
942     eventItem.data.fd = mWakeReadPipeFd;
943     result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
944     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance.  errno=%d",
945                         errno);
946 }
947 
~EventHub(void)948 EventHub::~EventHub(void) {
949     closeAllDevicesLocked();
950 
951     ::close(mEpollFd);
952     ::close(mINotifyFd);
953     ::close(mWakeReadPipeFd);
954     ::close(mWakeWritePipeFd);
955 }
956 
957 /**
958  * On devices that don't have any input devices (like some development boards), the /dev/input
959  * directory will be absent. However, the user may still plug in an input device at a later time.
960  * Add watch for contents of /dev/input only when /dev/input appears.
961  */
addDeviceInputInotify()962 void EventHub::addDeviceInputInotify() {
963     mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
964     LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
965                         DEVICE_INPUT_PATH, strerror(errno));
966 }
967 
addDeviceInotify()968 void EventHub::addDeviceInotify() {
969     mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
970     LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
971                         strerror(errno));
972 }
973 
getDeviceIdentifier(int32_t deviceId) const974 InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
975     std::scoped_lock _l(mLock);
976     Device* device = getDeviceLocked(deviceId);
977     return device != nullptr ? device->identifier : InputDeviceIdentifier();
978 }
979 
getDeviceClasses(int32_t deviceId) const980 ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
981     std::scoped_lock _l(mLock);
982     Device* device = getDeviceLocked(deviceId);
983     return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
984 }
985 
getDeviceControllerNumber(int32_t deviceId) const986 int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
987     std::scoped_lock _l(mLock);
988     Device* device = getDeviceLocked(deviceId);
989     return device != nullptr ? device->controllerNumber : 0;
990 }
991 
getConfiguration(int32_t deviceId) const992 std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
993     std::scoped_lock _l(mLock);
994     Device* device = getDeviceLocked(deviceId);
995     if (device == nullptr || device->configuration == nullptr) {
996         return {};
997     }
998     return *device->configuration;
999 }
1000 
getAbsoluteAxisInfo(int32_t deviceId,int axis,RawAbsoluteAxisInfo * outAxisInfo) const1001 status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
1002                                        RawAbsoluteAxisInfo* outAxisInfo) const {
1003     outAxisInfo->clear();
1004     if (axis < 0 || axis > ABS_MAX) {
1005         return NAME_NOT_FOUND;
1006     }
1007     std::scoped_lock _l(mLock);
1008     const Device* device = getDeviceLocked(deviceId);
1009     if (device == nullptr) {
1010         return NAME_NOT_FOUND;
1011     }
1012     // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1013     // fd, because the info is populated once when the device is first opened, and it doesn't change
1014     // throughout the device lifecycle.
1015     auto it = device->absState.find(axis);
1016     if (it == device->absState.end()) {
1017         return NAME_NOT_FOUND;
1018     }
1019     *outAxisInfo = it->second.info;
1020     return OK;
1021 }
1022 
hasRelativeAxis(int32_t deviceId,int axis) const1023 bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1024     if (axis >= 0 && axis <= REL_MAX) {
1025         std::scoped_lock _l(mLock);
1026         Device* device = getDeviceLocked(deviceId);
1027         return device != nullptr ? device->relBitmask.test(axis) : false;
1028     }
1029     return false;
1030 }
1031 
hasInputProperty(int32_t deviceId,int property) const1032 bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
1033     std::scoped_lock _l(mLock);
1034 
1035     Device* device = getDeviceLocked(deviceId);
1036     return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1037             ? device->propBitmask.test(property)
1038             : false;
1039 }
1040 
hasMscEvent(int32_t deviceId,int mscEvent) const1041 bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1042     std::scoped_lock _l(mLock);
1043 
1044     Device* device = getDeviceLocked(deviceId);
1045     return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1046             ? device->mscBitmask.test(mscEvent)
1047             : false;
1048 }
1049 
getScanCodeState(int32_t deviceId,int32_t scanCode) const1050 int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
1051     if (scanCode < 0 || scanCode > KEY_MAX) {
1052         return AKEY_STATE_UNKNOWN;
1053     }
1054     std::scoped_lock _l(mLock);
1055     const Device* device = getDeviceLocked(deviceId);
1056     if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1057         return AKEY_STATE_UNKNOWN;
1058     }
1059     return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
1060 }
1061 
getKeyCodeState(int32_t deviceId,int32_t keyCode) const1062 int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
1063     std::scoped_lock _l(mLock);
1064     const Device* device = getDeviceLocked(deviceId);
1065     if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1066         return AKEY_STATE_UNKNOWN;
1067     }
1068     const std::vector<int32_t> scanCodes =
1069             device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1070     if (scanCodes.empty()) {
1071         return AKEY_STATE_UNKNOWN;
1072     }
1073     return std::any_of(scanCodes.begin(), scanCodes.end(),
1074                        [&device](const int32_t sc) {
1075                            return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1076                        })
1077             ? AKEY_STATE_DOWN
1078             : AKEY_STATE_UP;
1079 }
1080 
getKeyCodeForKeyLocation(int32_t deviceId,int32_t locationKeyCode) const1081 int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1082     std::scoped_lock _l(mLock);
1083 
1084     Device* device = getDeviceLocked(deviceId);
1085     if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1086         device->keyMap.keyLayoutMap == nullptr) {
1087         return AKEYCODE_UNKNOWN;
1088     }
1089     std::vector<int32_t> scanCodes =
1090             device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
1091     if (scanCodes.empty()) {
1092         ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1093               "device %d",
1094               locationKeyCode, deviceId);
1095         return AKEYCODE_UNKNOWN;
1096     }
1097     if (scanCodes.size() > 1) {
1098         ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1099               locationKeyCode);
1100     }
1101     int32_t outKeyCode;
1102     status_t mapKeyRes =
1103             device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
1104     switch (mapKeyRes) {
1105         case OK:
1106             break;
1107         case NAME_NOT_FOUND:
1108             // key character map doesn't re-map this scanCode, hence the keyCode remains the same
1109             outKeyCode = locationKeyCode;
1110             break;
1111         default:
1112             ALOGW("Failed to get key code for key location: Key character map returned error %s",
1113                   statusToString(mapKeyRes).c_str());
1114             outKeyCode = AKEYCODE_UNKNOWN;
1115             break;
1116     }
1117     // Remap if there is a Key remapping added to the KCM and return the remapped key
1118     return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
1119 }
1120 
getSwitchState(int32_t deviceId,int32_t sw) const1121 int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
1122     if (sw < 0 || sw > SW_MAX) {
1123         return AKEY_STATE_UNKNOWN;
1124     }
1125     std::scoped_lock _l(mLock);
1126     const Device* device = getDeviceLocked(deviceId);
1127     if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1128         return AKEY_STATE_UNKNOWN;
1129     }
1130     return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
1131 }
1132 
getAbsoluteAxisValue(int32_t deviceId,int32_t axis,int32_t * outValue) const1133 status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
1134     *outValue = 0;
1135     if (axis < 0 || axis > ABS_MAX) {
1136         return NAME_NOT_FOUND;
1137     }
1138     std::scoped_lock _l(mLock);
1139     const Device* device = getDeviceLocked(deviceId);
1140     if (device == nullptr || !device->hasValidFd()) {
1141         return NAME_NOT_FOUND;
1142     }
1143     const auto it = device->absState.find(axis);
1144     if (it == device->absState.end()) {
1145         return NAME_NOT_FOUND;
1146     }
1147     *outValue = it->second.value;
1148     return OK;
1149 }
1150 
getMtSlotValues(int32_t deviceId,int32_t axis,size_t slotCount) const1151 base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1152                                                              size_t slotCount) const {
1153     std::scoped_lock _l(mLock);
1154     const Device* device = getDeviceLocked(deviceId);
1155     if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1156         return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1157     }
1158     std::vector<int32_t> outValues(slotCount + 1);
1159     outValues[0] = axis;
1160     const size_t bufferSize = outValues.size() * sizeof(int32_t);
1161     if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1162         return base::ErrnoError();
1163     }
1164     return std::move(outValues);
1165 }
1166 
markSupportedKeyCodes(int32_t deviceId,const std::vector<int32_t> & keyCodes,uint8_t * outFlags) const1167 bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
1168                                      uint8_t* outFlags) const {
1169     std::scoped_lock _l(mLock);
1170 
1171     Device* device = getDeviceLocked(deviceId);
1172     if (device != nullptr && device->keyMap.haveKeyLayout()) {
1173         for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
1174             if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1175                 outFlags[codeIndex] = 1;
1176             }
1177         }
1178         return true;
1179     }
1180     return false;
1181 }
1182 
addKeyRemapping(int32_t deviceId,int32_t fromKeyCode,int32_t toKeyCode) const1183 void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1184     std::scoped_lock _l(mLock);
1185     Device* device = getDeviceLocked(deviceId);
1186     if (device == nullptr) {
1187         return;
1188     }
1189     const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1190     if (kcm) {
1191         kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1192     }
1193 }
1194 
mapKey(int32_t deviceId,int32_t scanCode,int32_t usageCode,int32_t metaState,int32_t * outKeycode,int32_t * outMetaState,uint32_t * outFlags) const1195 status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1196                           int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
1197     std::scoped_lock _l(mLock);
1198     Device* device = getDeviceLocked(deviceId);
1199     status_t status = NAME_NOT_FOUND;
1200 
1201     if (device != nullptr) {
1202         // Check the key character map first.
1203         const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1204         if (kcm) {
1205             if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1206                 *outFlags = 0;
1207                 status = NO_ERROR;
1208             }
1209         }
1210 
1211         // Check the key layout next.
1212         if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
1213             if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
1214                 status = NO_ERROR;
1215             }
1216         }
1217 
1218         if (status == NO_ERROR) {
1219             if (kcm) {
1220                 // Remap keys based on user-defined key remappings and key behavior defined in the
1221                 // corresponding kcm file
1222                 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1223 
1224                 // Remap keys based on Key behavior defined in KCM file
1225                 std::tie(*outKeycode, *outMetaState) =
1226                         kcm->applyKeyBehavior(*outKeycode, metaState);
1227             } else {
1228                 *outMetaState = metaState;
1229             }
1230         }
1231     }
1232 
1233     if (status != NO_ERROR) {
1234         *outKeycode = 0;
1235         *outFlags = 0;
1236         *outMetaState = metaState;
1237     }
1238 
1239     return status;
1240 }
1241 
mapAxis(int32_t deviceId,int32_t scanCode,AxisInfo * outAxisInfo) const1242 status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
1243     std::scoped_lock _l(mLock);
1244     Device* device = getDeviceLocked(deviceId);
1245 
1246     if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1247         return NAME_NOT_FOUND;
1248     }
1249     std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1250     if (!info.has_value()) {
1251         return NAME_NOT_FOUND;
1252     }
1253     *outAxisInfo = *info;
1254     return NO_ERROR;
1255 }
1256 
mapSensor(int32_t deviceId,int32_t absCode) const1257 base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
1258                                                                             int32_t absCode) const {
1259     std::scoped_lock _l(mLock);
1260     Device* device = getDeviceLocked(deviceId);
1261 
1262     if (device != nullptr && device->keyMap.haveKeyLayout()) {
1263         return device->keyMap.keyLayoutMap->mapSensor(absCode);
1264     }
1265     return Errorf("Device not found or device has no key layout.");
1266 }
1267 
1268 // Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1269 // associated with the device ID. Returns an empty map if no miscellaneous device found.
getBatteryInfoLocked(int32_t deviceId) const1270 const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1271         int32_t deviceId) const {
1272     static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1273     Device* device = getDeviceLocked(deviceId);
1274     if (device == nullptr || !device->associatedDevice) {
1275         return EMPTY_BATTERY_INFO;
1276     }
1277     return device->associatedDevice->batteryInfos;
1278 }
1279 
getRawBatteryIds(int32_t deviceId) const1280 std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
1281     std::scoped_lock _l(mLock);
1282     std::vector<int32_t> batteryIds;
1283 
1284     for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
1285         batteryIds.push_back(id);
1286     }
1287 
1288     return batteryIds;
1289 }
1290 
getRawBatteryInfo(int32_t deviceId,int32_t batteryId) const1291 std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1292                                                           int32_t batteryId) const {
1293     std::scoped_lock _l(mLock);
1294 
1295     const auto infos = getBatteryInfoLocked(deviceId);
1296 
1297     auto it = infos.find(batteryId);
1298     if (it != infos.end()) {
1299         return it->second;
1300     }
1301 
1302     return std::nullopt;
1303 }
1304 
1305 // Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
1306 // with the device ID. Returns an empty map if no miscellaneous device found.
getLightInfoLocked(int32_t deviceId) const1307 const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1308         int32_t deviceId) const {
1309     static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1310     Device* device = getDeviceLocked(deviceId);
1311     if (device == nullptr || !device->associatedDevice) {
1312         return EMPTY_LIGHT_INFO;
1313     }
1314     return device->associatedDevice->lightInfos;
1315 }
1316 
getRawLightIds(int32_t deviceId) const1317 std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
1318     std::scoped_lock _l(mLock);
1319     std::vector<int32_t> lightIds;
1320 
1321     for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
1322         lightIds.push_back(id);
1323     }
1324 
1325     return lightIds;
1326 }
1327 
getRawLightInfo(int32_t deviceId,int32_t lightId) const1328 std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
1329     std::scoped_lock _l(mLock);
1330 
1331     const auto infos = getLightInfoLocked(deviceId);
1332 
1333     auto it = infos.find(lightId);
1334     if (it != infos.end()) {
1335         return it->second;
1336     }
1337 
1338     return std::nullopt;
1339 }
1340 
getLightBrightness(int32_t deviceId,int32_t lightId) const1341 std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
1342     std::scoped_lock _l(mLock);
1343 
1344     const auto infos = getLightInfoLocked(deviceId);
1345     auto it = infos.find(lightId);
1346     if (it == infos.end()) {
1347         return std::nullopt;
1348     }
1349     std::string buffer;
1350     if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1351                                 &buffer)) {
1352         return std::nullopt;
1353     }
1354     return std::stoi(buffer);
1355 }
1356 
getLightIntensities(int32_t deviceId,int32_t lightId) const1357 std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1358         int32_t deviceId, int32_t lightId) const {
1359     std::scoped_lock _l(mLock);
1360 
1361     const auto infos = getLightInfoLocked(deviceId);
1362     auto lightIt = infos.find(lightId);
1363     if (lightIt == infos.end()) {
1364         return std::nullopt;
1365     }
1366 
1367     auto ret =
1368             getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1369 
1370     if (!ret.has_value()) {
1371         return std::nullopt;
1372     }
1373     std::array<LightColor, COLOR_NUM> colors = ret.value();
1374 
1375     std::string intensityStr;
1376     if (!base::ReadFileToString(lightIt->second.path /
1377                                         LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1378                                 &intensityStr)) {
1379         return std::nullopt;
1380     }
1381 
1382     // Intensity node outputs 3 color values
1383     std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1384     std::smatch results;
1385 
1386     if (!std::regex_match(intensityStr, results, intensityPattern)) {
1387         return std::nullopt;
1388     }
1389     std::unordered_map<LightColor, int32_t> intensities;
1390     for (size_t i = 1; i < results.size(); i++) {
1391         int value = std::stoi(results[i].str());
1392         intensities.emplace(colors[i - 1], value);
1393     }
1394     return intensities;
1395 }
1396 
setLightBrightness(int32_t deviceId,int32_t lightId,int32_t brightness)1397 void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1398     std::scoped_lock _l(mLock);
1399 
1400     const auto infos = getLightInfoLocked(deviceId);
1401     auto lightIt = infos.find(lightId);
1402     if (lightIt == infos.end()) {
1403         ALOGE("%s lightId %d not found ", __func__, lightId);
1404         return;
1405     }
1406 
1407     if (!base::WriteStringToFile(std::to_string(brightness),
1408                                  lightIt->second.path /
1409                                          LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1410         ALOGE("Can not write to file, error: %s", strerror(errno));
1411     }
1412 }
1413 
setLightIntensities(int32_t deviceId,int32_t lightId,std::unordered_map<LightColor,int32_t> intensities)1414 void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1415                                    std::unordered_map<LightColor, int32_t> intensities) {
1416     std::scoped_lock _l(mLock);
1417 
1418     const auto infos = getLightInfoLocked(deviceId);
1419     auto lightIt = infos.find(lightId);
1420     if (lightIt == infos.end()) {
1421         ALOGE("Light Id %d does not exist.", lightId);
1422         return;
1423     }
1424 
1425     auto ret =
1426             getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1427 
1428     if (!ret.has_value()) {
1429         return;
1430     }
1431     std::array<LightColor, COLOR_NUM> colors = ret.value();
1432 
1433     std::string rgbStr;
1434     for (size_t i = 0; i < COLOR_NUM; i++) {
1435         auto it = intensities.find(colors[i]);
1436         if (it != intensities.end()) {
1437             rgbStr += std::to_string(it->second);
1438             // Insert space between colors
1439             if (i < COLOR_NUM - 1) {
1440                 rgbStr += " ";
1441             }
1442         }
1443     }
1444     // Append new line
1445     rgbStr += "\n";
1446 
1447     if (!base::WriteStringToFile(rgbStr,
1448                                  lightIt->second.path /
1449                                          LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1450         ALOGE("Can not write to file, error: %s", strerror(errno));
1451     }
1452 }
1453 
getRawLayoutInfo(int32_t deviceId) const1454 std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
1455     std::scoped_lock _l(mLock);
1456     Device* device = getDeviceLocked(deviceId);
1457     if (device == nullptr || !device->associatedDevice) {
1458         return std::nullopt;
1459     }
1460     return device->associatedDevice->layoutInfo;
1461 }
1462 
setExcludedDevices(const std::vector<std::string> & devices)1463 void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
1464     std::scoped_lock _l(mLock);
1465 
1466     mExcludedDevices = devices;
1467 }
1468 
hasScanCode(int32_t deviceId,int32_t scanCode) const1469 bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
1470     std::scoped_lock _l(mLock);
1471     Device* device = getDeviceLocked(deviceId);
1472     if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1473         return device->keyBitmask.test(scanCode);
1474     }
1475     return false;
1476 }
1477 
hasKeyCode(int32_t deviceId,int32_t keyCode) const1478 bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1479     std::scoped_lock _l(mLock);
1480     Device* device = getDeviceLocked(deviceId);
1481     if (device != nullptr) {
1482         return device->hasKeycodeLocked(keyCode);
1483     }
1484     return false;
1485 }
1486 
hasLed(int32_t deviceId,int32_t led) const1487 bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
1488     std::scoped_lock _l(mLock);
1489     Device* device = getDeviceLocked(deviceId);
1490     int32_t sc;
1491     if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
1492         return device->ledBitmask.test(sc);
1493     }
1494     return false;
1495 }
1496 
setLedState(int32_t deviceId,int32_t led,bool on)1497 void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
1498     std::scoped_lock _l(mLock);
1499     Device* device = getDeviceLocked(deviceId);
1500     if (device != nullptr && device->hasValidFd()) {
1501         device->setLedStateLocked(led, on);
1502     }
1503 }
1504 
getVirtualKeyDefinitions(int32_t deviceId,std::vector<VirtualKeyDefinition> & outVirtualKeys) const1505 void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
1506                                         std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
1507     outVirtualKeys.clear();
1508 
1509     std::scoped_lock _l(mLock);
1510     Device* device = getDeviceLocked(deviceId);
1511     if (device != nullptr && device->virtualKeyMap) {
1512         const std::vector<VirtualKeyDefinition> virtualKeys =
1513                 device->virtualKeyMap->getVirtualKeys();
1514         outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
1515     }
1516 }
1517 
getKeyCharacterMap(int32_t deviceId) const1518 const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
1519     std::scoped_lock _l(mLock);
1520     Device* device = getDeviceLocked(deviceId);
1521     if (device != nullptr) {
1522         return device->getKeyCharacterMap();
1523     }
1524     return nullptr;
1525 }
1526 
1527 // If provided map is null, it will reset key character map to default KCM.
setKeyboardLayoutOverlay(int32_t deviceId,std::shared_ptr<KeyCharacterMap> map)1528 bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
1529     std::scoped_lock _l(mLock);
1530     Device* device = getDeviceLocked(deviceId);
1531     if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1532         return false;
1533     }
1534     if (map == nullptr) {
1535         device->keyMap.keyCharacterMap->clearLayoutOverlay();
1536         return true;
1537     }
1538     device->keyMap.keyCharacterMap->combine(*map);
1539     return true;
1540 }
1541 
generateDescriptor(InputDeviceIdentifier & identifier)1542 static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1543     std::string rawDescriptor;
1544     rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
1545     // TODO add handling for USB devices to not uniqueify kbs that show up twice
1546     if (!identifier.uniqueId.empty()) {
1547         rawDescriptor += "uniqueId:";
1548         rawDescriptor += identifier.uniqueId;
1549     }
1550     if (identifier.nonce != 0) {
1551         rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
1552     }
1553 
1554     if (identifier.vendor == 0 && identifier.product == 0) {
1555         // If we don't know the vendor and product id, then the device is probably
1556         // built-in so we need to rely on other information to uniquely identify
1557         // the input device.  Usually we try to avoid relying on the device name or
1558         // location but for built-in input device, they are unlikely to ever change.
1559         if (!identifier.name.empty()) {
1560             rawDescriptor += "name:";
1561             rawDescriptor += identifier.name;
1562         } else if (!identifier.location.empty()) {
1563             rawDescriptor += "location:";
1564             rawDescriptor += identifier.location;
1565         }
1566     }
1567     identifier.descriptor = sha1(rawDescriptor);
1568     return rawDescriptor;
1569 }
1570 
assignDescriptorLocked(InputDeviceIdentifier & identifier)1571 void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1572     // Compute a device descriptor that uniquely identifies the device.
1573     // The descriptor is assumed to be a stable identifier.  Its value should not
1574     // change between reboots, reconnections, firmware updates or new releases
1575     // of Android. In practice we sometimes get devices that cannot be uniquely
1576     // identified. In this case we enforce uniqueness between connected devices.
1577     // Ideally, we also want the descriptor to be short and relatively opaque.
1578     // Note that we explicitly do not use the path or location for external devices
1579     // as their path or location will change as they are plugged/unplugged or moved
1580     // to different ports. We do fallback to using name and location in the case of
1581     // internal devices which are detected by the vendor and product being 0 in
1582     // generateDescriptor. If two identical descriptors are detected we will fallback
1583     // to using a 'nonce' and incrementing it until the new descriptor no longer has
1584     // a match with any existing descriptors.
1585 
1586     identifier.nonce = 0;
1587     std::string rawDescriptor = generateDescriptor(identifier);
1588     // Enforce that the generated descriptor is unique.
1589     while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1590         identifier.nonce++;
1591         rawDescriptor = generateDescriptor(identifier);
1592     }
1593     ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
1594           identifier.descriptor.c_str());
1595 }
1596 
obtainAssociatedDeviceLocked(const std::filesystem::path & devicePath) const1597 std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1598         const std::filesystem::path& devicePath) const {
1599     const std::optional<std::filesystem::path> sysfsRootPathOpt =
1600             getSysfsRootPath(devicePath.c_str());
1601     if (!sysfsRootPathOpt) {
1602         return nullptr;
1603     }
1604 
1605     const auto& path = *sysfsRootPathOpt;
1606 
1607     std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
1608             AssociatedDevice{.sysfsRootPath = path,
1609                              .batteryInfos = readBatteryConfiguration(path),
1610                              .lightInfos = readLightsConfiguration(path),
1611                              .layoutInfo = readLayoutConfiguration(path)});
1612 
1613     bool associatedDeviceChanged = false;
1614     for (const auto& [id, dev] : mDevices) {
1615         if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1616             if (*associatedDevice != *dev->associatedDevice) {
1617                 associatedDeviceChanged = true;
1618                 dev->associatedDevice = associatedDevice;
1619             }
1620             associatedDevice = dev->associatedDevice;
1621         }
1622     }
1623     ALOGI_IF(associatedDeviceChanged,
1624              "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1625              path.c_str(), associatedDevice->dump().c_str());
1626 
1627     return associatedDevice;
1628 }
1629 
isChanged() const1630 bool EventHub::AssociatedDevice::isChanged() const {
1631     std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1632             readBatteryConfiguration(sysfsRootPath);
1633     std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1634             readLightsConfiguration(sysfsRootPath);
1635     std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1636 
1637     if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1638         newLayoutInfo == layoutInfo) {
1639         return false;
1640     }
1641     return true;
1642 }
1643 
vibrate(int32_t deviceId,const VibrationElement & element)1644 void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
1645     std::scoped_lock _l(mLock);
1646     Device* device = getDeviceLocked(deviceId);
1647     if (device != nullptr && device->hasValidFd()) {
1648         ff_effect effect;
1649         memset(&effect, 0, sizeof(effect));
1650         effect.type = FF_RUMBLE;
1651         effect.id = device->ffEffectId;
1652         // evdev FF_RUMBLE effect only supports two channels of vibration.
1653         effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1654         effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1655         effect.replay.length = element.duration.count();
1656         effect.replay.delay = 0;
1657         if (ioctl(device->fd, EVIOCSFF, &effect)) {
1658             ALOGW("Could not upload force feedback effect to device %s due to error %d.",
1659                   device->identifier.name.c_str(), errno);
1660             return;
1661         }
1662         device->ffEffectId = effect.id;
1663 
1664         struct input_event ev;
1665         ev.input_event_sec = 0;
1666         ev.input_event_usec = 0;
1667         ev.type = EV_FF;
1668         ev.code = device->ffEffectId;
1669         ev.value = 1;
1670         if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1671             ALOGW("Could not start force feedback effect on device %s due to error %d.",
1672                   device->identifier.name.c_str(), errno);
1673             return;
1674         }
1675         device->ffEffectPlaying = true;
1676     }
1677 }
1678 
cancelVibrate(int32_t deviceId)1679 void EventHub::cancelVibrate(int32_t deviceId) {
1680     std::scoped_lock _l(mLock);
1681     Device* device = getDeviceLocked(deviceId);
1682     if (device != nullptr && device->hasValidFd()) {
1683         if (device->ffEffectPlaying) {
1684             device->ffEffectPlaying = false;
1685 
1686             struct input_event ev;
1687             ev.input_event_sec = 0;
1688             ev.input_event_usec = 0;
1689             ev.type = EV_FF;
1690             ev.code = device->ffEffectId;
1691             ev.value = 0;
1692             if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1693                 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
1694                       device->identifier.name.c_str(), errno);
1695                 return;
1696             }
1697         }
1698     }
1699 }
1700 
getVibratorIds(int32_t deviceId) const1701 std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
1702     std::scoped_lock _l(mLock);
1703     std::vector<int32_t> vibrators;
1704     Device* device = getDeviceLocked(deviceId);
1705     if (device != nullptr && device->hasValidFd() &&
1706         device->classes.test(InputDeviceClass::VIBRATOR)) {
1707         vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1708         vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1709     }
1710     return vibrators;
1711 }
1712 
1713 /**
1714  * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1715  */
hasDeviceWithDescriptorLocked(const std::string & descriptor) const1716 bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1717     for (const auto& device : mOpeningDevices) {
1718         if (descriptor == device->identifier.descriptor) {
1719             return true;
1720         }
1721     }
1722 
1723     for (const auto& [id, device] : mDevices) {
1724         if (descriptor == device->identifier.descriptor) {
1725             return true;
1726         }
1727     }
1728     return false;
1729 }
1730 
getDeviceLocked(int32_t deviceId) const1731 EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
1732     if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
1733         deviceId = mBuiltInKeyboardId;
1734     }
1735     const auto& it = mDevices.find(deviceId);
1736     return it != mDevices.end() ? it->second.get() : nullptr;
1737 }
1738 
getDeviceByPathLocked(const std::string & devicePath) const1739 EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
1740     for (const auto& [id, device] : mDevices) {
1741         if (device->path == devicePath) {
1742             return device.get();
1743         }
1744     }
1745     return nullptr;
1746 }
1747 
1748 /**
1749  * The file descriptor could be either input device, or a video device (associated with a
1750  * specific input device). Check both cases here, and return the device that this event
1751  * belongs to. Caller can compare the fd's once more to determine event type.
1752  * Looks through all input devices, and only attached video devices. Unattached video
1753  * devices are ignored.
1754  */
getDeviceByFdLocked(int fd) const1755 EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
1756     for (const auto& [id, device] : mDevices) {
1757         if (device->fd == fd) {
1758             // This is an input device event
1759             return device.get();
1760         }
1761         if (device->videoDevice && device->videoDevice->getFd() == fd) {
1762             // This is a video device event
1763             return device.get();
1764         }
1765     }
1766     // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1767     // and therefore should never be looked up by fd.
1768     return nullptr;
1769 }
1770 
getBatteryCapacity(int32_t deviceId,int32_t batteryId) const1771 std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
1772     std::filesystem::path batteryPath;
1773     {
1774         // Do not read the sysfs node to get the battery state while holding
1775         // the EventHub lock. For some peripheral devices, reading battery state
1776         // can be broken and take 5+ seconds. Holding the lock in this case would
1777         // block all other event processing during this time. For now, we assume this
1778         // call never happens on the InputReader thread and read the sysfs node outside
1779         // the lock to prevent event processing from being blocked by this call.
1780         std::scoped_lock _l(mLock);
1781 
1782         const auto& infos = getBatteryInfoLocked(deviceId);
1783         auto it = infos.find(batteryId);
1784         if (it == infos.end()) {
1785             return std::nullopt;
1786         }
1787         batteryPath = it->second.path;
1788     } // release lock
1789 
1790     std::string buffer;
1791 
1792     // Some devices report battery capacity as an integer through the "capacity" file
1793     if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
1794                                &buffer)) {
1795         return std::stoi(base::Trim(buffer));
1796     }
1797 
1798     // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1799     // These values are taken from kernel source code include/linux/power_supply.h
1800     if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
1801                                &buffer)) {
1802         // Remove any white space such as trailing new line
1803         const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1804         if (levelIt != BATTERY_LEVEL.end()) {
1805             return levelIt->second;
1806         }
1807     }
1808 
1809     return std::nullopt;
1810 }
1811 
getBatteryStatus(int32_t deviceId,int32_t batteryId) const1812 std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
1813     std::filesystem::path batteryPath;
1814     {
1815         // Do not read the sysfs node to get the battery state while holding
1816         // the EventHub lock. For some peripheral devices, reading battery state
1817         // can be broken and take 5+ seconds. Holding the lock in this case would
1818         // block all other event processing during this time. For now, we assume this
1819         // call never happens on the InputReader thread and read the sysfs node outside
1820         // the lock to prevent event processing from being blocked by this call.
1821         std::scoped_lock _l(mLock);
1822 
1823         const auto& infos = getBatteryInfoLocked(deviceId);
1824         auto it = infos.find(batteryId);
1825         if (it == infos.end()) {
1826             return std::nullopt;
1827         }
1828         batteryPath = it->second.path;
1829     } // release lock
1830 
1831     std::string buffer;
1832 
1833     if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
1834                                 &buffer)) {
1835         ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1836         return std::nullopt;
1837     }
1838 
1839     // Remove white space like trailing new line
1840     const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1841     if (statusIt != BATTERY_STATUS.end()) {
1842         return statusIt->second;
1843     }
1844 
1845     return std::nullopt;
1846 }
1847 
getEvents(int timeoutMillis)1848 std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
1849     std::scoped_lock _l(mLock);
1850 
1851     std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
1852 
1853     std::vector<RawEvent> events;
1854     bool awoken = false;
1855     for (;;) {
1856         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1857 
1858         // Reopen input devices if needed.
1859         if (mNeedToReopenDevices) {
1860             mNeedToReopenDevices = false;
1861 
1862             ALOGI("Reopening all input devices due to a configuration change.");
1863 
1864             closeAllDevicesLocked();
1865             mNeedToScanDevices = true;
1866             break; // return to the caller before we actually rescan
1867         }
1868 
1869         // Report any devices that had last been added/removed.
1870         for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1871             std::unique_ptr<Device> device = std::move(*it);
1872             ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
1873             const int32_t deviceId = (device->id == mBuiltInKeyboardId)
1874                     ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1875                     : device->id;
1876             events.push_back({
1877                     .when = now,
1878                     .deviceId = deviceId,
1879                     .type = DEVICE_REMOVED,
1880             });
1881             it = mClosingDevices.erase(it);
1882             mNeedToSendFinishedDeviceScan = true;
1883             if (events.size() == EVENT_BUFFER_SIZE) {
1884                 break;
1885             }
1886         }
1887 
1888         if (mNeedToScanDevices) {
1889             mNeedToScanDevices = false;
1890             scanDevicesLocked();
1891             mNeedToSendFinishedDeviceScan = true;
1892         }
1893 
1894         while (!mOpeningDevices.empty()) {
1895             std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1896             mOpeningDevices.pop_back();
1897             ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
1898             const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1899             events.push_back({
1900                     .when = now,
1901                     .deviceId = deviceId,
1902                     .type = DEVICE_ADDED,
1903             });
1904 
1905             // Try to find a matching video device by comparing device names
1906             for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1907                  it++) {
1908                 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
1909                 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
1910                     // videoDevice was transferred to 'device'
1911                     it = mUnattachedVideoDevices.erase(it);
1912                     break;
1913                 }
1914             }
1915 
1916             auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1917             if (!inserted) {
1918                 ALOGW("Device id %d exists, replaced.", device->id);
1919             }
1920             mNeedToSendFinishedDeviceScan = true;
1921             if (events.size() == EVENT_BUFFER_SIZE) {
1922                 break;
1923             }
1924         }
1925 
1926         if (mNeedToSendFinishedDeviceScan) {
1927             mNeedToSendFinishedDeviceScan = false;
1928             events.push_back({
1929                     .when = now,
1930                     .type = FINISHED_DEVICE_SCAN,
1931             });
1932             if (events.size() == EVENT_BUFFER_SIZE) {
1933                 break;
1934             }
1935         }
1936 
1937         // Grab the next input event.
1938         bool deviceChanged = false;
1939         while (mPendingEventIndex < mPendingEventCount) {
1940             const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
1941             if (eventItem.data.fd == mINotifyFd) {
1942                 if (eventItem.events & EPOLLIN) {
1943                     mPendingINotify = true;
1944                 } else {
1945                     ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1946                 }
1947                 continue;
1948             }
1949 
1950             if (eventItem.data.fd == mWakeReadPipeFd) {
1951                 if (eventItem.events & EPOLLIN) {
1952                     ALOGV("awoken after wake()");
1953                     awoken = true;
1954                     char wakeReadBuffer[16];
1955                     ssize_t nRead;
1956                     do {
1957                         nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1958                     } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
1959                 } else {
1960                     ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
1961                           eventItem.events);
1962                 }
1963                 continue;
1964             }
1965 
1966             Device* device = getDeviceByFdLocked(eventItem.data.fd);
1967             if (device == nullptr) {
1968                 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1969                       eventItem.data.fd);
1970                 ALOG_ASSERT(!DEBUG);
1971                 continue;
1972             }
1973             if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1974                 if (eventItem.events & EPOLLIN) {
1975                     size_t numFrames = device->videoDevice->readAndQueueFrames();
1976                     if (numFrames == 0) {
1977                         ALOGE("Received epoll event for video device %s, but could not read frame",
1978                               device->videoDevice->getName().c_str());
1979                     }
1980                 } else if (eventItem.events & EPOLLHUP) {
1981                     // TODO(b/121395353) - consider adding EPOLLRDHUP
1982                     ALOGI("Removing video device %s due to epoll hang-up event.",
1983                           device->videoDevice->getName().c_str());
1984                     unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1985                     device->videoDevice = nullptr;
1986                 } else {
1987                     ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1988                           device->videoDevice->getName().c_str());
1989                     ALOG_ASSERT(!DEBUG);
1990                 }
1991                 continue;
1992             }
1993             // This must be an input event
1994             if (eventItem.events & EPOLLIN) {
1995                 int32_t readSize =
1996                         read(device->fd, readBuffer.data(),
1997                              sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
1998                 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1999                     // Device was removed before INotify noticed.
2000                     ALOGW("could not get event, removed? (fd: %d size: %" PRId32
2001                           " capacity: %zu errno: %d)\n",
2002                           device->fd, readSize, readBuffer.size(), errno);
2003                     deviceChanged = true;
2004                     closeDeviceLocked(*device);
2005                 } else if (readSize < 0) {
2006                     if (errno != EAGAIN && errno != EINTR) {
2007                         ALOGW("could not get event (errno=%d)", errno);
2008                     }
2009                 } else if ((readSize % sizeof(struct input_event)) != 0) {
2010                     ALOGE("could not get event (wrong size: %d)", readSize);
2011                 } else {
2012                     const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
2013 
2014                     const size_t count = size_t(readSize) / sizeof(struct input_event);
2015                     for (size_t i = 0; i < count; i++) {
2016                         struct input_event& iev = readBuffer[i];
2017                         device->trackInputEvent(iev);
2018                         events.push_back({
2019                                 .when = processEventTimestamp(iev),
2020                                 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2021                                 .deviceId = deviceId,
2022                                 .type = iev.type,
2023                                 .code = iev.code,
2024                                 .value = iev.value,
2025                         });
2026                     }
2027                     if (events.size() >= EVENT_BUFFER_SIZE) {
2028                         // The result buffer is full.  Reset the pending event index
2029                         // so we will try to read the device again on the next iteration.
2030                         mPendingEventIndex -= 1;
2031                         break;
2032                     }
2033                 }
2034             } else if (eventItem.events & EPOLLHUP) {
2035                 ALOGI("Removing device %s due to epoll hang-up event.",
2036                       device->identifier.name.c_str());
2037                 deviceChanged = true;
2038                 closeDeviceLocked(*device);
2039             } else {
2040                 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2041                       device->identifier.name.c_str());
2042             }
2043         }
2044 
2045         // readNotify() will modify the list of devices so this must be done after
2046         // processing all other events to ensure that we read all remaining events
2047         // before closing the devices.
2048         if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2049             mPendingINotify = false;
2050             const auto res = readNotifyLocked();
2051             if (!res.ok()) {
2052                 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2053             }
2054             deviceChanged = true;
2055         }
2056 
2057         // Report added or removed devices immediately.
2058         if (deviceChanged) {
2059             continue;
2060         }
2061 
2062         // Return now if we have collected any events or if we were explicitly awoken.
2063         if (!events.empty() || awoken) {
2064             break;
2065         }
2066 
2067         // Poll for events.
2068         // When a device driver has pending (unread) events, it acquires
2069         // a kernel wake lock.  Once the last pending event has been read, the device
2070         // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2071         // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2072         // is called again for the same fd that produced the event.
2073         // Thus the system can only sleep if there are no events pending or
2074         // currently being processed.
2075         //
2076         // The timeout is advisory only.  If the device is asleep, it will not wake just to
2077         // service the timeout.
2078         mPendingEventIndex = 0;
2079 
2080         mLock.unlock(); // release lock before poll
2081 
2082         int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2083 
2084         mLock.lock(); // reacquire lock after poll
2085 
2086         if (pollResult == 0) {
2087             // Timed out.
2088             mPendingEventCount = 0;
2089             break;
2090         }
2091 
2092         if (pollResult < 0) {
2093             // An error occurred.
2094             mPendingEventCount = 0;
2095 
2096             // Sleep after errors to avoid locking up the system.
2097             // Hopefully the error is transient.
2098             if (errno != EINTR) {
2099                 ALOGW("poll failed (errno=%d)\n", errno);
2100                 usleep(100000);
2101             }
2102         } else {
2103             // Some events occurred.
2104             mPendingEventCount = size_t(pollResult);
2105         }
2106     }
2107 
2108     // All done, return the number of events we read.
2109     return events;
2110 }
2111 
getVideoFrames(int32_t deviceId)2112 std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
2113     std::scoped_lock _l(mLock);
2114 
2115     Device* device = getDeviceLocked(deviceId);
2116     if (device == nullptr || !device->videoDevice) {
2117         return {};
2118     }
2119     return device->videoDevice->consumeFrames();
2120 }
2121 
wake()2122 void EventHub::wake() {
2123     ALOGV("wake() called");
2124 
2125     ssize_t nWrite;
2126     do {
2127         nWrite = write(mWakeWritePipeFd, "W", 1);
2128     } while (nWrite == -1 && errno == EINTR);
2129 
2130     if (nWrite != 1 && errno != EAGAIN) {
2131         ALOGW("Could not write wake signal: %s", strerror(errno));
2132     }
2133 }
2134 
scanDevicesLocked()2135 void EventHub::scanDevicesLocked() {
2136     status_t result;
2137     std::error_code errorCode;
2138 
2139     if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2140         result = scanDirLocked(DEVICE_INPUT_PATH);
2141         if (result < 0) {
2142             ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2143         }
2144     } else {
2145         if (errorCode) {
2146             ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2147                   errorCode.message().c_str());
2148         }
2149     }
2150     if (isV4lScanningEnabled()) {
2151         result = scanVideoDirLocked(DEVICE_PATH);
2152         if (result != OK) {
2153             ALOGE("scan video dir failed for %s", DEVICE_PATH);
2154         }
2155     }
2156     if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
2157         createVirtualKeyboardLocked();
2158     }
2159 }
2160 
2161 // ----------------------------------------------------------------------------
2162 
registerFdForEpoll(int fd)2163 status_t EventHub::registerFdForEpoll(int fd) {
2164     // TODO(b/121395353) - consider adding EPOLLRDHUP
2165     struct epoll_event eventItem = {};
2166     eventItem.events = EPOLLIN | EPOLLWAKEUP;
2167     eventItem.data.fd = fd;
2168     if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2169         ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
2170         return -errno;
2171     }
2172     return OK;
2173 }
2174 
unregisterFdFromEpoll(int fd)2175 status_t EventHub::unregisterFdFromEpoll(int fd) {
2176     if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2177         ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2178         return -errno;
2179     }
2180     return OK;
2181 }
2182 
registerDeviceForEpollLocked(Device & device)2183 status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2184     status_t result = registerFdForEpoll(device.fd);
2185     if (result != OK) {
2186         ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
2187         return result;
2188     }
2189     if (device.videoDevice) {
2190         registerVideoDeviceForEpollLocked(*device.videoDevice);
2191     }
2192     return result;
2193 }
2194 
registerVideoDeviceForEpollLocked(const TouchVideoDevice & videoDevice)2195 void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2196     status_t result = registerFdForEpoll(videoDevice.getFd());
2197     if (result != OK) {
2198         ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2199     }
2200 }
2201 
unregisterDeviceFromEpollLocked(Device & device)2202 status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2203     if (device.hasValidFd()) {
2204         status_t result = unregisterFdFromEpoll(device.fd);
2205         if (result != OK) {
2206             ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
2207             return result;
2208         }
2209     }
2210     if (device.videoDevice) {
2211         unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
2212     }
2213     return OK;
2214 }
2215 
unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice & videoDevice)2216 void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2217     if (videoDevice.hasValidFd()) {
2218         status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2219         if (result != OK) {
2220             ALOGW("Could not remove video device fd from epoll for device: %s",
2221                   videoDevice.getName().c_str());
2222         }
2223     }
2224 }
2225 
reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier & identifier,ftl::Flags<InputDeviceClass> classes)2226 void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
2227                                                     ftl::Flags<InputDeviceClass> classes) {
2228     SHA256_CTX ctx;
2229     SHA256_Init(&ctx);
2230     SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2231                   identifier.uniqueId.size());
2232     std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2233     SHA256_Final(digest.data(), &ctx);
2234 
2235     std::string obfuscatedId;
2236     for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2237         obfuscatedId += StringPrintf("%02x", digest[i]);
2238     }
2239 
2240     android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2241                                identifier.vendor, identifier.product, identifier.version,
2242                                identifier.bus, obfuscatedId.c_str(), classes.get());
2243 }
2244 
openDeviceLocked(const std::string & devicePath)2245 void EventHub::openDeviceLocked(const std::string& devicePath) {
2246     // If an input device happens to register around the time when EventHub's constructor runs, it
2247     // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2248     // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2249     // from getting registered, ensure that this path is not already covered by an existing device.
2250     for (const auto& [deviceId, device] : mDevices) {
2251         if (device->path == devicePath) {
2252             return; // device was already registered
2253         }
2254     }
2255 
2256     char buffer[80];
2257 
2258     ALOGV("Opening device: %s", devicePath.c_str());
2259 
2260     int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
2261     if (fd < 0) {
2262         ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
2263         return;
2264     }
2265 
2266     InputDeviceIdentifier identifier;
2267 
2268     // Get device name.
2269     if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
2270         ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
2271     } else {
2272         buffer[sizeof(buffer) - 1] = '\0';
2273         identifier.name = buffer;
2274     }
2275 
2276     // Check to see if the device is on our excluded list
2277     for (size_t i = 0; i < mExcludedDevices.size(); i++) {
2278         const std::string& item = mExcludedDevices[i];
2279         if (identifier.name == item) {
2280             ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
2281             close(fd);
2282             return;
2283         }
2284     }
2285 
2286     // Get device driver version.
2287     int driverVersion;
2288     if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
2289         ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
2290         close(fd);
2291         return;
2292     }
2293 
2294     // Get device identifier.
2295     struct input_id inputId;
2296     if (ioctl(fd, EVIOCGID, &inputId)) {
2297         ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
2298         close(fd);
2299         return;
2300     }
2301     identifier.bus = inputId.bustype;
2302     identifier.product = inputId.product;
2303     identifier.vendor = inputId.vendor;
2304     identifier.version = inputId.version;
2305 
2306     // Get device physical location.
2307     if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2308         // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
2309     } else {
2310         buffer[sizeof(buffer) - 1] = '\0';
2311         identifier.location = buffer;
2312     }
2313 
2314     // Get device unique id.
2315     if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2316         // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
2317     } else {
2318         buffer[sizeof(buffer) - 1] = '\0';
2319         identifier.uniqueId = buffer;
2320     }
2321 
2322     // Attempt to get the bluetooth address of an input device from the uniqueId.
2323     if (identifier.bus == BUS_BLUETOOTH &&
2324         std::regex_match(identifier.uniqueId,
2325                          std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2326         identifier.bluetoothAddress = identifier.uniqueId;
2327         // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2328         for (auto& c : *identifier.bluetoothAddress) {
2329             c = ::toupper(c);
2330         }
2331     }
2332 
2333     // Fill in the descriptor.
2334     assignDescriptorLocked(identifier);
2335 
2336     // Allocate device.  (The device object takes ownership of the fd at this point.)
2337     int32_t deviceId = mNextDeviceId++;
2338     std::unique_ptr<Device> device =
2339             std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2340                                      obtainAssociatedDeviceLocked(devicePath));
2341 
2342     ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
2343     ALOGV("  bus:        %04x\n"
2344           "  vendor      %04x\n"
2345           "  product     %04x\n"
2346           "  version     %04x\n",
2347           identifier.bus, identifier.vendor, identifier.product, identifier.version);
2348     ALOGV("  name:       \"%s\"\n", identifier.name.c_str());
2349     ALOGV("  location:   \"%s\"\n", identifier.location.c_str());
2350     ALOGV("  unique id:  \"%s\"\n", identifier.uniqueId.c_str());
2351     ALOGV("  descriptor: \"%s\"\n", identifier.descriptor.c_str());
2352     ALOGV("  driver:     v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2353           driverVersion & 0xff);
2354 
2355     // Load the configuration file for the device.
2356     device->loadConfigurationLocked();
2357 
2358     // Figure out the kinds of events the device reports.
2359     device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2360     device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2361     device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2362     device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2363     device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2364     device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
2365     device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
2366     device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
2367 
2368     // See if this is a device with keys. This could be full keyboard, or other devices like
2369     // gamepads, joysticks, and styluses with buttons that should generate key presses.
2370     bool haveKeyboardKeys =
2371             device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2372     bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2373             device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
2374     bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2375             device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2376     if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
2377         device->classes |= InputDeviceClass::KEYBOARD;
2378     }
2379 
2380     // See if this is a cursor device such as a trackball or mouse.
2381     if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2382         device->relBitmask.test(REL_Y)) {
2383         device->classes |= InputDeviceClass::CURSOR;
2384     }
2385 
2386     // See if the device is specially configured to be of a certain type.
2387     if (device->configuration) {
2388         std::string deviceType = device->configuration->getString("device.type").value_or("");
2389         if (deviceType == "rotaryEncoder") {
2390             device->classes |= InputDeviceClass::ROTARY_ENCODER;
2391         } else if (deviceType == "externalStylus") {
2392             device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2393         }
2394     }
2395 
2396     // See if this is a touch pad.
2397     // Is this a new modern multi-touch driver?
2398     if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
2399         // Some joysticks such as the PS3 controller report axes that conflict
2400         // with the ABS_MT range.  Try to confirm that the device really is
2401         // a touch screen.
2402         if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
2403             device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
2404             if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2405                 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2406                 device->classes |= InputDeviceClass::TOUCHPAD;
2407             }
2408         }
2409         // Is this an old style single-touch driver?
2410     } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2411                device->absBitmask.test(ABS_Y)) {
2412         device->classes |= InputDeviceClass::TOUCH;
2413         // Is this a stylus that reports contact/pressure independently of touch coordinates?
2414     } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2415                !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
2416         device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2417     }
2418 
2419     // See if this device is a joystick.
2420     // Assumes that joysticks always have gamepad buttons in order to distinguish them
2421     // from other devices such as accelerometers that also have absolute axes.
2422     if (haveGamepadButtons) {
2423         auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
2424         for (int i = 0; i <= ABS_MAX; i++) {
2425             if (device->absBitmask.test(i) &&
2426                 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
2427                 device->classes = assumedClasses;
2428                 break;
2429             }
2430         }
2431     }
2432 
2433     // Check whether this device is an accelerometer.
2434     if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2435         device->classes |= InputDeviceClass::SENSOR;
2436     }
2437 
2438     // Check whether this device has switches.
2439     for (int i = 0; i <= SW_MAX; i++) {
2440         if (device->swBitmask.test(i)) {
2441             device->classes |= InputDeviceClass::SWITCH;
2442             break;
2443         }
2444     }
2445 
2446     // Check whether this device supports the vibrator.
2447     if (device->ffBitmask.test(FF_RUMBLE)) {
2448         device->classes |= InputDeviceClass::VIBRATOR;
2449     }
2450 
2451     // Configure virtual keys.
2452     if ((device->classes.test(InputDeviceClass::TOUCH))) {
2453         // Load the virtual keys for the touch screen, if any.
2454         // We do this now so that we can make sure to load the keymap if necessary.
2455         bool success = device->loadVirtualKeyMapLocked();
2456         if (success) {
2457             device->classes |= InputDeviceClass::KEYBOARD;
2458         }
2459     }
2460 
2461     // Load the key map.
2462     // We need to do this for joysticks too because the key layout may specify axes, and for
2463     // sensor as well because the key layout may specify the axes to sensor data mapping.
2464     status_t keyMapStatus = NAME_NOT_FOUND;
2465     if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2466                             InputDeviceClass::SENSOR)) {
2467         // Load the keymap for the device.
2468         keyMapStatus = device->loadKeyMapLocked();
2469     }
2470 
2471     // Configure the keyboard, gamepad or virtual keyboard.
2472     if (device->classes.test(InputDeviceClass::KEYBOARD)) {
2473         // Register the keyboard as a built-in keyboard if it is eligible.
2474         if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
2475             isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2476                                       &device->keyMap)) {
2477             mBuiltInKeyboardId = device->id;
2478         }
2479 
2480         // 'Q' key support = cheap test of whether this is an alpha-capable kbd
2481         if (device->hasKeycodeLocked(AKEYCODE_Q)) {
2482             device->classes |= InputDeviceClass::ALPHAKEY;
2483         }
2484 
2485         // See if this device has a D-pad.
2486         if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2487                         [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2488             device->classes |= InputDeviceClass::DPAD;
2489         }
2490 
2491         // See if this device has a gamepad.
2492         if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2493                         [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2494             device->classes |= InputDeviceClass::GAMEPAD;
2495         }
2496 
2497         // See if this device has any stylus buttons that we would want to fuse with touch data.
2498         if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
2499             !device->classes.any(InputDeviceClass::ALPHAKEY) &&
2500             std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2501                         [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2502             device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2503         }
2504     }
2505 
2506     // If the device isn't recognized as something we handle, don't monitor it.
2507     if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
2508         ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
2509               device->identifier.name.c_str());
2510         return;
2511     }
2512 
2513     // Classify InputDeviceClass::BATTERY.
2514     if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
2515         device->classes |= InputDeviceClass::BATTERY;
2516     }
2517 
2518     // Classify InputDeviceClass::LIGHT.
2519     if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
2520         device->classes |= InputDeviceClass::LIGHT;
2521     }
2522 
2523     // Determine whether the device has a mic.
2524     if (device->deviceHasMicLocked()) {
2525         device->classes |= InputDeviceClass::MIC;
2526     }
2527 
2528     // Determine whether the device is external or internal.
2529     if (device->isExternalDeviceLocked()) {
2530         device->classes |= InputDeviceClass::EXTERNAL;
2531     }
2532 
2533     if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2534         device->classes.test(InputDeviceClass::GAMEPAD)) {
2535         device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2536         device->setLedForControllerLocked();
2537     }
2538 
2539     if (registerDeviceForEpollLocked(*device) != OK) {
2540         return;
2541     }
2542 
2543     device->configureFd();
2544 
2545     ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
2546           "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
2547           deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2548           device->classes.string().c_str(), device->configurationFile.c_str(),
2549           device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2550           toString(mBuiltInKeyboardId == deviceId));
2551 
2552     addDeviceLocked(std::move(device));
2553 }
2554 
openVideoDeviceLocked(const std::string & devicePath)2555 void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2556     std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2557     if (!videoDevice) {
2558         ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2559         return;
2560     }
2561     // Transfer ownership of this video device to a matching input device
2562     for (const auto& [id, device] : mDevices) {
2563         if (tryAddVideoDeviceLocked(*device, videoDevice)) {
2564             return; // 'device' now owns 'videoDevice'
2565         }
2566     }
2567 
2568     // Couldn't find a matching input device, so just add it to a temporary holding queue.
2569     // A matching input device may appear later.
2570     ALOGI("Adding video device %s to list of unattached video devices",
2571           videoDevice->getName().c_str());
2572     mUnattachedVideoDevices.push_back(std::move(videoDevice));
2573 }
2574 
tryAddVideoDeviceLocked(EventHub::Device & device,std::unique_ptr<TouchVideoDevice> & videoDevice)2575 bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2576                                        std::unique_ptr<TouchVideoDevice>& videoDevice) {
2577     if (videoDevice->getName() != device.identifier.name) {
2578         return false;
2579     }
2580     device.videoDevice = std::move(videoDevice);
2581     if (device.enabled) {
2582         registerVideoDeviceForEpollLocked(*device.videoDevice);
2583     }
2584     return true;
2585 }
2586 
isDeviceEnabled(int32_t deviceId) const2587 bool EventHub::isDeviceEnabled(int32_t deviceId) const {
2588     std::scoped_lock _l(mLock);
2589     Device* device = getDeviceLocked(deviceId);
2590     if (device == nullptr) {
2591         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2592         return false;
2593     }
2594     return device->enabled;
2595 }
2596 
enableDevice(int32_t deviceId)2597 status_t EventHub::enableDevice(int32_t deviceId) {
2598     std::scoped_lock _l(mLock);
2599     Device* device = getDeviceLocked(deviceId);
2600     if (device == nullptr) {
2601         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2602         return BAD_VALUE;
2603     }
2604     if (device->enabled) {
2605         ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2606         return OK;
2607     }
2608     status_t result = device->enable();
2609     if (result != OK) {
2610         ALOGE("Failed to enable device %" PRId32, deviceId);
2611         return result;
2612     }
2613 
2614     device->configureFd();
2615 
2616     return registerDeviceForEpollLocked(*device);
2617 }
2618 
disableDevice(int32_t deviceId)2619 status_t EventHub::disableDevice(int32_t deviceId) {
2620     std::scoped_lock _l(mLock);
2621     Device* device = getDeviceLocked(deviceId);
2622     if (device == nullptr) {
2623         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2624         return BAD_VALUE;
2625     }
2626     if (!device->enabled) {
2627         ALOGW("Duplicate call to %s, input device already disabled", __func__);
2628         return OK;
2629     }
2630     unregisterDeviceFromEpollLocked(*device);
2631     return device->disable();
2632 }
2633 
2634 // TODO(b/274755573): Shift to uevent handling on native side and remove this method
2635 // Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2636 // NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2637 // directly observe UEvents instead of triggering from Java side.
sysfsNodeChanged(const std::string & sysfsNodePath)2638 void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2639     std::scoped_lock _l(mLock);
2640 
2641     // Check in opening devices
2642     for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2643         std::unique_ptr<Device>& device = *it;
2644         if (device->associatedDevice &&
2645             sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2646                     std::string::npos &&
2647             device->associatedDevice->isChanged()) {
2648             it = mOpeningDevices.erase(it);
2649             openDeviceLocked(device->path);
2650         }
2651     }
2652 
2653     // Check in already added device
2654     std::vector<Device*> devicesToReopen;
2655     for (const auto& [id, device] : mDevices) {
2656         if (device->associatedDevice &&
2657             sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2658                     std::string::npos &&
2659             device->associatedDevice->isChanged()) {
2660             devicesToReopen.push_back(device.get());
2661         }
2662     }
2663     for (const auto& device : devicesToReopen) {
2664         closeDeviceLocked(*device);
2665         openDeviceLocked(device->path);
2666     }
2667     devicesToReopen.clear();
2668 }
2669 
createVirtualKeyboardLocked()2670 void EventHub::createVirtualKeyboardLocked() {
2671     InputDeviceIdentifier identifier;
2672     identifier.name = "Virtual";
2673     identifier.uniqueId = "<virtual>";
2674     assignDescriptorLocked(identifier);
2675 
2676     std::unique_ptr<Device> device =
2677             std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2678                                      identifier, /*associatedDevice=*/nullptr);
2679     device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2680             InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
2681     device->loadKeyMapLocked();
2682     addDeviceLocked(std::move(device));
2683 }
2684 
addDeviceLocked(std::unique_ptr<Device> device)2685 void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
2686     reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
2687     mOpeningDevices.push_back(std::move(device));
2688 }
2689 
getNextControllerNumberLocked(const std::string & name)2690 int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
2691     if (mControllerNumbers.isFull()) {
2692         ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
2693               name.c_str());
2694         return 0;
2695     }
2696     // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2697     // one
2698     return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2699 }
2700 
releaseControllerNumberLocked(int32_t num)2701 void EventHub::releaseControllerNumberLocked(int32_t num) {
2702     if (num > 0) {
2703         mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
2704     }
2705 }
2706 
closeDeviceByPathLocked(const std::string & devicePath)2707 void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
2708     Device* device = getDeviceByPathLocked(devicePath);
2709     if (device != nullptr) {
2710         closeDeviceLocked(*device);
2711         return;
2712     }
2713     ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
2714 }
2715 
2716 /**
2717  * Find the video device by filename, and close it.
2718  * The video device is closed by path during an inotify event, where we don't have the
2719  * additional context about the video device fd, or the associated input device.
2720  */
closeVideoDeviceByPathLocked(const std::string & devicePath)2721 void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
2722     // A video device may be owned by an existing input device, or it may be stored in
2723     // the mUnattachedVideoDevices queue. Check both locations.
2724     for (const auto& [id, device] : mDevices) {
2725         if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
2726             unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
2727             device->videoDevice = nullptr;
2728             return;
2729         }
2730     }
2731     std::erase_if(mUnattachedVideoDevices,
2732                   [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2733                       return videoDevice->getPath() == devicePath;
2734                   });
2735 }
2736 
closeAllDevicesLocked()2737 void EventHub::closeAllDevicesLocked() {
2738     mUnattachedVideoDevices.clear();
2739     while (!mDevices.empty()) {
2740         closeDeviceLocked(*(mDevices.begin()->second));
2741     }
2742 }
2743 
closeDeviceLocked(Device & device)2744 void EventHub::closeDeviceLocked(Device& device) {
2745     ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2746           device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
2747 
2748     if (device.id == mBuiltInKeyboardId) {
2749         ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
2750               device.path.c_str(), mBuiltInKeyboardId);
2751         mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2752     }
2753 
2754     unregisterDeviceFromEpollLocked(device);
2755     if (device.videoDevice) {
2756         // This must be done after the video device is removed from epoll
2757         mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
2758     }
2759 
2760     releaseControllerNumberLocked(device.controllerNumber);
2761     device.controllerNumber = 0;
2762     device.close();
2763     mClosingDevices.push_back(std::move(mDevices[device.id]));
2764 
2765     mDevices.erase(device.id);
2766 }
2767 
readNotifyLocked()2768 base::Result<void> EventHub::readNotifyLocked() {
2769     static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2770     uint8_t eventBuffer[512];
2771     ssize_t sizeRead;
2772 
2773     ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2774     do {
2775         sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2776     } while (sizeRead < 0 && errno == EINTR);
2777 
2778     if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2779 
2780     for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2781         const inotify_event* event;
2782         event = (const inotify_event*)(eventBuffer + eventPos);
2783         if (event->len == 0) continue;
2784 
2785         handleNotifyEventLocked(*event);
2786 
2787         const ssize_t eventSize = EVENT_SIZE + event->len;
2788         sizeRead -= eventSize;
2789         eventPos += eventSize;
2790     }
2791     return {};
2792 }
2793 
handleNotifyEventLocked(const inotify_event & event)2794 void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2795     if (event.wd == mDeviceInputWd) {
2796         std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2797         if (event.mask & IN_CREATE) {
2798             openDeviceLocked(filename);
2799         } else {
2800             ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2801             closeDeviceByPathLocked(filename);
2802         }
2803     } else if (event.wd == mDeviceWd) {
2804         if (isV4lTouchNode(event.name)) {
2805             std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2806             if (event.mask & IN_CREATE) {
2807                 openVideoDeviceLocked(filename);
2808             } else {
2809                 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2810                 closeVideoDeviceByPathLocked(filename);
2811             }
2812         } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2813             addDeviceInputInotify();
2814         }
2815     } else {
2816         LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2817     }
2818 }
2819 
scanDirLocked(const std::string & dirname)2820 status_t EventHub::scanDirLocked(const std::string& dirname) {
2821     for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2822         openDeviceLocked(entry.path());
2823     }
2824     return 0;
2825 }
2826 
2827 /**
2828  * Look for all dirname/v4l-touch* devices, and open them.
2829  */
scanVideoDirLocked(const std::string & dirname)2830 status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
2831     for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2832         if (isV4lTouchNode(entry.path())) {
2833             ALOGI("Found touch video device %s", entry.path().c_str());
2834             openVideoDeviceLocked(entry.path());
2835         }
2836     }
2837     return OK;
2838 }
2839 
requestReopenDevices()2840 void EventHub::requestReopenDevices() {
2841     ALOGV("requestReopenDevices() called");
2842 
2843     std::scoped_lock _l(mLock);
2844     mNeedToReopenDevices = true;
2845 }
2846 
dump(std::string & dump) const2847 void EventHub::dump(std::string& dump) const {
2848     dump += "Event Hub State:\n";
2849 
2850     { // acquire lock
2851         std::scoped_lock _l(mLock);
2852 
2853         dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
2854 
2855         dump += INDENT "Devices:\n";
2856 
2857         for (const auto& [id, device] : mDevices) {
2858             if (mBuiltInKeyboardId == device->id) {
2859                 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
2860                                      device->id, device->identifier.name.c_str());
2861             } else {
2862                 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
2863                                      device->identifier.name.c_str());
2864             }
2865             dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
2866             dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
2867             dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
2868             dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2869             dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
2870             dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
2871             dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
2872             dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
2873                                          "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
2874                                  device->identifier.bus, device->identifier.vendor,
2875                                  device->identifier.product, device->identifier.version,
2876                                  toString(device->identifier.bluetoothAddress).c_str());
2877             dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
2878                                  device->keyMap.keyLayoutFile.c_str());
2879             dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
2880                                  device->keyMap.keyCharacterMapFile.c_str());
2881             if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2882                 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2883                                      device->associatedDevice->layoutInfo->languageTag.c_str());
2884                 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2885                                      device->associatedDevice->layoutInfo->layoutType.c_str());
2886             }
2887             dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
2888                                  device->configurationFile.c_str());
2889             dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2890                                  device->videoDevice ? device->videoDevice->dump().c_str()
2891                                                      : "<none>");
2892             dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2893                                  device->associatedDevice
2894                                          ? device->associatedDevice->sysfsRootPath.c_str()
2895                                          : "<none>");
2896             if (device->keyBitmask.any(0, KEY_MAX + 1)) {
2897                 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
2898                     return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
2899                 });
2900                 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
2901             }
2902             if (device->swBitmask.any(0, SW_MAX + 1)) {
2903                 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
2904                     return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
2905                 });
2906                 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
2907             }
2908             if (!device->absState.empty()) {
2909                 std::string axisValues;
2910                 for (const auto& [axis, state] : device->absState) {
2911                     if (!axisValues.empty()) {
2912                         axisValues += ", ";
2913                     }
2914                     axisValues += StringPrintf("%s=%d",
2915                                                InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
2916                                                        .code.c_str(),
2917                                                state.value);
2918                 }
2919                 dump += INDENT3 "AbsState: " + axisValues + "\n";
2920             }
2921         }
2922 
2923         dump += INDENT "Unattached video devices:\n";
2924         for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2925             dump += INDENT2 + videoDevice->dump() + "\n";
2926         }
2927         if (mUnattachedVideoDevices.empty()) {
2928             dump += INDENT2 "<none>\n";
2929         }
2930     } // release lock
2931 }
2932 
monitor() const2933 void EventHub::monitor() const {
2934     // Acquire and release the lock to ensure that the event hub has not deadlocked.
2935     std::unique_lock<std::mutex> lock(mLock);
2936 }
2937 
dump() const2938 std::string EventHub::AssociatedDevice::dump() const {
2939     return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2940                         batteryInfos.size(), lightInfos.size());
2941 }
2942 
2943 } // namespace android
2944