Limit the number of keys read by KeyCharacterMaps.

Apps can send us a KCM containing a ridiculous key count, which will
cause us to crash when an allocation fails. Limit the key count so this
doesn't happen.

Bug: 24876135
Change-Id: I2bb4a5acabfc9184a867a406eef756c28c28f0ad
diff --git a/include/input/KeyCharacterMap.h b/include/input/KeyCharacterMap.h
index eb5840e..7935927 100644
--- a/include/input/KeyCharacterMap.h
+++ b/include/input/KeyCharacterMap.h
@@ -31,6 +31,9 @@
 #include <utils/Unicode.h>
 #include <utils/RefBase.h>
 
+// Maximum number of keys supported by KeyCharacterMaps
+#define MAX_KEYS 8192
+
 namespace android {
 
 /**
diff --git a/libs/input/KeyCharacterMap.cpp b/libs/input/KeyCharacterMap.cpp
index dd01a93..fe649fb 100644
--- a/libs/input/KeyCharacterMap.cpp
+++ b/libs/input/KeyCharacterMap.cpp
@@ -607,6 +607,10 @@
     if (parcel->errorCheck()) {
         return NULL;
     }
+    if (numKeys > MAX_KEYS) {
+        ALOGE("Too many keys in KeyCharacterMap (%d > %d)", numKeys, MAX_KEYS);
+        return NULL;
+    }
 
     for (size_t i = 0; i < numKeys; i++) {
         int32_t keyCode = parcel->readInt32();