Refactor sensor list in SensorService

Refactor sensor lists management logic in sensorservice:
  * Factor all sensor list management code into a separate class.
  * Remove error-prone repeated sensor lists.
  * Solve synchronization issue when sensor is added or removed during runtime.
  * Switch to STL containers.

Bug: b/27911774

Change-Id: I94d5571e1fa3166dbe893ffac2a2a7584be6349c
diff --git a/include/gui/Sensor.h b/include/gui/Sensor.h
index 3792540..353003c 100644
--- a/include/gui/Sensor.h
+++ b/include/gui/Sensor.h
@@ -56,7 +56,7 @@
         uint8_t b[16];
     } uuid_t;
 
-    Sensor();
+    Sensor(const char * name = "");
     Sensor(struct sensor_t const* hwSensor, int halVersion = 0);
     ~Sensor();
 
@@ -80,6 +80,7 @@
     int32_t getMaxDelay() const;
     uint32_t getFlags() const;
     bool isWakeUpSensor() const;
+    bool isDynamicSensor() const;
     int32_t getReportingMode() const;
     const uuid_t& getUuid() const;
 
diff --git a/libs/gui/Sensor.cpp b/libs/gui/Sensor.cpp
index 0b2b942..4b9a2ab 100644
--- a/libs/gui/Sensor.cpp
+++ b/libs/gui/Sensor.cpp
@@ -35,8 +35,8 @@
 namespace android {
 // ----------------------------------------------------------------------------
 
-Sensor::Sensor()
-    : mHandle(0), mType(0),
+Sensor::Sensor(const char * name)
+    : mName(name), mHandle(0), mType(0),
       mMinValue(0), mMaxValue(0), mResolution(0),
       mPower(0), mMinDelay(0), mVersion(0), mFifoReservedEventCount(0),
       mFifoMaxEventCount(0), mRequiredAppOp(0),
@@ -390,6 +390,10 @@
     return mFlags & SENSOR_FLAG_WAKE_UP;
 }
 
+bool Sensor::isDynamicSensor() const {
+    return mFlags & SENSOR_FLAG_DYNAMIC_SENSOR;
+}
+
 int32_t Sensor::getReportingMode() const {
     return ((mFlags & REPORTING_MODE_MASK) >> REPORTING_MODE_SHIFT);
 }
diff --git a/services/sensorservice/Android.mk b/services/sensorservice/Android.mk
index 57c56a6..85e96d6 100644
--- a/services/sensorservice/Android.mk
+++ b/services/sensorservice/Android.mk
@@ -16,6 +16,7 @@
     SensorEventConnection.cpp \
     MostRecentEventLogger.cpp \
     SensorRecord.cpp \
+    SensorList.cpp \
 
 
 LOCAL_CFLAGS:= -DLOG_TAG=\"SensorService\"
diff --git a/services/sensorservice/CorrectedGyroSensor.cpp b/services/sensorservice/CorrectedGyroSensor.cpp
index 7b1f346..788def9 100644
--- a/services/sensorservice/CorrectedGyroSensor.cpp
+++ b/services/sensorservice/CorrectedGyroSensor.cpp
@@ -39,6 +39,18 @@
             break;
         }
     }
+
+    sensor_t hwSensor;
+    hwSensor.name       = "Corrected Gyroscope Sensor";
+    hwSensor.vendor     = "AOSP";
+    hwSensor.version    = 1;
+    hwSensor.handle     = '_cgy';
+    hwSensor.type       = SENSOR_TYPE_GYROSCOPE;
+    hwSensor.maxRange   = mGyro.getMaxValue();
+    hwSensor.resolution = mGyro.getResolution();
+    hwSensor.power      = mSensorFusion.getPowerUsage();
+    hwSensor.minDelay   = mGyro.getMinDelay();
+    mSensor = Sensor(&hwSensor);
 }
 
 bool CorrectedGyroSensor::process(sensors_event_t* outEvent,
@@ -66,19 +78,8 @@
     return mSensorFusion.setDelay(FUSION_9AXIS, ident, ns);
 }
 
-Sensor CorrectedGyroSensor::getSensor() const {
-    sensor_t hwSensor;
-    hwSensor.name       = "Corrected Gyroscope Sensor";
-    hwSensor.vendor     = "AOSP";
-    hwSensor.version    = 1;
-    hwSensor.handle     = '_cgy';
-    hwSensor.type       = SENSOR_TYPE_GYROSCOPE;
-    hwSensor.maxRange   = mGyro.getMaxValue();
-    hwSensor.resolution = mGyro.getResolution();
-    hwSensor.power      = mSensorFusion.getPowerUsage();
-    hwSensor.minDelay   = mGyro.getMinDelay();
-    Sensor sensor(&hwSensor);
-    return sensor;
+const Sensor& CorrectedGyroSensor::getSensor() const {
+    return mSensor;
 }
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/CorrectedGyroSensor.h b/services/sensorservice/CorrectedGyroSensor.h
index 3c49c08..3419a8a 100644
--- a/services/sensorservice/CorrectedGyroSensor.h
+++ b/services/sensorservice/CorrectedGyroSensor.h
@@ -35,15 +35,15 @@
     SensorDevice& mSensorDevice;
     SensorFusion& mSensorFusion;
     Sensor mGyro;
+    Sensor mSensor;
 
 public:
     CorrectedGyroSensor(sensor_t const* list, size_t count);
-    virtual bool process(sensors_event_t* outEvent,
-            const sensors_event_t& event);
-    virtual status_t activate(void* ident, bool enabled);
-    virtual status_t setDelay(void* ident, int handle, int64_t ns);
-    virtual Sensor getSensor() const;
-    virtual bool isVirtual() const { return true; }
+    virtual bool process(sensors_event_t* outEvent, const sensors_event_t& event) override;
+    virtual status_t activate(void* ident, bool enabled) override;
+    virtual status_t setDelay(void* ident, int handle, int64_t ns) override;
+    virtual const Sensor& getSensor() const override;
+    virtual bool isVirtual() const override { return true; }
 };
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/GravitySensor.cpp b/services/sensorservice/GravitySensor.cpp
index a165a5b..0e80f16 100644
--- a/services/sensorservice/GravitySensor.cpp
+++ b/services/sensorservice/GravitySensor.cpp
@@ -39,6 +39,18 @@
             break;
         }
     }
+
+    sensor_t hwSensor;
+    hwSensor.name       = "Gravity Sensor";
+    hwSensor.vendor     = "AOSP";
+    hwSensor.version    = 3;
+    hwSensor.handle     = '_grv';
+    hwSensor.type       = SENSOR_TYPE_GRAVITY;
+    hwSensor.maxRange   = GRAVITY_EARTH * 2;
+    hwSensor.resolution = mAccelerometer.getResolution();
+    hwSensor.power      = mSensorFusion.getPowerUsage();
+    hwSensor.minDelay   = mSensorFusion.getMinDelay();
+    mSensor = Sensor(&hwSensor);
 }
 
 bool GravitySensor::process(sensors_event_t* outEvent,
@@ -73,19 +85,8 @@
     return mSensorFusion.setDelay(FUSION_NOMAG, ident, ns);
 }
 
-Sensor GravitySensor::getSensor() const {
-    sensor_t hwSensor;
-    hwSensor.name       = "Gravity Sensor";
-    hwSensor.vendor     = "AOSP";
-    hwSensor.version    = 3;
-    hwSensor.handle     = '_grv';
-    hwSensor.type       = SENSOR_TYPE_GRAVITY;
-    hwSensor.maxRange   = GRAVITY_EARTH * 2;
-    hwSensor.resolution = mAccelerometer.getResolution();
-    hwSensor.power      = mSensorFusion.getPowerUsage();
-    hwSensor.minDelay   = mSensorFusion.getMinDelay();
-    Sensor sensor(&hwSensor);
-    return sensor;
+const Sensor& GravitySensor::getSensor() const {
+    return mSensor;
 }
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/GravitySensor.h b/services/sensorservice/GravitySensor.h
index ac177c4..f9c0a99 100644
--- a/services/sensorservice/GravitySensor.h
+++ b/services/sensorservice/GravitySensor.h
@@ -35,15 +35,15 @@
     SensorDevice& mSensorDevice;
     SensorFusion& mSensorFusion;
     Sensor mAccelerometer;
+    Sensor mSensor;
 
 public:
     GravitySensor(sensor_t const* list, size_t count);
-    virtual bool process(sensors_event_t* outEvent,
-            const sensors_event_t& event);
-    virtual status_t activate(void* ident, bool enabled);
-    virtual status_t setDelay(void* ident, int handle, int64_t ns);
-    virtual Sensor getSensor() const;
-    virtual bool isVirtual() const { return true; }
+    virtual bool process(sensors_event_t* outEvent, const sensors_event_t& event) override;
+    virtual status_t activate(void* ident, bool enabled) override;
+    virtual status_t setDelay(void* ident, int handle, int64_t ns) override;
+    virtual const Sensor& getSensor() const override;
+    virtual bool isVirtual() const override { return true; }
 };
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/LinearAccelerationSensor.cpp b/services/sensorservice/LinearAccelerationSensor.cpp
index d5f20d2..04beced 100644
--- a/services/sensorservice/LinearAccelerationSensor.cpp
+++ b/services/sensorservice/LinearAccelerationSensor.cpp
@@ -33,6 +33,18 @@
     : mSensorDevice(SensorDevice::getInstance()),
       mGravitySensor(list, count)
 {
+    const Sensor &gsensor = mGravitySensor.getSensor();
+    sensor_t hwSensor;
+    hwSensor.name       = "Linear Acceleration Sensor";
+    hwSensor.vendor     = "AOSP";
+    hwSensor.version    = gsensor.getVersion();
+    hwSensor.handle     = '_lin';
+    hwSensor.type       = SENSOR_TYPE_LINEAR_ACCELERATION;
+    hwSensor.maxRange   = gsensor.getMaxValue();
+    hwSensor.resolution = gsensor.getResolution();
+    hwSensor.power      = gsensor.getPowerUsage();
+    hwSensor.minDelay   = gsensor.getMinDelay();
+    mSensor = Sensor(&hwSensor);
 }
 
 bool LinearAccelerationSensor::process(sensors_event_t* outEvent,
@@ -58,20 +70,8 @@
     return mGravitySensor.setDelay(ident, handle, ns);
 }
 
-Sensor LinearAccelerationSensor::getSensor() const {
-    Sensor gsensor(mGravitySensor.getSensor());
-    sensor_t hwSensor;
-    hwSensor.name       = "Linear Acceleration Sensor";
-    hwSensor.vendor     = "AOSP";
-    hwSensor.version    = gsensor.getVersion();
-    hwSensor.handle     = '_lin';
-    hwSensor.type       = SENSOR_TYPE_LINEAR_ACCELERATION;
-    hwSensor.maxRange   = gsensor.getMaxValue();
-    hwSensor.resolution = gsensor.getResolution();
-    hwSensor.power      = gsensor.getPowerUsage();
-    hwSensor.minDelay   = gsensor.getMinDelay();
-    Sensor sensor(&hwSensor);
-    return sensor;
+const Sensor& LinearAccelerationSensor::getSensor() const {
+    return mSensor;
 }
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/LinearAccelerationSensor.h b/services/sensorservice/LinearAccelerationSensor.h
index 5deb24f..6b8027b 100644
--- a/services/sensorservice/LinearAccelerationSensor.h
+++ b/services/sensorservice/LinearAccelerationSensor.h
@@ -35,15 +35,16 @@
 class LinearAccelerationSensor : public SensorInterface {
     SensorDevice& mSensorDevice;
     GravitySensor mGravitySensor;
+    Sensor mSensor;
 
     virtual bool process(sensors_event_t* outEvent,
             const sensors_event_t& event);
 public:
     LinearAccelerationSensor(sensor_t const* list, size_t count);
-    virtual status_t activate(void* ident, bool enabled);
-    virtual status_t setDelay(void* ident, int handle, int64_t ns);
-    virtual Sensor getSensor() const;
-    virtual bool isVirtual() const { return true; }
+    virtual status_t activate(void* ident, bool enabled) override;
+    virtual status_t setDelay(void* ident, int handle, int64_t ns) override;
+    virtual const Sensor& getSensor() const override;
+    virtual bool isVirtual() const override { return true; }
 };
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/OrientationSensor.cpp b/services/sensorservice/OrientationSensor.cpp
index d55f336..20b49be 100644
--- a/services/sensorservice/OrientationSensor.cpp
+++ b/services/sensorservice/OrientationSensor.cpp
@@ -36,6 +36,17 @@
     // FIXME: instead of using the SensorFusion code, we should use
     // the SENSOR_TYPE_ROTATION_VECTOR instead. This way we could use the
     // HAL's implementation.
+    sensor_t hwSensor;
+    hwSensor.name       = "Orientation Sensor";
+    hwSensor.vendor     = "AOSP";
+    hwSensor.version    = 1;
+    hwSensor.handle     = '_ypr';
+    hwSensor.type       = SENSOR_TYPE_ORIENTATION;
+    hwSensor.maxRange   = 360.0f;
+    hwSensor.resolution = 1.0f/256.0f; // FIXME: real value here
+    hwSensor.power      = mSensorFusion.getPowerUsage();
+    hwSensor.minDelay   = mSensorFusion.getMinDelay();
+    mSensor = Sensor(&hwSensor);
 }
 
 bool OrientationSensor::process(sensors_event_t* outEvent,
@@ -73,19 +84,8 @@
     return mSensorFusion.setDelay(FUSION_9AXIS, ident, ns);
 }
 
-Sensor OrientationSensor::getSensor() const {
-    sensor_t hwSensor;
-    hwSensor.name       = "Orientation Sensor";
-    hwSensor.vendor     = "AOSP";
-    hwSensor.version    = 1;
-    hwSensor.handle     = '_ypr';
-    hwSensor.type       = SENSOR_TYPE_ORIENTATION;
-    hwSensor.maxRange   = 360.0f;
-    hwSensor.resolution = 1.0f/256.0f; // FIXME: real value here
-    hwSensor.power      = mSensorFusion.getPowerUsage();
-    hwSensor.minDelay   = mSensorFusion.getMinDelay();
-    Sensor sensor(&hwSensor);
-    return sensor;
+const Sensor& OrientationSensor::getSensor() const {
+    return mSensor;
 }
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/OrientationSensor.h b/services/sensorservice/OrientationSensor.h
index 855949d..644a774 100644
--- a/services/sensorservice/OrientationSensor.h
+++ b/services/sensorservice/OrientationSensor.h
@@ -34,15 +34,15 @@
 class OrientationSensor : public SensorInterface {
     SensorDevice& mSensorDevice;
     SensorFusion& mSensorFusion;
+    Sensor mSensor;
 
 public:
     OrientationSensor();
-    virtual bool process(sensors_event_t* outEvent,
-            const sensors_event_t& event);
-    virtual status_t activate(void* ident, bool enabled);
-    virtual status_t setDelay(void* ident, int handle, int64_t ns);
-    virtual Sensor getSensor() const;
-    virtual bool isVirtual() const { return true; }
+    virtual bool process(sensors_event_t* outEvent, const sensors_event_t& event) override;
+    virtual status_t activate(void* ident, bool enabled) override;
+    virtual status_t setDelay(void* ident, int handle, int64_t ns) override;
+    virtual const Sensor& getSensor() const override;
+    virtual bool isVirtual() const override { return true; }
 };
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/RotationVectorSensor.cpp b/services/sensorservice/RotationVectorSensor.cpp
index 238845b..5a40ef9 100644
--- a/services/sensorservice/RotationVectorSensor.cpp
+++ b/services/sensorservice/RotationVectorSensor.cpp
@@ -32,6 +32,17 @@
       mSensorFusion(SensorFusion::getInstance()),
       mMode(mode)
 {
+    sensor_t hwSensor;
+    hwSensor.name       = getSensorName();
+    hwSensor.vendor     = "AOSP";
+    hwSensor.version    = 3;
+    hwSensor.handle     = getSensorToken();
+    hwSensor.type       = getSensorType();
+    hwSensor.maxRange   = 1;
+    hwSensor.resolution = 1.0f / (1<<24);
+    hwSensor.power      = mSensorFusion.getPowerUsage();
+    hwSensor.minDelay   = mSensorFusion.getMinDelay();
+    mSensor = Sensor(&hwSensor);
 }
 
 bool RotationVectorSensor::process(sensors_event_t* outEvent,
@@ -61,19 +72,8 @@
     return mSensorFusion.setDelay(mMode, ident, ns);
 }
 
-Sensor RotationVectorSensor::getSensor() const {
-    sensor_t hwSensor;
-    hwSensor.name       = getSensorName();
-    hwSensor.vendor     = "AOSP";
-    hwSensor.version    = 3;
-    hwSensor.handle     = getSensorToken();
-    hwSensor.type       = getSensorType();
-    hwSensor.maxRange   = 1;
-    hwSensor.resolution = 1.0f / (1<<24);
-    hwSensor.power      = mSensorFusion.getPowerUsage();
-    hwSensor.minDelay   = mSensorFusion.getMinDelay();
-    Sensor sensor(&hwSensor);
-    return sensor;
+const Sensor& RotationVectorSensor::getSensor() const {
+    return mSensor;
 }
 
 int RotationVectorSensor::getSensorType() const {
@@ -124,6 +124,17 @@
     : mSensorDevice(SensorDevice::getInstance()),
       mSensorFusion(SensorFusion::getInstance())
 {
+    sensor_t hwSensor;
+    hwSensor.name       = "Gyroscope Bias (debug)";
+    hwSensor.vendor     = "AOSP";
+    hwSensor.version    = 1;
+    hwSensor.handle     = '_gbs';
+    hwSensor.type       = SENSOR_TYPE_ACCELEROMETER;
+    hwSensor.maxRange   = 1;
+    hwSensor.resolution = 1.0f / (1<<24);
+    hwSensor.power      = mSensorFusion.getPowerUsage();
+    hwSensor.minDelay   = mSensorFusion.getMinDelay();
+    mSensor = Sensor(&hwSensor);
 }
 
 bool GyroDriftSensor::process(sensors_event_t* outEvent,
@@ -152,19 +163,8 @@
     return mSensorFusion.setDelay(FUSION_9AXIS, ident, ns);
 }
 
-Sensor GyroDriftSensor::getSensor() const {
-    sensor_t hwSensor;
-    hwSensor.name       = "Gyroscope Bias (debug)";
-    hwSensor.vendor     = "AOSP";
-    hwSensor.version    = 1;
-    hwSensor.handle     = '_gbs';
-    hwSensor.type       = SENSOR_TYPE_ACCELEROMETER;
-    hwSensor.maxRange   = 1;
-    hwSensor.resolution = 1.0f / (1<<24);
-    hwSensor.power      = mSensorFusion.getPowerUsage();
-    hwSensor.minDelay   = mSensorFusion.getMinDelay();
-    Sensor sensor(&hwSensor);
-    return sensor;
+const Sensor& GyroDriftSensor::getSensor() const {
+    return mSensor;
 }
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/RotationVectorSensor.h b/services/sensorservice/RotationVectorSensor.h
index 1fc316b..5dba0d5 100644
--- a/services/sensorservice/RotationVectorSensor.h
+++ b/services/sensorservice/RotationVectorSensor.h
@@ -36,6 +36,7 @@
     SensorDevice& mSensorDevice;
     SensorFusion& mSensorFusion;
     int mMode;
+    Sensor mSensor;
 
     int getSensorType() const;
     const char* getSensorName() const ;
@@ -43,12 +44,11 @@
 
 public:
     RotationVectorSensor(int mode = FUSION_9AXIS);
-    virtual bool process(sensors_event_t* outEvent,
-            const sensors_event_t& event);
-    virtual status_t activate(void* ident, bool enabled);
-    virtual status_t setDelay(void* ident, int handle, int64_t ns);
-    virtual Sensor getSensor() const;
-    virtual bool isVirtual() const { return true; }
+    virtual bool process(sensors_event_t* outEvent, const sensors_event_t& event) override;
+    virtual status_t activate(void* ident, bool enabled) override;
+    virtual status_t setDelay(void* ident, int handle, int64_t ns) override;
+    virtual const Sensor& getSensor() const override;
+    virtual bool isVirtual() const override { return true; }
 };
 
 class GameRotationVectorSensor : public RotationVectorSensor {
@@ -64,15 +64,15 @@
 class GyroDriftSensor : public SensorInterface {
     SensorDevice& mSensorDevice;
     SensorFusion& mSensorFusion;
+    Sensor mSensor;
 
 public:
     GyroDriftSensor();
-    virtual bool process(sensors_event_t* outEvent,
-            const sensors_event_t& event);
-    virtual status_t activate(void* ident, bool enabled);
-    virtual status_t setDelay(void* ident, int handle, int64_t ns);
-    virtual Sensor getSensor() const;
-    virtual bool isVirtual() const { return true; }
+    virtual bool process(sensors_event_t* outEvent, const sensors_event_t& event) override;
+    virtual status_t activate(void* ident, bool enabled) override;
+    virtual status_t setDelay(void* ident, int handle, int64_t ns) override;
+    virtual const Sensor& getSensor() const override;
+    virtual bool isVirtual() const override { return true; }
 };
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/SensorInterface.cpp b/services/sensorservice/SensorInterface.cpp
index 970220b..bb2a8a2 100644
--- a/services/sensorservice/SensorInterface.cpp
+++ b/services/sensorservice/SensorInterface.cpp
@@ -65,7 +65,7 @@
     mSensorDevice.autoDisable(ident, handle);
 }
 
-Sensor HardwareSensor::getSensor() const {
+const Sensor& HardwareSensor::getSensor() const {
     return mSensor;
 }
 
diff --git a/services/sensorservice/SensorInterface.h b/services/sensorservice/SensorInterface.h
index 3e76377..06cca75 100644
--- a/services/sensorservice/SensorInterface.h
+++ b/services/sensorservice/SensorInterface.h
@@ -33,8 +33,7 @@
 public:
     virtual ~SensorInterface();
 
-    virtual bool process(sensors_event_t* outEvent,
-            const sensors_event_t& event) = 0;
+    virtual bool process(sensors_event_t* outEvent, const sensors_event_t& event) = 0;
 
     virtual status_t activate(void* ident, bool enabled) = 0;
     virtual status_t setDelay(void* ident, int handle, int64_t ns) = 0;
@@ -52,7 +51,7 @@
         return -EINVAL;
     }
 
-    virtual Sensor getSensor() const = 0;
+    virtual const Sensor& getSensor() const = 0;
     virtual bool isVirtual() const = 0;
     virtual void autoDisable(void* /*ident*/, int /*handle*/) { }
 };
@@ -72,14 +71,14 @@
     virtual bool process(sensors_event_t* outEvent,
             const sensors_event_t& event);
 
-    virtual status_t activate(void* ident, bool enabled);
+    virtual status_t activate(void* ident, bool enabled) override;
     virtual status_t batch(void* ident, int handle, int flags, int64_t samplingPeriodNs,
-                           int64_t maxBatchReportLatencyNs);
-    virtual status_t setDelay(void* ident, int handle, int64_t ns);
-    virtual status_t flush(void* ident, int handle);
-    virtual Sensor getSensor() const;
-    virtual bool isVirtual() const { return false; }
-    virtual void autoDisable(void *ident, int handle);
+                           int64_t maxBatchReportLatencyNs) override;
+    virtual status_t setDelay(void* ident, int handle, int64_t ns) override;
+    virtual status_t flush(void* ident, int handle) override;
+    virtual const Sensor& getSensor() const override;
+    virtual bool isVirtual() const override { return false; }
+    virtual void autoDisable(void *ident, int handle) override;
 };
 
 
diff --git a/services/sensorservice/SensorList.cpp b/services/sensorservice/SensorList.cpp
new file mode 100644
index 0000000..f28acd2
--- /dev/null
+++ b/services/sensorservice/SensorList.cpp
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "SensorList.h"
+
+#include <hardware/sensors.h>
+#include <utils/String8.h>
+
+namespace android {
+namespace SensorServiceUtil {
+
+const Sensor SensorList::mNonSensor = Sensor("unknown");
+
+bool SensorList::add(
+        int handle, SensorInterface* si, bool isForDebug, bool isVirtual) {
+    std::lock_guard<std::mutex> lk(mLock);
+    if (handle == si->getSensor().getHandle() &&
+        mUsedHandle.insert(handle).second) {
+        // will succeed as the mUsedHandle does not have this handle
+        mHandleMap.emplace(handle, Entry(si, isForDebug, isVirtual));
+        return true;
+    }
+    // handle exist already or handle mismatch
+    return false;
+}
+
+bool SensorList::remove(int handle) {
+    std::lock_guard<std::mutex> lk(mLock);
+    auto entry = mHandleMap.find(handle);
+    if (entry != mHandleMap.end()) {
+        mRecycle.push_back(entry->second.si);
+        mHandleMap.erase(entry);
+        return true;
+    }
+    return false;
+}
+
+String8 SensorList::getName(int handle) const {
+    return getOne<String8>(
+            handle, [] (const Entry& e) -> String8 {return e.si->getSensor().getName();},
+            mNonSensor.getName());
+}
+
+const Sensor& SensorList::get(int handle) const {
+    return getOne<const Sensor&>(
+            handle, [] (const Entry& e) -> const Sensor& {return e.si->getSensor();}, mNonSensor);
+}
+
+SensorInterface* SensorList::getInterface(int handle) const {
+    return getOne<SensorInterface *>(
+            handle, [] (const Entry& e) -> SensorInterface* {return e.si;}, nullptr);
+}
+
+
+bool SensorList::isNewHandle(int handle) const {
+    std::lock_guard<std::mutex> lk(mLock);
+    return mUsedHandle.find(handle) == mUsedHandle.end();
+}
+
+const Vector<Sensor> SensorList::getUserSensors() const {
+    // lock in forEachEntry
+    Vector<Sensor> sensors;
+    forEachEntry(
+            [&sensors] (const Entry& e) -> bool {
+                if (!e.isForDebug && !e.si->getSensor().isDynamicSensor()) {
+                    sensors.add(e.si->getSensor());
+                }
+                return true;
+            });
+    return sensors;
+}
+
+const Vector<Sensor> SensorList::getUserDebugSensors() const {
+    // lock in forEachEntry
+    Vector<Sensor> sensors;
+    forEachEntry(
+            [&sensors] (const Entry& e) -> bool {
+                if (!e.si->getSensor().isDynamicSensor()) {
+                    sensors.add(e.si->getSensor());
+                }
+                return true;
+            });
+    return sensors;
+}
+
+const Vector<Sensor> SensorList::getDynamicSensors() const {
+    // lock in forEachEntry
+    Vector<Sensor> sensors;
+    forEachEntry(
+            [&sensors] (const Entry& e) -> bool {
+                if (!e.isForDebug && e.si->getSensor().isDynamicSensor()) {
+                    sensors.add(e.si->getSensor());
+                }
+                return true;
+            });
+    return sensors;
+}
+
+const Vector<Sensor> SensorList::getVirtualSensors() const {
+    // lock in forEachEntry
+    Vector<Sensor> sensors;
+    forEachEntry(
+            [&sensors] (const Entry& e) -> bool {
+                if (e.isVirtual) {
+                    sensors.add(e.si->getSensor());
+                }
+                return true;
+            });
+    return sensors;
+}
+
+std::string SensorList::dump() const {
+    String8 result;
+
+    result.append("Sensor List:\n");
+    forEachSensor([&result] (const Sensor& s) -> bool {
+            result.appendFormat(
+                    "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
+                    s.getName().string(),
+                    s.getVendor().string(),
+                    s.getVersion(),
+                    s.getStringType().string(),
+                    s.getHandle(),
+                    s.getRequiredPermission().string(),
+                    s.getType());
+
+            const int reportingMode = s.getReportingMode();
+            if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
+                result.append(" continuous | ");
+            } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
+                result.append(" on-change | ");
+            } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
+                result.append(" one-shot | ");
+            } else if (reportingMode == AREPORTING_MODE_SPECIAL_TRIGGER) {
+                result.append(" special-trigger | ");
+            } else {
+                result.append(" unknown-mode | ");
+            }
+
+            if (s.getMaxDelay() > 0) {
+                result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
+            } else {
+                result.appendFormat("maxDelay=%dus | ", s.getMaxDelay());
+            }
+
+            if (s.getMinDelay() > 0) {
+                result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
+            } else {
+                result.appendFormat("minDelay=%dus | ", s.getMinDelay());
+            }
+
+            if (s.getFifoMaxEventCount() > 0) {
+                result.appendFormat("FifoMax=%d events | ",
+                        s.getFifoMaxEventCount());
+            } else {
+                result.append("no batching | ");
+            }
+
+            if (s.isWakeUpSensor()) {
+                result.appendFormat("wakeUp | ");
+            } else {
+                result.appendFormat("non-wakeUp | ");
+            }
+
+            result.append("\n");
+            return true;
+        });
+    return std::string(result.string());
+}
+
+SensorList::~SensorList() {
+    // from this point on no one should access anything in SensorList
+    mLock.lock();
+    for (auto i : mRecycle) {
+        delete i;
+    }
+    for (auto&& i : mHandleMap) {
+        delete i.second.si;
+    }
+    // the lock will eventually get destructed, there is no guarantee after that.
+}
+
+} // namespace SensorServiceUtil
+} // namespace android
+
diff --git a/services/sensorservice/SensorList.h b/services/sensorservice/SensorList.h
new file mode 100644
index 0000000..3fe73cc
--- /dev/null
+++ b/services/sensorservice/SensorList.h
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_SENSOR_LIST_H
+#define ANDROID_SENSOR_LIST_H
+
+#include "SensorInterface.h"
+
+#include <gui/Sensor.h>
+#include <utils/String8.h>
+#include <utils/Vector.h>
+
+#include <mutex>
+#include <map>
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+namespace android {
+class SensorInterface;
+
+namespace SensorServiceUtil {
+
+class Dumpable {
+public:
+    virtual std::string dump() const;
+    virtual void setFormat(std::string ) {}
+    virtual ~Dumpable() {}
+};
+
+class SensorList : public Dumpable {
+public:
+    // After SensorInterface * is added into SensorList, it can be assumed that SensorList own the
+    // object it pointed to and the object should not be released elsewhere.
+    bool add(int handle, SensorInterface* si, bool isForDebug = false, bool isVirtual = false);
+    bool remove(int handle);
+
+    inline bool hasAnySensor() const { return mHandleMap.size() > 0;}
+
+    //helper functions
+    const Vector<Sensor> getUserSensors() const;
+    const Vector<Sensor> getUserDebugSensors() const;
+    const Vector<Sensor> getDynamicSensors() const;
+    const Vector<Sensor> getVirtualSensors() const;
+
+    String8 getName(int handle) const;
+    const Sensor& get(int handle) const;
+    SensorInterface* getInterface(int handle) const;
+    bool isNewHandle(int handle) const;
+
+    // Iterate through Sensor in sensor list and perform operation f on each Sensor object.
+    //
+    // TF is a function with the signature:
+    //    bool f(const Sensor &);
+    // A return value of 'false' stops the iteration immediately.
+    //
+    // Note: in the function f, it is illegal to make calls to member functions of the same
+    // SensorList object on which forEachSensor is invoked.
+    template <typename TF>
+    void forEachSensor(const TF& f) const;
+
+    const Sensor& getNonSensor() const { return mNonSensor;}
+
+    // Dumpable interface
+    virtual std::string dump() const override;
+
+    virtual ~SensorList();
+private:
+    struct Entry {
+        //TODO: use sp<> here
+        SensorInterface * const si;
+        const bool isForDebug;
+        const bool isVirtual;
+        Entry(SensorInterface* si_, bool debug_, bool virtual_) :
+            si(si_), isForDebug(debug_), isVirtual(virtual_) {
+        }
+    };
+
+    const static Sensor mNonSensor; //.getName() == "unknown",
+
+    // Iterate through Entry in sensor list and perform operation f on each Entry.
+    //
+    // TF is a function with the signature:
+    //    bool f(const Entry &);
+    // A return value of 'false' stops the iteration over entries immediately.
+    //
+    // Note: in the function being passed in, it is illegal to make calls to member functions of the
+    // same SensorList object on which forEachSensor is invoked.
+    template <typename TF>
+    void forEachEntry(const TF& f) const;
+
+    template <typename T, typename TF>
+    T getOne(int handle, const TF& accessor, T def = T()) const;
+
+    mutable std::mutex mLock;
+    std::map<int, Entry> mHandleMap;
+    std::unordered_set<int> mUsedHandle;
+    std::vector<SensorInterface *> mRecycle;
+};
+
+template <typename TF>
+void SensorList::forEachSensor(const TF& f) const {
+    // lock happens in forEachEntry
+    forEachEntry([&f] (const Entry& e) -> bool { return f(e.si->getSensor());});
+}
+
+template <typename TF>
+void SensorList::forEachEntry(const TF& f) const {
+    std::lock_guard<std::mutex> lk(mLock);
+
+    for (auto&& i : mHandleMap) {
+        if (!f(i.second)){
+            break;
+        }
+    }
+}
+
+template <typename T, typename TF>
+T SensorList::getOne(int handle, const TF& accessor, T def) const {
+    std::lock_guard<std::mutex> lk(mLock);
+    auto i = mHandleMap.find(handle);
+    if (i != mHandleMap.end()) {
+        return accessor(i->second);
+    } else {
+        return def;
+    }
+}
+
+} // namespace SensorServiceUtil
+} // namespace android
+
+#endif // ANDROID_SENSOR_LIST_H
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index 31ca0e3..f334e29 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -125,78 +125,51 @@
             // registered)
             SensorFusion::getInstance();
 
-            // build the sensor list returned to users
-            mUserSensorList = mSensorList;
-
             if (hasGyro && hasAccel && hasMag) {
                 // Add Android virtual sensors if they're not already
                 // available in the HAL
-                Sensor aSensor;
+                bool needRotationVector =
+                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
 
-                aSensor = registerVirtualSensor( new RotationVectorSensor() );
-                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
-                    mUserSensorList.add(aSensor);
-                }
+                registerSensor(new RotationVectorSensor(), !needRotationVector, true);
+                registerSensor(new OrientationSensor(), !needRotationVector, true);
 
-                aSensor = registerVirtualSensor( new OrientationSensor() );
-                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
-                    // if we are doing our own rotation-vector, also add
-                    // the orientation sensor and remove the HAL provided one.
-                    mUserSensorList.replaceAt(aSensor, orientationIndex);
-                }
+                bool needLinearAcceleration =
+                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
 
-                aSensor = registerVirtualSensor(
-                                new LinearAccelerationSensor(list, count) );
-                if (virtualSensorsNeeds &
-                            (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
-                    mUserSensorList.add(aSensor);
-                }
+                registerSensor(new LinearAccelerationSensor(list, count),
+                               !needLinearAcceleration, true);
 
-                // virtual debugging sensors are not added to mUserSensorList
-                registerVirtualSensor( new CorrectedGyroSensor(list, count) );
-                registerVirtualSensor( new GyroDriftSensor() );
+                // virtual debugging sensors are not for user
+                registerSensor( new CorrectedGyroSensor(list, count), false, true);
+                registerSensor( new GyroDriftSensor(), false, true);
             }
 
             if (hasAccel && hasGyro) {
-                Sensor aSensor;
+                bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
+                registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
 
-                aSensor = registerVirtualSensor(
-                                new GravitySensor(list, count) );
-                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
-                    mUserSensorList.add(aSensor);
-                }
-
-                aSensor = registerVirtualSensor(
-                                new GameRotationVectorSensor() );
-                if (virtualSensorsNeeds &
-                            (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) {
-                    mUserSensorList.add(aSensor);
-                }
+                bool needGameRotationVector =
+                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
+                registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
             }
 
             if (hasAccel && hasMag) {
-                Sensor aSensor;
-
-                aSensor = registerVirtualSensor(
-                                new GeoMagRotationVectorSensor() );
-                if (virtualSensorsNeeds &
-                        (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) {
-                    mUserSensorList.add(aSensor);
-                }
+                bool needGeoMagRotationVector =
+                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
+                registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
             }
 
-            // debugging sensor list
-            mUserSensorListDebug = mSensorList;
-
             // Check if the device really supports batching by looking at the FIFO event
             // counts for each sensor.
             bool batchingSupported = false;
-            for (size_t i = 0; i < mSensorList.size(); ++i) {
-                if (mSensorList[i].getFifoMaxEventCount() > 0) {
-                    batchingSupported = true;
-                    break;
-                }
-            }
+            mSensors.forEachSensor(
+                    [&batchingSupported] (const Sensor& s) -> bool {
+                        if (s.getFifoMaxEventCount() > 0) {
+                            batchingSupported = true;
+                        }
+                        return !batchingSupported;
+                    });
 
             if (batchingSupported) {
                 // Increase socket buffer size to a max of 100 KB for batching capabilities.
@@ -242,75 +215,35 @@
     }
 }
 
-Sensor SensorService::registerSensor(SensorInterface* s) {
-    const Sensor sensor(s->getSensor());
-
-    // add handle to used handle list
-    mUsedHandleList.add(sensor.getHandle());
-    // add to the sensor list (returned to clients)
-    mSensorList.add(sensor);
-    // add to our handle->SensorInterface mapping
-    mSensorMap.add(sensor.getHandle(), s);
-    // create an entry in the mLastEventSeen array
-    mLastEventSeen.add(sensor.getHandle(), NULL);
-
-    return sensor;
+const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
+    int handle = s->getSensor().getHandle();
+    if (mSensors.add(handle, s, isDebug, isVirtual)){
+        mLastEventSeen.add(handle, nullptr);
+        return s->getSensor();
+    } else {
+        return mSensors.getNonSensor();
+    }
 }
 
-Sensor SensorService::registerDynamicSensor(SensorInterface* s) {
-    Sensor sensor = registerSensor(s);
-    mDynamicSensorList.add(sensor);
-
-    auto compareSensorHandle = [] (const Sensor* lhs, const Sensor* rhs) {
-        return lhs->getHandle() - rhs->getHandle();
-    };
-    mDynamicSensorList.sort(compareSensorHandle);
-    return sensor;
+const Sensor& SensorService::registerDynamicSensor(SensorInterface* s, bool isDebug) {
+    return registerSensor(s, isDebug);
 }
 
 bool SensorService::unregisterDynamicSensor(int handle) {
-    bool found = false;
-
-    for (size_t i = 0 ; i < mSensorList.size() ; i++) {
-        if (mSensorList[i].getHandle() == handle) {
-            mSensorList.removeAt(i);
-            found = true;
-            break;
-        }
+    bool ret = mSensors.remove(handle);
+    MostRecentEventLogger *buf = mLastEventSeen.valueFor(handle);
+    if (buf) {
+        delete buf;
     }
-
-    if (found) {
-        for (size_t i = 0 ; i < mDynamicSensorList.size() ; i++) {
-            if (mDynamicSensorList[i].getHandle() == handle) {
-                mDynamicSensorList.removeAt(i);
-            }
-        }
-
-        mSensorMap.removeItem(handle);
-        mLastEventSeen.removeItem(handle);
-    }
-    return found;
+    mLastEventSeen.removeItem(handle);
+    return ret;
 }
 
-Sensor SensorService::registerVirtualSensor(SensorInterface* s) {
-    Sensor sensor = registerSensor(s);
-    mVirtualSensorList.add( s );
-    return sensor;
-}
-
-bool SensorService::isNewHandle(int handle) {
-    for (int h : mUsedHandleList) {
-        if (h == handle) {
-            return false;
-        }
-    }
-    return true;
+const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
+    return registerSensor(s, isDebug, true);
 }
 
 SensorService::~SensorService() {
-    for (size_t i=0 ; i<mSensorMap.size() ; i++) {
-        delete mSensorMap.valueAt(i);
-    }
 }
 
 status_t SensorService::dump(int fd, const Vector<String16>& args) {
@@ -374,73 +307,31 @@
                 // Transition to data injection mode supported only from NORMAL mode.
                 return INVALID_OPERATION;
             }
-        } else if (mSensorList.size() == 0) {
+        } else if (!mSensors.hasAnySensor()) {
             result.append("No Sensors on the device\n");
         } else {
             // Default dump the sensor list and debugging information.
-            result.append("Sensor List:\n");
-            for (size_t i=0 ; i<mSensorList.size() ; i++) {
-                const Sensor& s(mSensorList[i]);
-                result.appendFormat(
-                        "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
-                        s.getName().string(),
-                        s.getVendor().string(),
-                        s.getVersion(),
-                        s.getStringType().string(),
-                        s.getHandle(),
-                        s.getRequiredPermission().string(),
-                        s.getType());
+            //
+            result.append(mSensors.dump().c_str());
 
-                const int reportingMode = s.getReportingMode();
-                if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
-                    result.append(" continuous | ");
-                } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
-                    result.append(" on-change | ");
-                } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
-                    result.append(" one-shot | ");
-                } else {
-                    result.append(" special-trigger | ");
-                }
-
-                if (s.getMaxDelay() > 0) {
-                    result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
-                } else {
-                    result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
-                }
-
-                if (s.getMinDelay() > 0) {
-                    result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
-                } else {
-                    result.appendFormat("minDelay=%dus |", s.getMinDelay());
-                }
-
-                if (s.getFifoMaxEventCount() > 0) {
-                    result.appendFormat("FifoMax=%d events | ",
-                            s.getFifoMaxEventCount());
-                } else {
-                    result.append("no batching | ");
-                }
-
-                if (s.isWakeUpSensor()) {
-                    result.appendFormat("wakeUp | ");
-                } else {
-                    result.appendFormat("non-wakeUp | ");
-                }
-
-                int bufIndex = mLastEventSeen.indexOfKey(s.getHandle());
-                if (bufIndex >= 0) {
-                    const MostRecentEventLogger* buf = mLastEventSeen.valueAt(bufIndex);
-                    if (buf != NULL && s.getRequiredPermission().isEmpty()) {
-                        buf->printBuffer(result);
-                    } else {
-                        result.append("last=<> \n");
-                    }
-                }
-                result.append("\n");
-            }
             SensorFusion::getInstance().dump(result);
             SensorDevice::getInstance().dump(result);
 
+            result.append("Recent Sensor events:\n");
+            auto& lastEvents = mLastEventSeen;
+            mSensors.forEachSensor([&result, &lastEvents] (const Sensor& s) -> bool {
+                    int bufIndex = lastEvents.indexOfKey(s.getHandle());
+                    if (bufIndex >= 0) {
+                        const MostRecentEventLogger* buf = lastEvents.valueAt(bufIndex);
+                        if (buf != nullptr && s.getRequiredPermission().isEmpty()) {
+                            result.appendFormat("%s (handle:0x%08x): ",
+                                          s.getName().string(), s.getHandle());
+                            buf->printBuffer(result);
+                        }
+                    }
+                    return true;
+                });
+
             result.append("Active sensors:\n");
             for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
                 int handle = mActiveSensors.keyAt(i);
@@ -508,6 +399,7 @@
     return NO_ERROR;
 }
 
+//TODO: move to SensorEventConnection later
 void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
         sensors_event_t const* buffer, const int count) {
     for (int i=0 ; i<count ; i++) {
@@ -516,12 +408,12 @@
             handle = buffer[i].meta_data.sensor;
         }
         if (connection->hasSensor(handle)) {
-            SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
+            SensorInterface* si = mSensors.getInterface(handle);
             // If this buffer has an event from a one_shot sensor and this connection is registered
             // for this particular one_shot sensor, try cleaning up the connection.
-            if (sensor != NULL &&
-                sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
-                sensor->autoDisable(connection.get(), handle);
+            if (si != NULL &&
+                si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
+                si->autoDisable(connection.get(), handle);
                 cleanupWithoutDisableLocked(connection, handle);
             }
 
@@ -535,11 +427,11 @@
     // each virtual sensor could generate an event per "real" event, that's why we need to size
     // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.  in practice, this is too
     // aggressive, but guaranteed to be enough.
+    const size_t vcount = mSensors.getVirtualSensors().size();
     const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
-    const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
+    const size_t numEventMax = minBufferSize / (1 + vcount);
 
     SensorDevice& device(SensorDevice::getInstance());
-    const size_t vcount = mVirtualSensorList.size();
 
     const int halVersion = device.getHalDeviceVersion();
     do {
@@ -632,10 +524,10 @@
         }
 
         for (int i = 0; i < count; ++i) {
-            // Map flush_complete_events in the buffer to SensorEventConnections which called flush on
-            // the hardware sensor. mapFlushEventsToConnections[i] will be the SensorEventConnection
-            // mapped to the corresponding flush_complete_event in mSensorEventBuffer[i] if such a
-            // mapping exists (NULL otherwise).
+            // Map flush_complete_events in the buffer to SensorEventConnections which called flush
+            // on the hardware sensor. mapFlushEventsToConnections[i] will be the
+            // SensorEventConnection mapped to the corresponding flush_complete_event in
+            // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
             mMapFlushEventsToConnections[i] = NULL;
             if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
                 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
@@ -656,7 +548,7 @@
                     ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
                           handle, dynamicSensor.type, dynamicSensor.name);
 
-                    if (isNewHandle(handle)) {
+                    if (mSensors.isNewHandle(handle)) {
                         sensor_t s = dynamicSensor;
                         // make sure the dynamic sensor flag is set
                         s.flags |= DYNAMIC_SENSOR_MASK;
@@ -664,8 +556,8 @@
                         s.handle = handle;
                         SensorInterface *si = new HardwareSensor(s);
 
-                        // This will release hold on dynamic sensor meta, so it should be called after
-                        // Sensor object is created.
+                        // This will release hold on dynamic sensor meta, so it should be called
+                        // after Sensor object is created.
                         device.handleDynamicSensorConnection(handle, true /*connected*/);
                         registerDynamicSensor(si);
                     } else {
@@ -802,14 +694,7 @@
 }
 
 String8 SensorService::getSensorName(int handle) const {
-    size_t count = mUserSensorList.size();
-    for (size_t i=0 ; i<count ; i++) {
-        const Sensor& sensor(mUserSensorList[i]);
-        if (sensor.getHandle() == handle) {
-            return sensor.getName();
-        }
-    }
-    return String8("unknown");
+    return mSensors.getName(handle);
 }
 
 bool SensorService::isVirtualSensor(int handle) const {
@@ -830,7 +715,7 @@
     char value[PROPERTY_VALUE_MAX];
     property_get("debug.sensors", value, "0");
     const Vector<Sensor>& initialSensorList = (atoi(value)) ?
-            mUserSensorListDebug : mUserSensorList;
+            mSensors.getUserDebugSensors() : mSensors.getUserSensors();
     Vector<Sensor> accessibleSensorList;
     for (size_t i = 0; i < initialSensorList.size(); i++) {
         Sensor sensor = initialSensorList[i];
@@ -848,17 +733,19 @@
 
 Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
     Vector<Sensor> accessibleSensorList;
-    for (size_t i = 0; i < mDynamicSensorList.size(); i++) {
-        Sensor sensor = mDynamicSensorList[i];
-        if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
-            accessibleSensorList.add(sensor);
-        } else {
-            ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
-                  sensor.getName().string(),
-                  sensor.getRequiredPermission().string(),
-                  sensor.getRequiredAppOp());
-        }
-    }
+    mSensors.forEachSensor(
+            [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
+                if (sensor.isDynamicSensor() &&
+                        canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
+                    accessibleSensorList.add(sensor);
+                } else {
+                    ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
+                          sensor.getName().string(),
+                          sensor.getRequiredPermission().string(),
+                          sensor.getRequiredAppOp());
+                }
+                return true;
+            });
     return accessibleSensorList;
 }
 
@@ -950,13 +837,11 @@
 }
 
 SensorInterface* SensorService::getSensorInterfaceFromHandle(int handle) const {
-    ssize_t index = mSensorMap.indexOfKey(handle);
-    return index < 0 ? nullptr : mSensorMap.valueAt(index);
+    return mSensors.getInterface(handle);
 }
 
-Sensor SensorService::getSensorFromHandle(int handle) const {
-    SensorInterface* si = getSensorInterfaceFromHandle(handle);
-    return si ? si->getSensor() : Sensor();
+const Sensor& SensorService::getSensorFromHandle(int handle) const {
+    return mSensors.get(handle);
 }
 
 status_t SensorService::enable(const sp<SensorEventConnection>& connection,
diff --git a/services/sensorservice/SensorService.h b/services/sensorservice/SensorService.h
index da97286..e535339 100644
--- a/services/sensorservice/SensorService.h
+++ b/services/sensorservice/SensorService.h
@@ -37,6 +37,7 @@
 #include <gui/ISensorEventConnection.h>
 
 #include "SensorInterface.h"
+#include "SensorList.h"
 
 #if __clang__
 // Clang warns about SensorEventConnection::dump hiding BBinder::dump. The cause isn't fixable
@@ -156,18 +157,18 @@
     virtual int isDataInjectionEnabled();
     virtual status_t dump(int fd, const Vector<String16>& args);
 
-
     static int getNumEventsForSensorType(int sensor_event_type);
     String8 getSensorName(int handle) const;
     bool isVirtualSensor(int handle) const;
     SensorInterface* getSensorInterfaceFromHandle(int handle) const;
-    Sensor getSensorFromHandle(int handle) const;
+    const Sensor& getSensorFromHandle(int handle) const;
     bool isWakeUpSensor(int type) const;
     void recordLastValueLocked(sensors_event_t const* buffer, size_t count);
     static void sortEventBuffer(sensors_event_t* buffer, size_t count);
-    Sensor registerSensor(SensorInterface* sensor);
-    Sensor registerVirtualSensor(SensorInterface* sensor);
-    Sensor registerDynamicSensor(SensorInterface* sensor);
+    const Sensor& registerSensor(SensorInterface* sensor,
+                                 bool isDebug = false, bool isVirtual = false);
+    const Sensor& registerVirtualSensor(SensorInterface* sensor, bool isDebug = false);
+    const Sensor& registerDynamicSensor(SensorInterface* sensor, bool isDebug = false);
     bool unregisterDynamicSensor(int handle);
     status_t cleanupWithoutDisable(const sp<SensorEventConnection>& connection, int handle);
     status_t cleanupWithoutDisableLocked(const sp<SensorEventConnection>& connection, int handle);
@@ -182,7 +183,6 @@
     void checkWakeLockStateLocked();
     bool isWakeLockAcquired();
     bool isWakeUpSensorEvent(const sensors_event_t& event) const;
-    bool isNewHandle(int handle);
 
     sp<Looper> getLooper() const;
 
@@ -211,14 +211,7 @@
     status_t resetToNormalMode();
     status_t resetToNormalModeLocked();
 
-    // lists and maps
-    Vector<Sensor> mSensorList;
-    Vector<Sensor> mUserSensorListDebug;
-    Vector<Sensor> mUserSensorList;
-    Vector<Sensor> mDynamicSensorList;
-    DefaultKeyedVector<int, SensorInterface*> mSensorMap;
-    Vector<SensorInterface *> mVirtualSensorList;
-    Vector<int> mUsedHandleList;
+    SensorServiceUtil::SensorList mSensors;
     status_t mInitCheck;
 
     // Socket buffersize used to initialize BitTube. This size depends on whether batching is
@@ -233,6 +226,7 @@
     bool mWakeLockAcquired;
     sensors_event_t *mSensorEventBuffer, *mSensorEventScratch;
     SensorEventConnection const **mMapFlushEventsToConnections;
+    KeyedVector<int32_t, MostRecentEventLogger*> mLastEventSeen;
     Mode mCurrentOperatingMode;
 
     // This packagaName is set when SensorService is in RESTRICTED or DATA_INJECTION mode. Only
@@ -241,9 +235,6 @@
     // sensors.
     String8 mWhiteListedPackage;
 
-    // The size of this vector is constant, only the items are mutable
-    KeyedVector<int32_t, MostRecentEventLogger *> mLastEventSeen;
-
     int mNextSensorRegIndex;
     Vector<SensorRegistrationInfo> mLastNSensorRegistrations;
 };