Replace non-alphanumerics with _ in VirtualKeyMap

We currently rewrite device name for finding the matching .idc, .kl,
.kcm files, but we aren't allowing this for virtual key maps.

Rewrite the name for virtual devices to provide some flexibility in
matching for the right files in sys/board_properties.

Bug: 113575658
Test: atest libinput_tests inputflinger_tests
Change-Id: I54d159e9ecf02327cae388ae14c0bcf21c415e6e
diff --git a/include/input/InputDevice.h b/include/input/InputDevice.h
index ce8db91..48ac88d 100644
--- a/include/input/InputDevice.h
+++ b/include/input/InputDevice.h
@@ -51,6 +51,15 @@
     // is intended to be a minimum way to distinguish from other active devices and may
     // reuse values that are not associated with an input anymore.
     uint16_t nonce;
+
+    /**
+     * Return InputDeviceIdentifier.name that has been adjusted as follows:
+     *     - all characters besides alphanumerics, dash,
+     *       and underscore have been replaced with underscores.
+     * This helps in situations where a file that matches the device name is needed,
+     * while conforming to the filename limitations.
+     */
+    std::string getCanonicalName() const;
 };
 
 /*
diff --git a/libs/input/InputDevice.cpp b/libs/input/InputDevice.cpp
index 778c453..7dcad5a 100644
--- a/libs/input/InputDevice.cpp
+++ b/libs/input/InputDevice.cpp
@@ -140,6 +140,18 @@
     return "";
 }
 
+// --- InputDeviceIdentifier
+
+std::string InputDeviceIdentifier::getCanonicalName() const {
+    std::string replacedName = name;
+    for (char& ch : replacedName) {
+        if (!isValidNameChar(ch)) {
+            ch = '_';
+        }
+    }
+    return replacedName;
+}
+
 
 // --- InputDeviceInfo ---
 
diff --git a/services/inputflinger/EventHub.cpp b/services/inputflinger/EventHub.cpp
index 4735643..4da1473 100644
--- a/services/inputflinger/EventHub.cpp
+++ b/services/inputflinger/EventHub.cpp
@@ -1617,7 +1617,7 @@
     // The virtual key map is supplied by the kernel as a system board property file.
     std::string path;
     path += "/sys/board_properties/virtualkeys.";
-    path += device->identifier.name;
+    path += device->identifier.getCanonicalName();
     if (access(path.c_str(), R_OK)) {
         return false;
     }