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