sensorhal: validate handle value is in range

Test: send out of range value to flush (asan build of libhubconnection.so)
Bug: 32648480
Change-Id: Ie3147367dc61fb09ba486dcbbaa6a38b6faedbfb
Signed-off-by: Ben Fennema <fennema@google.com>
diff --git a/sensorhal/hubconnection.cpp b/sensorhal/hubconnection.cpp
index 5a464df..1e93973 100644
--- a/sensorhal/hubconnection.cpp
+++ b/sensorhal/hubconnection.cpp
@@ -1250,7 +1250,7 @@
 
     Mutex::Autolock autoLock(mLock);
 
-    if (mSensorState[handle].sensorType) {
+    if (isValidHandle(handle)) {
         mSensorState[handle].enable = enable;
 
         initConfigCmd(&cmd, handle);
@@ -1274,7 +1274,7 @@
 
     Mutex::Autolock autoLock(mLock);
 
-    if (mSensorState[handle].sensorType) {
+    if (isValidHandle(handle)) {
         if (sampling_period_ns > 0 &&
                 mSensorState[handle].rate != SENSOR_RATE_ONCHANGE &&
                 mSensorState[handle].rate != SENSOR_RATE_ONESHOT) {
@@ -1305,7 +1305,7 @@
 
     Mutex::Autolock autoLock(mLock);
 
-    if (mSensorState[handle].sensorType) {
+    if (isValidHandle(handle)) {
         if (sampling_period_ns > 0 &&
                 mSensorState[handle].rate != SENSOR_RATE_ONCHANGE &&
                 mSensorState[handle].rate != SENSOR_RATE_ONESHOT) {
@@ -1335,7 +1335,7 @@
 
     Mutex::Autolock autoLock(mLock);
 
-    if (mSensorState[handle].sensorType) {
+    if (isValidHandle(handle)) {
         mSensorState[handle].flushCnt++;
 
         initConfigCmd(&cmd, handle);
@@ -1359,7 +1359,7 @@
     struct ConfigCmd *cmd = (struct ConfigCmd *)malloc(sizeof(struct ConfigCmd) + length);
     size_t ret;
 
-    if (cmd && mSensorState[handle].sensorType) {
+    if (cmd && isValidHandle(handle)) {
         initConfigCmd(cmd, handle);
         memcpy(cmd->data, data, length);
         cmd->cmd = CONFIG_CMD_CFG_DATA;
diff --git a/sensorhal/hubconnection.h b/sensorhal/hubconnection.h
index 77b5fe1..a609e66 100644
--- a/sensorhal/hubconnection.h
+++ b/sensorhal/hubconnection.h
@@ -219,6 +219,12 @@
     void postOsLog(uint8_t *buf, ssize_t len);
     ssize_t processBuf(uint8_t *buf, ssize_t len);
 
+    inline bool isValidHandle(int handle) {
+        return handle >= 0
+            && handle < NUM_COMMS_SENSORS_PLUS_1
+            && mSensorState[handle].sensorType;
+    }
+
     void initConfigCmd(struct ConfigCmd *cmd, int handle);
 
     void queueDataInternal(int handle, void *data, size_t length);