Home | History | Annotate | Download | only in sensorservice
      1 /*
      2  * Copyright (C) 2010 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 #include <binder/ActivityManager.h>
     17 #include <binder/AppOpsManager.h>
     18 #include <binder/BinderService.h>
     19 #include <binder/IServiceManager.h>
     20 #include <binder/PermissionCache.h>
     21 #include <binder/PermissionController.h>
     22 #include <cutils/ashmem.h>
     23 #include <cutils/misc.h>
     24 #include <cutils/properties.h>
     25 #include <hardware/sensors.h>
     26 #include <hardware_legacy/power.h>
     27 #include <log/log.h>
     28 #include <openssl/digest.h>
     29 #include <openssl/hmac.h>
     30 #include <openssl/rand.h>
     31 #include <sensor/SensorEventQueue.h>
     32 #include <utils/SystemClock.h>
     33 
     34 #include "BatteryService.h"
     35 #include "CorrectedGyroSensor.h"
     36 #include "GravitySensor.h"
     37 #include "LinearAccelerationSensor.h"
     38 #include "OrientationSensor.h"
     39 #include "RotationVectorSensor.h"
     40 #include "SensorFusion.h"
     41 #include "SensorInterface.h"
     42 
     43 #include "SensorService.h"
     44 #include "SensorDirectConnection.h"
     45 #include "SensorEventAckReceiver.h"
     46 #include "SensorEventConnection.h"
     47 #include "SensorRecord.h"
     48 #include "SensorRegistrationInfo.h"
     49 
     50 #include <inttypes.h>
     51 #include <math.h>
     52 #include <sched.h>
     53 #include <stdint.h>
     54 #include <sys/socket.h>
     55 #include <sys/stat.h>
     56 #include <sys/types.h>
     57 #include <unistd.h>
     58 
     59 #include <private/android_filesystem_config.h>
     60 
     61 namespace android {
     62 // ---------------------------------------------------------------------------
     63 
     64 /*
     65  * Notes:
     66  *
     67  * - what about a gyro-corrected magnetic-field sensor?
     68  * - run mag sensor from time to time to force calibration
     69  * - gravity sensor length is wrong (=> drift in linear-acc sensor)
     70  *
     71  */
     72 
     73 const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
     74 uint8_t SensorService::sHmacGlobalKey[128] = {};
     75 bool SensorService::sHmacGlobalKeyIsValid = false;
     76 
     77 #define SENSOR_SERVICE_DIR "/data/system/sensor_service"
     78 #define SENSOR_SERVICE_HMAC_KEY_FILE  SENSOR_SERVICE_DIR "/hmac_key"
     79 #define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
     80 
     81 // Permissions.
     82 static const String16 sDumpPermission("android.permission.DUMP");
     83 static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
     84 static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
     85 
     86 SensorService::SensorService()
     87     : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
     88       mWakeLockAcquired(false) {
     89     mUidPolicy = new UidPolicy(this);
     90 }
     91 
     92 bool SensorService::initializeHmacKey() {
     93     int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
     94     if (fd != -1) {
     95         int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
     96         close(fd);
     97         if (result == sizeof(sHmacGlobalKey)) {
     98             return true;
     99         }
    100         ALOGW("Unable to read HMAC key; generating new one.");
    101     }
    102 
    103     if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
    104         ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
    105         return false;
    106     }
    107 
    108     // We need to make sure this is only readable to us.
    109     bool wroteKey = false;
    110     mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
    111     fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
    112               S_IRUSR|S_IWUSR);
    113     if (fd != -1) {
    114         int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
    115         close(fd);
    116         wroteKey = (result == sizeof(sHmacGlobalKey));
    117     }
    118     if (wroteKey) {
    119         ALOGI("Generated new HMAC key.");
    120     } else {
    121         ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
    122               "after reboot.");
    123     }
    124     // Even if we failed to write the key we return true, because we did
    125     // initialize the HMAC key.
    126     return true;
    127 }
    128 
    129 // Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
    130 void SensorService::enableSchedFifoMode() {
    131     struct sched_param param = {0};
    132     param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
    133     if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
    134         ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
    135     }
    136 }
    137 
    138 void SensorService::onFirstRef() {
    139     ALOGD("nuSensorService starting...");
    140     SensorDevice& dev(SensorDevice::getInstance());
    141 
    142     sHmacGlobalKeyIsValid = initializeHmacKey();
    143 
    144     if (dev.initCheck() == NO_ERROR) {
    145         sensor_t const* list;
    146         ssize_t count = dev.getSensorList(&list);
    147         if (count > 0) {
    148             ssize_t orientationIndex = -1;
    149             bool hasGyro = false, hasAccel = false, hasMag = false;
    150             uint32_t virtualSensorsNeeds =
    151                     (1<<SENSOR_TYPE_GRAVITY) |
    152                     (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
    153                     (1<<SENSOR_TYPE_ROTATION_VECTOR) |
    154                     (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
    155                     (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
    156 
    157             for (ssize_t i=0 ; i<count ; i++) {
    158                 bool useThisSensor=true;
    159 
    160                 switch (list[i].type) {
    161                     case SENSOR_TYPE_ACCELEROMETER:
    162                         hasAccel = true;
    163                         break;
    164                     case SENSOR_TYPE_MAGNETIC_FIELD:
    165                         hasMag = true;
    166                         break;
    167                     case SENSOR_TYPE_ORIENTATION:
    168                         orientationIndex = i;
    169                         break;
    170                     case SENSOR_TYPE_GYROSCOPE:
    171                     case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
    172                         hasGyro = true;
    173                         break;
    174                     case SENSOR_TYPE_GRAVITY:
    175                     case SENSOR_TYPE_LINEAR_ACCELERATION:
    176                     case SENSOR_TYPE_ROTATION_VECTOR:
    177                     case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
    178                     case SENSOR_TYPE_GAME_ROTATION_VECTOR:
    179                         if (IGNORE_HARDWARE_FUSION) {
    180                             useThisSensor = false;
    181                         } else {
    182                             virtualSensorsNeeds &= ~(1<<list[i].type);
    183                         }
    184                         break;
    185                 }
    186                 if (useThisSensor) {
    187                     registerSensor( new HardwareSensor(list[i]) );
    188                 }
    189             }
    190 
    191             // it's safe to instantiate the SensorFusion object here
    192             // (it wants to be instantiated after h/w sensors have been
    193             // registered)
    194             SensorFusion::getInstance();
    195 
    196             if (hasGyro && hasAccel && hasMag) {
    197                 // Add Android virtual sensors if they're not already
    198                 // available in the HAL
    199                 bool needRotationVector =
    200                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
    201 
    202                 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
    203                 registerSensor(new OrientationSensor(), !needRotationVector, true);
    204 
    205                 bool needLinearAcceleration =
    206                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
    207 
    208                 registerSensor(new LinearAccelerationSensor(list, count),
    209                                !needLinearAcceleration, true);
    210 
    211                 // virtual debugging sensors are not for user
    212                 registerSensor( new CorrectedGyroSensor(list, count), true, true);
    213                 registerSensor( new GyroDriftSensor(), true, true);
    214             }
    215 
    216             if (hasAccel && hasGyro) {
    217                 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
    218                 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
    219 
    220                 bool needGameRotationVector =
    221                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
    222                 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
    223             }
    224 
    225             if (hasAccel && hasMag) {
    226                 bool needGeoMagRotationVector =
    227                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
    228                 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
    229             }
    230 
    231             // Check if the device really supports batching by looking at the FIFO event
    232             // counts for each sensor.
    233             bool batchingSupported = false;
    234             mSensors.forEachSensor(
    235                     [&batchingSupported] (const Sensor& s) -> bool {
    236                         if (s.getFifoMaxEventCount() > 0) {
    237                             batchingSupported = true;
    238                         }
    239                         return !batchingSupported;
    240                     });
    241 
    242             if (batchingSupported) {
    243                 // Increase socket buffer size to a max of 100 KB for batching capabilities.
    244                 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
    245             } else {
    246                 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
    247             }
    248 
    249             // Compare the socketBufferSize value against the system limits and limit
    250             // it to maxSystemSocketBufferSize if necessary.
    251             FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
    252             char line[128];
    253             if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
    254                 line[sizeof(line) - 1] = '\0';
    255                 size_t maxSystemSocketBufferSize;
    256                 sscanf(line, "%zu", &maxSystemSocketBufferSize);
    257                 if (mSocketBufferSize > maxSystemSocketBufferSize) {
    258                     mSocketBufferSize = maxSystemSocketBufferSize;
    259                 }
    260             }
    261             if (fp) {
    262                 fclose(fp);
    263             }
    264 
    265             mWakeLockAcquired = false;
    266             mLooper = new Looper(false);
    267             const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
    268             mSensorEventBuffer = new sensors_event_t[minBufferSize];
    269             mSensorEventScratch = new sensors_event_t[minBufferSize];
    270             mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
    271             mCurrentOperatingMode = NORMAL;
    272 
    273             mNextSensorRegIndex = 0;
    274             for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
    275                 mLastNSensorRegistrations.push();
    276             }
    277 
    278             mInitCheck = NO_ERROR;
    279             mAckReceiver = new SensorEventAckReceiver(this);
    280             mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
    281             run("SensorService", PRIORITY_URGENT_DISPLAY);
    282 
    283             // priority can only be changed after run
    284             enableSchedFifoMode();
    285 
    286             // Start watching UID changes to apply policy.
    287             mUidPolicy->registerSelf();
    288         }
    289     }
    290 }
    291 
    292 void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
    293     SortedVector< sp<SensorEventConnection> > activeConnections;
    294     populateActiveConnections(&activeConnections);
    295     {
    296         Mutex::Autolock _l(mLock);
    297         for (size_t i = 0 ; i < activeConnections.size(); i++) {
    298             if (activeConnections[i] != 0 && activeConnections[i]->getUid() == uid) {
    299                 activeConnections[i]->setSensorAccess(hasAccess);
    300             }
    301         }
    302     }
    303 }
    304 
    305 const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
    306     int handle = s->getSensor().getHandle();
    307     int type = s->getSensor().getType();
    308     if (mSensors.add(handle, s, isDebug, isVirtual)){
    309         mRecentEvent.emplace(handle, new RecentEventLogger(type));
    310         return s->getSensor();
    311     } else {
    312         return mSensors.getNonSensor();
    313     }
    314 }
    315 
    316 const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
    317     return registerSensor(s, isDebug);
    318 }
    319 
    320 bool SensorService::unregisterDynamicSensorLocked(int handle) {
    321     bool ret = mSensors.remove(handle);
    322 
    323     const auto i = mRecentEvent.find(handle);
    324     if (i != mRecentEvent.end()) {
    325         delete i->second;
    326         mRecentEvent.erase(i);
    327     }
    328     return ret;
    329 }
    330 
    331 const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
    332     return registerSensor(s, isDebug, true);
    333 }
    334 
    335 SensorService::~SensorService() {
    336     for (auto && entry : mRecentEvent) {
    337         delete entry.second;
    338     }
    339     mUidPolicy->unregisterSelf();
    340 }
    341 
    342 status_t SensorService::dump(int fd, const Vector<String16>& args) {
    343     String8 result;
    344     if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
    345         result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
    346                 IPCThreadState::self()->getCallingPid(),
    347                 IPCThreadState::self()->getCallingUid());
    348     } else {
    349         bool privileged = IPCThreadState::self()->getCallingUid() == 0;
    350         if (args.size() > 2) {
    351            return INVALID_OPERATION;
    352         }
    353         Mutex::Autolock _l(mLock);
    354         SensorDevice& dev(SensorDevice::getInstance());
    355         if (args.size() == 2 && args[0] == String16("restrict")) {
    356             // If already in restricted mode. Ignore.
    357             if (mCurrentOperatingMode == RESTRICTED) {
    358                 return status_t(NO_ERROR);
    359             }
    360             // If in any mode other than normal, ignore.
    361             if (mCurrentOperatingMode != NORMAL) {
    362                 return INVALID_OPERATION;
    363             }
    364 
    365             mCurrentOperatingMode = RESTRICTED;
    366             // temporarily stop all sensor direct report
    367             for (auto &i : mDirectConnections) {
    368                 sp<SensorDirectConnection> connection(i.promote());
    369                 if (connection != nullptr) {
    370                     connection->stopAll(true /* backupRecord */);
    371                 }
    372             }
    373 
    374             dev.disableAllSensors();
    375             // Clear all pending flush connections for all active sensors. If one of the active
    376             // connections has called flush() and the underlying sensor has been disabled before a
    377             // flush complete event is returned, we need to remove the connection from this queue.
    378             for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
    379                 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
    380             }
    381             mWhiteListedPackage.setTo(String8(args[1]));
    382             return status_t(NO_ERROR);
    383         } else if (args.size() == 1 && args[0] == String16("enable")) {
    384             // If currently in restricted mode, reset back to NORMAL mode else ignore.
    385             if (mCurrentOperatingMode == RESTRICTED) {
    386                 mCurrentOperatingMode = NORMAL;
    387                 dev.enableAllSensors();
    388                 // recover all sensor direct report
    389                 for (auto &i : mDirectConnections) {
    390                     sp<SensorDirectConnection> connection(i.promote());
    391                     if (connection != nullptr) {
    392                         connection->recoverAll();
    393                     }
    394                 }
    395             }
    396             if (mCurrentOperatingMode == DATA_INJECTION) {
    397                resetToNormalModeLocked();
    398             }
    399             mWhiteListedPackage.clear();
    400             return status_t(NO_ERROR);
    401         } else if (args.size() == 2 && args[0] == String16("data_injection")) {
    402             if (mCurrentOperatingMode == NORMAL) {
    403                 dev.disableAllSensors();
    404                 status_t err = dev.setMode(DATA_INJECTION);
    405                 if (err == NO_ERROR) {
    406                     mCurrentOperatingMode = DATA_INJECTION;
    407                 } else {
    408                     // Re-enable sensors.
    409                     dev.enableAllSensors();
    410                 }
    411                 mWhiteListedPackage.setTo(String8(args[1]));
    412                 return NO_ERROR;
    413             } else if (mCurrentOperatingMode == DATA_INJECTION) {
    414                 // Already in DATA_INJECTION mode. Treat this as a no_op.
    415                 return NO_ERROR;
    416             } else {
    417                 // Transition to data injection mode supported only from NORMAL mode.
    418                 return INVALID_OPERATION;
    419             }
    420         } else if (!mSensors.hasAnySensor()) {
    421             result.append("No Sensors on the device\n");
    422             result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
    423         } else {
    424             // Default dump the sensor list and debugging information.
    425             //
    426             result.append("Sensor Device:\n");
    427             result.append(SensorDevice::getInstance().dump().c_str());
    428 
    429             result.append("Sensor List:\n");
    430             result.append(mSensors.dump().c_str());
    431 
    432             result.append("Fusion States:\n");
    433             SensorFusion::getInstance().dump(result);
    434 
    435             result.append("Recent Sensor events:\n");
    436             for (auto&& i : mRecentEvent) {
    437                 sp<SensorInterface> s = mSensors.getInterface(i.first);
    438                 if (!i.second->isEmpty()) {
    439                     if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
    440                         i.second->setFormat("normal");
    441                     } else {
    442                         i.second->setFormat("mask_data");
    443                     }
    444                     // if there is events and sensor does not need special permission.
    445                     result.appendFormat("%s: ", s->getSensor().getName().string());
    446                     result.append(i.second->dump().c_str());
    447                 }
    448             }
    449 
    450             result.append("Active sensors:\n");
    451             for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
    452                 int handle = mActiveSensors.keyAt(i);
    453                 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
    454                         getSensorName(handle).string(),
    455                         handle,
    456                         mActiveSensors.valueAt(i)->getNumConnections());
    457             }
    458 
    459             result.appendFormat("Socket Buffer size = %zd events\n",
    460                                 mSocketBufferSize/sizeof(sensors_event_t));
    461             result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
    462                     "not held");
    463             result.appendFormat("Mode :");
    464             switch(mCurrentOperatingMode) {
    465                case NORMAL:
    466                    result.appendFormat(" NORMAL\n");
    467                    break;
    468                case RESTRICTED:
    469                    result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
    470                    break;
    471                case DATA_INJECTION:
    472                    result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
    473             }
    474 
    475             result.appendFormat("%zd active connections\n", mActiveConnections.size());
    476             for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
    477                 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
    478                 if (connection != 0) {
    479                     result.appendFormat("Connection Number: %zu \n", i);
    480                     connection->dump(result);
    481                 }
    482             }
    483 
    484             result.appendFormat("%zd direct connections\n", mDirectConnections.size());
    485             for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
    486                 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
    487                 if (connection != nullptr) {
    488                     result.appendFormat("Direct connection %zu:\n", i);
    489                     connection->dump(result);
    490                 }
    491             }
    492 
    493             result.appendFormat("Previous Registrations:\n");
    494             // Log in the reverse chronological order.
    495             int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
    496                 SENSOR_REGISTRATIONS_BUF_SIZE;
    497             const int startIndex = currentIndex;
    498             do {
    499                 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
    500                 if (SensorRegistrationInfo::isSentinel(reg_info)) {
    501                     // Ignore sentinel, proceed to next item.
    502                     currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
    503                         SENSOR_REGISTRATIONS_BUF_SIZE;
    504                     continue;
    505                 }
    506                 result.appendFormat("%s\n", reg_info.dump().c_str());
    507                 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
    508                         SENSOR_REGISTRATIONS_BUF_SIZE;
    509             } while(startIndex != currentIndex);
    510         }
    511     }
    512     write(fd, result.string(), result.size());
    513     return NO_ERROR;
    514 }
    515 
    516 // NOTE: This is a remote API - make sure all args are validated
    517 status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
    518     if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
    519         return PERMISSION_DENIED;
    520     }
    521     if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
    522         return BAD_VALUE;
    523     }
    524     if (args.size() == 3 && args[0] == String16("set-uid-state")) {
    525         return handleSetUidState(args, err);
    526     } else if (args.size() == 2 && args[0] == String16("reset-uid-state")) {
    527         return handleResetUidState(args, err);
    528     } else if (args.size() == 2 && args[0] == String16("get-uid-state")) {
    529         return handleGetUidState(args, out, err);
    530     } else if (args.size() == 1 && args[0] == String16("help")) {
    531         printHelp(out);
    532         return NO_ERROR;
    533     }
    534     printHelp(err);
    535     return BAD_VALUE;
    536 }
    537 
    538 status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
    539     PermissionController pc;
    540     int uid = pc.getPackageUid(args[1], 0);
    541     if (uid <= 0) {
    542         ALOGE("Unknown package: '%s'", String8(args[1]).string());
    543         dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
    544         return BAD_VALUE;
    545     }
    546     bool active = false;
    547     if (args[2] == String16("active")) {
    548         active = true;
    549     } else if ((args[2] != String16("idle"))) {
    550         ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
    551         return BAD_VALUE;
    552     }
    553     mUidPolicy->addOverrideUid(uid, active);
    554     return NO_ERROR;
    555 }
    556 
    557 status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
    558     PermissionController pc;
    559     int uid = pc.getPackageUid(args[1], 0);
    560     if (uid < 0) {
    561         ALOGE("Unknown package: '%s'", String8(args[1]).string());
    562         dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
    563         return BAD_VALUE;
    564     }
    565     mUidPolicy->removeOverrideUid(uid);
    566     return NO_ERROR;
    567 }
    568 
    569 status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
    570     PermissionController pc;
    571     int uid = pc.getPackageUid(args[1], 0);
    572     if (uid < 0) {
    573         ALOGE("Unknown package: '%s'", String8(args[1]).string());
    574         dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
    575         return BAD_VALUE;
    576     }
    577     if (mUidPolicy->isUidActive(uid)) {
    578         return dprintf(out, "active\n");
    579     } else {
    580         return dprintf(out, "idle\n");
    581     }
    582 }
    583 
    584 status_t SensorService::printHelp(int out) {
    585     return dprintf(out, "Sensor service commands:\n"
    586         "  get-uid-state <PACKAGE> gets the uid state\n"
    587         "  set-uid-state <PACKAGE> <active|idle> overrides the uid state\n"
    588         "  reset-uid-state <PACKAGE> clears the uid state override\n"
    589         "  help print this message\n");
    590 }
    591 
    592 //TODO: move to SensorEventConnection later
    593 void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
    594         sensors_event_t const* buffer, const int count) {
    595     for (int i=0 ; i<count ; i++) {
    596         int handle = buffer[i].sensor;
    597         if (buffer[i].type == SENSOR_TYPE_META_DATA) {
    598             handle = buffer[i].meta_data.sensor;
    599         }
    600         if (connection->hasSensor(handle)) {
    601             sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
    602             // If this buffer has an event from a one_shot sensor and this connection is registered
    603             // for this particular one_shot sensor, try cleaning up the connection.
    604             if (si != nullptr &&
    605                 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
    606                 si->autoDisable(connection.get(), handle);
    607                 cleanupWithoutDisableLocked(connection, handle);
    608             }
    609 
    610         }
    611    }
    612 }
    613 
    614 bool SensorService::threadLoop() {
    615     ALOGD("nuSensorService thread starting...");
    616 
    617     // each virtual sensor could generate an event per "real" event, that's why we need to size
    618     // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.  in practice, this is too
    619     // aggressive, but guaranteed to be enough.
    620     const size_t vcount = mSensors.getVirtualSensors().size();
    621     const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
    622     const size_t numEventMax = minBufferSize / (1 + vcount);
    623 
    624     SensorDevice& device(SensorDevice::getInstance());
    625 
    626     const int halVersion = device.getHalDeviceVersion();
    627     do {
    628         ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
    629         if (count < 0) {
    630             ALOGE("sensor poll failed (%s)", strerror(-count));
    631             break;
    632         }
    633 
    634         // Reset sensors_event_t.flags to zero for all events in the buffer.
    635         for (int i = 0; i < count; i++) {
    636              mSensorEventBuffer[i].flags = 0;
    637         }
    638 
    639         // Make a copy of the connection vector as some connections may be removed during the course
    640         // of this loop (especially when one-shot sensor events are present in the sensor_event
    641         // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
    642         // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
    643         // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
    644         // strongPointers to a vector before the lock is acquired.
    645         SortedVector< sp<SensorEventConnection> > activeConnections;
    646         populateActiveConnections(&activeConnections);
    647 
    648         Mutex::Autolock _l(mLock);
    649         // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
    650         // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
    651         // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
    652         // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
    653         // releasing the wakelock.
    654         bool bufferHasWakeUpEvent = false;
    655         for (int i = 0; i < count; i++) {
    656             if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
    657                 bufferHasWakeUpEvent = true;
    658                 break;
    659             }
    660         }
    661 
    662         if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
    663             setWakeLockAcquiredLocked(true);
    664         }
    665         recordLastValueLocked(mSensorEventBuffer, count);
    666 
    667         // handle virtual sensors
    668         if (count && vcount) {
    669             sensors_event_t const * const event = mSensorEventBuffer;
    670             if (!mActiveVirtualSensors.empty()) {
    671                 size_t k = 0;
    672                 SensorFusion& fusion(SensorFusion::getInstance());
    673                 if (fusion.isEnabled()) {
    674                     for (size_t i=0 ; i<size_t(count) ; i++) {
    675                         fusion.process(event[i]);
    676                     }
    677                 }
    678                 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
    679                     for (int handle : mActiveVirtualSensors) {
    680                         if (count + k >= minBufferSize) {
    681                             ALOGE("buffer too small to hold all events: "
    682                                     "count=%zd, k=%zu, size=%zu",
    683                                     count, k, minBufferSize);
    684                             break;
    685                         }
    686                         sensors_event_t out;
    687                         sp<SensorInterface> si = mSensors.getInterface(handle);
    688                         if (si == nullptr) {
    689                             ALOGE("handle %d is not an valid virtual sensor", handle);
    690                             continue;
    691                         }
    692 
    693                         if (si->process(&out, event[i])) {
    694                             mSensorEventBuffer[count + k] = out;
    695                             k++;
    696                         }
    697                     }
    698                 }
    699                 if (k) {
    700                     // record the last synthesized values
    701                     recordLastValueLocked(&mSensorEventBuffer[count], k);
    702                     count += k;
    703                     // sort the buffer by time-stamps
    704                     sortEventBuffer(mSensorEventBuffer, count);
    705                 }
    706             }
    707         }
    708 
    709         // handle backward compatibility for RotationVector sensor
    710         if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
    711             for (int i = 0; i < count; i++) {
    712                 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
    713                     // All the 4 components of the quaternion should be available
    714                     // No heading accuracy. Set it to -1
    715                     mSensorEventBuffer[i].data[4] = -1;
    716                 }
    717             }
    718         }
    719 
    720         for (int i = 0; i < count; ++i) {
    721             // Map flush_complete_events in the buffer to SensorEventConnections which called flush
    722             // on the hardware sensor. mapFlushEventsToConnections[i] will be the
    723             // SensorEventConnection mapped to the corresponding flush_complete_event in
    724             // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
    725             mMapFlushEventsToConnections[i] = NULL;
    726             if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
    727                 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
    728                 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
    729                 if (rec != NULL) {
    730                     mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
    731                     rec->removeFirstPendingFlushConnection();
    732                 }
    733             }
    734 
    735             // handle dynamic sensor meta events, process registration and unregistration of dynamic
    736             // sensor based on content of event.
    737             if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
    738                 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
    739                     int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
    740                     const sensor_t& dynamicSensor =
    741                             *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
    742                     ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
    743                           handle, dynamicSensor.type, dynamicSensor.name);
    744 
    745                     if (mSensors.isNewHandle(handle)) {
    746                         const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
    747                         sensor_t s = dynamicSensor;
    748                         // make sure the dynamic sensor flag is set
    749                         s.flags |= DYNAMIC_SENSOR_MASK;
    750                         // force the handle to be consistent
    751                         s.handle = handle;
    752 
    753                         SensorInterface *si = new HardwareSensor(s, uuid);
    754 
    755                         // This will release hold on dynamic sensor meta, so it should be called
    756                         // after Sensor object is created.
    757                         device.handleDynamicSensorConnection(handle, true /*connected*/);
    758                         registerDynamicSensorLocked(si);
    759                     } else {
    760                         ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
    761                     }
    762                 } else {
    763                     int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
    764                     ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
    765 
    766                     device.handleDynamicSensorConnection(handle, false /*connected*/);
    767                     if (!unregisterDynamicSensorLocked(handle)) {
    768                         ALOGE("Dynamic sensor release error.");
    769                     }
    770 
    771                     size_t numConnections = activeConnections.size();
    772                     for (size_t i=0 ; i < numConnections; ++i) {
    773                         if (activeConnections[i] != NULL) {
    774                             activeConnections[i]->removeSensor(handle);
    775                         }
    776                     }
    777                 }
    778             }
    779         }
    780 
    781         // Send our events to clients. Check the state of wake lock for each client and release the
    782         // lock if none of the clients need it.
    783         bool needsWakeLock = false;
    784         size_t numConnections = activeConnections.size();
    785         for (size_t i=0 ; i < numConnections; ++i) {
    786             if (activeConnections[i] != 0) {
    787                 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
    788                         mMapFlushEventsToConnections);
    789                 needsWakeLock |= activeConnections[i]->needsWakeLock();
    790                 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
    791                 // Early check for one-shot sensors.
    792                 if (activeConnections[i]->hasOneShotSensors()) {
    793                     cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
    794                             count);
    795                 }
    796             }
    797         }
    798 
    799         if (mWakeLockAcquired && !needsWakeLock) {
    800             setWakeLockAcquiredLocked(false);
    801         }
    802     } while (!Thread::exitPending());
    803 
    804     ALOGW("Exiting SensorService::threadLoop => aborting...");
    805     abort();
    806     return false;
    807 }
    808 
    809 sp<Looper> SensorService::getLooper() const {
    810     return mLooper;
    811 }
    812 
    813 void SensorService::resetAllWakeLockRefCounts() {
    814     SortedVector< sp<SensorEventConnection> > activeConnections;
    815     populateActiveConnections(&activeConnections);
    816     {
    817         Mutex::Autolock _l(mLock);
    818         for (size_t i=0 ; i < activeConnections.size(); ++i) {
    819             if (activeConnections[i] != 0) {
    820                 activeConnections[i]->resetWakeLockRefCount();
    821             }
    822         }
    823         setWakeLockAcquiredLocked(false);
    824     }
    825 }
    826 
    827 void SensorService::setWakeLockAcquiredLocked(bool acquire) {
    828     if (acquire) {
    829         if (!mWakeLockAcquired) {
    830             acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
    831             mWakeLockAcquired = true;
    832         }
    833         mLooper->wake();
    834     } else {
    835         if (mWakeLockAcquired) {
    836             release_wake_lock(WAKE_LOCK_NAME);
    837             mWakeLockAcquired = false;
    838         }
    839     }
    840 }
    841 
    842 bool SensorService::isWakeLockAcquired() {
    843     Mutex::Autolock _l(mLock);
    844     return mWakeLockAcquired;
    845 }
    846 
    847 bool SensorService::SensorEventAckReceiver::threadLoop() {
    848     ALOGD("new thread SensorEventAckReceiver");
    849     sp<Looper> looper = mService->getLooper();
    850     do {
    851         bool wakeLockAcquired = mService->isWakeLockAcquired();
    852         int timeout = -1;
    853         if (wakeLockAcquired) timeout = 5000;
    854         int ret = looper->pollOnce(timeout);
    855         if (ret == ALOOPER_POLL_TIMEOUT) {
    856            mService->resetAllWakeLockRefCounts();
    857         }
    858     } while(!Thread::exitPending());
    859     return false;
    860 }
    861 
    862 void SensorService::recordLastValueLocked(
    863         const sensors_event_t* buffer, size_t count) {
    864     for (size_t i = 0; i < count; i++) {
    865         if (buffer[i].type == SENSOR_TYPE_META_DATA ||
    866             buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
    867             buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
    868             continue;
    869         }
    870 
    871         auto logger = mRecentEvent.find(buffer[i].sensor);
    872         if (logger != mRecentEvent.end()) {
    873             logger->second->addEvent(buffer[i]);
    874         }
    875     }
    876 }
    877 
    878 void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
    879     struct compar {
    880         static int cmp(void const* lhs, void const* rhs) {
    881             sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
    882             sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
    883             return l->timestamp - r->timestamp;
    884         }
    885     };
    886     qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
    887 }
    888 
    889 String8 SensorService::getSensorName(int handle) const {
    890     return mSensors.getName(handle);
    891 }
    892 
    893 bool SensorService::isVirtualSensor(int handle) const {
    894     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
    895     return sensor != nullptr && sensor->isVirtual();
    896 }
    897 
    898 bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
    899     int handle = event.sensor;
    900     if (event.type == SENSOR_TYPE_META_DATA) {
    901         handle = event.meta_data.sensor;
    902     }
    903     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
    904     return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
    905 }
    906 
    907 int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
    908     if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
    909         // UUID is not supported for this device.
    910         return 0;
    911     }
    912     if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
    913         // This sensor can be uniquely identified in the system by
    914         // the combination of its type and name.
    915         return -1;
    916     }
    917 
    918     // We have a dynamic sensor.
    919 
    920     if (!sHmacGlobalKeyIsValid) {
    921         // Rather than risk exposing UUIDs, we cripple dynamic sensors.
    922         ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
    923         return 0;
    924     }
    925 
    926     // We want each app author/publisher to get a different ID, so that the
    927     // same dynamic sensor cannot be tracked across apps by multiple
    928     // authors/publishers.  So we use both our UUID and our User ID.
    929     // Note potential confusion:
    930     //     UUID => Universally Unique Identifier.
    931     //     UID  => User Identifier.
    932     // We refrain from using "uid" except as needed by API to try to
    933     // keep this distinction clear.
    934 
    935     auto appUserId = IPCThreadState::self()->getCallingUid();
    936     uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
    937     memcpy(uuidAndApp, &uuid, sizeof(uuid));
    938     memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
    939 
    940     // Now we use our key on our UUID/app combo to get the hash.
    941     uint8_t hash[EVP_MAX_MD_SIZE];
    942     unsigned int hashLen;
    943     if (HMAC(EVP_sha256(),
    944              sHmacGlobalKey, sizeof(sHmacGlobalKey),
    945              uuidAndApp, sizeof(uuidAndApp),
    946              hash, &hashLen) == nullptr) {
    947         // Rather than risk exposing UUIDs, we cripple dynamic sensors.
    948         ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
    949         return 0;
    950     }
    951 
    952     int32_t id = 0;
    953     if (hashLen < sizeof(id)) {
    954         // We never expect this case, but out of paranoia, we handle it.
    955         // Our 'id' length is already quite small, we don't want the
    956         // effective length of it to be even smaller.
    957         // Rather than risk exposing UUIDs, we cripple dynamic sensors.
    958         ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
    959         return 0;
    960     }
    961 
    962     // This is almost certainly less than all of 'hash', but it's as secure
    963     // as we can be with our current 'id' length.
    964     memcpy(&id, hash, sizeof(id));
    965 
    966     // Note at the beginning of the function that we return the values of
    967     // 0 and -1 to represent special cases.  As a result, we can't return
    968     // those as dynamic sensor IDs.  If we happened to hash to one of those
    969     // values, we change 'id' so we report as a dynamic sensor, and not as
    970     // one of those special cases.
    971     if (id == -1) {
    972         id = -2;
    973     } else if (id == 0) {
    974         id = 1;
    975     }
    976     return id;
    977 }
    978 
    979 void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
    980     for (auto &sensor : sensorList) {
    981         int32_t id = getIdFromUuid(sensor.getUuid());
    982         sensor.setId(id);
    983     }
    984 }
    985 
    986 Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
    987     char value[PROPERTY_VALUE_MAX];
    988     property_get("debug.sensors", value, "0");
    989     const Vector<Sensor>& initialSensorList = (atoi(value)) ?
    990             mSensors.getUserDebugSensors() : mSensors.getUserSensors();
    991     Vector<Sensor> accessibleSensorList;
    992     for (size_t i = 0; i < initialSensorList.size(); i++) {
    993         Sensor sensor = initialSensorList[i];
    994         accessibleSensorList.add(sensor);
    995     }
    996     makeUuidsIntoIdsForSensorList(accessibleSensorList);
    997     return accessibleSensorList;
    998 }
    999 
   1000 Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
   1001     Vector<Sensor> accessibleSensorList;
   1002     mSensors.forEachSensor(
   1003             [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
   1004                 if (sensor.isDynamicSensor()) {
   1005                     if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
   1006                         accessibleSensorList.add(sensor);
   1007                     } else {
   1008                         ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
   1009                               sensor.getName().string(),
   1010                               sensor.getRequiredPermission().string(),
   1011                               sensor.getRequiredAppOp());
   1012                     }
   1013                 }
   1014                 return true;
   1015             });
   1016     makeUuidsIntoIdsForSensorList(accessibleSensorList);
   1017     return accessibleSensorList;
   1018 }
   1019 
   1020 sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
   1021         int requestedMode, const String16& opPackageName) {
   1022     // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
   1023     if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
   1024         return NULL;
   1025     }
   1026 
   1027     Mutex::Autolock _l(mLock);
   1028     // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
   1029     // operating in DI mode.
   1030     if (requestedMode == DATA_INJECTION) {
   1031         if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
   1032         if (!isWhiteListedPackage(packageName)) return NULL;
   1033     }
   1034 
   1035     uid_t uid = IPCThreadState::self()->getCallingUid();
   1036     pid_t pid = IPCThreadState::self()->getCallingPid();
   1037 
   1038     String8 connPackageName =
   1039             (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
   1040     String16 connOpPackageName =
   1041             (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
   1042     bool hasSensorAccess = mUidPolicy->isUidActive(uid);
   1043     sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
   1044             requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
   1045     if (requestedMode == DATA_INJECTION) {
   1046         if (mActiveConnections.indexOf(result) < 0) {
   1047             mActiveConnections.add(result);
   1048         }
   1049         // Add the associated file descriptor to the Looper for polling whenever there is data to
   1050         // be injected.
   1051         result->updateLooperRegistration(mLooper);
   1052     }
   1053     return result;
   1054 }
   1055 
   1056 int SensorService::isDataInjectionEnabled() {
   1057     Mutex::Autolock _l(mLock);
   1058     return (mCurrentOperatingMode == DATA_INJECTION);
   1059 }
   1060 
   1061 sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
   1062         const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
   1063         const native_handle *resource) {
   1064     Mutex::Autolock _l(mLock);
   1065 
   1066     struct sensors_direct_mem_t mem = {
   1067         .type = type,
   1068         .format = format,
   1069         .size = size,
   1070         .handle = resource,
   1071     };
   1072     uid_t uid = IPCThreadState::self()->getCallingUid();
   1073 
   1074     if (mem.handle == nullptr) {
   1075         ALOGE("Failed to clone resource handle");
   1076         return nullptr;
   1077     }
   1078 
   1079     // check format
   1080     if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
   1081         ALOGE("Direct channel format %d is unsupported!", format);
   1082         return nullptr;
   1083     }
   1084 
   1085     // check for duplication
   1086     for (auto &i : mDirectConnections) {
   1087         sp<SensorDirectConnection> connection(i.promote());
   1088         if (connection != nullptr && connection->isEquivalent(&mem)) {
   1089             ALOGE("Duplicate create channel request for the same share memory");
   1090             return nullptr;
   1091         }
   1092     }
   1093 
   1094     // check specific to memory type
   1095     switch(type) {
   1096         case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
   1097             if (resource->numFds < 1) {
   1098                 ALOGE("Ashmem direct channel requires a memory region to be supplied");
   1099                 android_errorWriteLog(0x534e4554, "70986337");  // SafetyNet
   1100                 return nullptr;
   1101             }
   1102             int fd = resource->data[0];
   1103             int size2 = ashmem_get_size_region(fd);
   1104             // check size consistency
   1105             if (size2 < static_cast<int64_t>(size)) {
   1106                 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
   1107                       size, size2);
   1108                 return nullptr;
   1109             }
   1110             break;
   1111         }
   1112         case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
   1113             // no specific checks for gralloc
   1114             break;
   1115         default:
   1116             ALOGE("Unknown direct connection memory type %d", type);
   1117             return nullptr;
   1118     }
   1119 
   1120     native_handle_t *clone = native_handle_clone(resource);
   1121     if (!clone) {
   1122         return nullptr;
   1123     }
   1124 
   1125     SensorDirectConnection* conn = nullptr;
   1126     SensorDevice& dev(SensorDevice::getInstance());
   1127     int channelHandle = dev.registerDirectChannel(&mem);
   1128 
   1129     if (channelHandle <= 0) {
   1130         ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
   1131     } else {
   1132         mem.handle = clone;
   1133         conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
   1134     }
   1135 
   1136     if (conn == nullptr) {
   1137         native_handle_close(clone);
   1138         native_handle_delete(clone);
   1139     } else {
   1140         // add to list of direct connections
   1141         // sensor service should never hold pointer or sp of SensorDirectConnection object.
   1142         mDirectConnections.add(wp<SensorDirectConnection>(conn));
   1143     }
   1144     return conn;
   1145 }
   1146 
   1147 int SensorService::setOperationParameter(
   1148             int32_t handle, int32_t type,
   1149             const Vector<float> &floats, const Vector<int32_t> &ints) {
   1150     Mutex::Autolock _l(mLock);
   1151 
   1152     if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
   1153         return PERMISSION_DENIED;
   1154     }
   1155 
   1156     bool isFloat = true;
   1157     bool isCustom = false;
   1158     size_t expectSize = INT32_MAX;
   1159     switch (type) {
   1160         case AINFO_LOCAL_GEOMAGNETIC_FIELD:
   1161             isFloat = true;
   1162             expectSize = 3;
   1163             break;
   1164         case AINFO_LOCAL_GRAVITY:
   1165             isFloat = true;
   1166             expectSize = 1;
   1167             break;
   1168         case AINFO_DOCK_STATE:
   1169         case AINFO_HIGH_PERFORMANCE_MODE:
   1170         case AINFO_MAGNETIC_FIELD_CALIBRATION:
   1171             isFloat = false;
   1172             expectSize = 1;
   1173             break;
   1174         default:
   1175             // CUSTOM events must only contain float data; it may have variable size
   1176             if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
   1177                     ints.size() ||
   1178                     sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
   1179                     handle < 0) {
   1180                 return BAD_VALUE;
   1181             }
   1182             isFloat = true;
   1183             isCustom = true;
   1184             expectSize = floats.size();
   1185             break;
   1186     }
   1187 
   1188     if (!isCustom && handle != -1) {
   1189         return BAD_VALUE;
   1190     }
   1191 
   1192     // three events: first one is begin tag, last one is end tag, the one in the middle
   1193     // is the payload.
   1194     sensors_event_t event[3];
   1195     int64_t timestamp = elapsedRealtimeNano();
   1196     for (sensors_event_t* i = event; i < event + 3; i++) {
   1197         *i = (sensors_event_t) {
   1198             .version = sizeof(sensors_event_t),
   1199             .sensor = handle,
   1200             .type = SENSOR_TYPE_ADDITIONAL_INFO,
   1201             .timestamp = timestamp++,
   1202             .additional_info = (additional_info_event_t) {
   1203                 .serial = 0
   1204             }
   1205         };
   1206     }
   1207 
   1208     event[0].additional_info.type = AINFO_BEGIN;
   1209     event[1].additional_info.type = type;
   1210     event[2].additional_info.type = AINFO_END;
   1211 
   1212     if (isFloat) {
   1213         if (floats.size() != expectSize) {
   1214             return BAD_VALUE;
   1215         }
   1216         for (size_t i = 0; i < expectSize; ++i) {
   1217             event[1].additional_info.data_float[i] = floats[i];
   1218         }
   1219     } else {
   1220         if (ints.size() != expectSize) {
   1221             return BAD_VALUE;
   1222         }
   1223         for (size_t i = 0; i < expectSize; ++i) {
   1224             event[1].additional_info.data_int32[i] = ints[i];
   1225         }
   1226     }
   1227 
   1228     SensorDevice& dev(SensorDevice::getInstance());
   1229     for (sensors_event_t* i = event; i < event + 3; i++) {
   1230         int ret = dev.injectSensorData(i);
   1231         if (ret != NO_ERROR) {
   1232             return ret;
   1233         }
   1234     }
   1235     return NO_ERROR;
   1236 }
   1237 
   1238 status_t SensorService::resetToNormalMode() {
   1239     Mutex::Autolock _l(mLock);
   1240     return resetToNormalModeLocked();
   1241 }
   1242 
   1243 status_t SensorService::resetToNormalModeLocked() {
   1244     SensorDevice& dev(SensorDevice::getInstance());
   1245     status_t err = dev.setMode(NORMAL);
   1246     if (err == NO_ERROR) {
   1247         mCurrentOperatingMode = NORMAL;
   1248         dev.enableAllSensors();
   1249     }
   1250     return err;
   1251 }
   1252 
   1253 void SensorService::cleanupConnection(SensorEventConnection* c) {
   1254     Mutex::Autolock _l(mLock);
   1255     const wp<SensorEventConnection> connection(c);
   1256     size_t size = mActiveSensors.size();
   1257     ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
   1258     for (size_t i=0 ; i<size ; ) {
   1259         int handle = mActiveSensors.keyAt(i);
   1260         if (c->hasSensor(handle)) {
   1261             ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
   1262             sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
   1263             if (sensor != nullptr) {
   1264                 sensor->activate(c, false);
   1265             } else {
   1266                 ALOGE("sensor interface of handle=0x%08x is null!", handle);
   1267             }
   1268             c->removeSensor(handle);
   1269         }
   1270         SensorRecord* rec = mActiveSensors.valueAt(i);
   1271         ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
   1272         ALOGD_IF(DEBUG_CONNECTIONS,
   1273                 "removing connection %p for sensor[%zu].handle=0x%08x",
   1274                 c, i, handle);
   1275 
   1276         if (rec && rec->removeConnection(connection)) {
   1277             ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
   1278             mActiveSensors.removeItemsAt(i, 1);
   1279             mActiveVirtualSensors.erase(handle);
   1280             delete rec;
   1281             size--;
   1282         } else {
   1283             i++;
   1284         }
   1285     }
   1286     c->updateLooperRegistration(mLooper);
   1287     mActiveConnections.remove(connection);
   1288     BatteryService::cleanup(c->getUid());
   1289     if (c->needsWakeLock()) {
   1290         checkWakeLockStateLocked();
   1291     }
   1292 
   1293     SensorDevice& dev(SensorDevice::getInstance());
   1294     dev.notifyConnectionDestroyed(c);
   1295 }
   1296 
   1297 void SensorService::cleanupConnection(SensorDirectConnection* c) {
   1298     Mutex::Autolock _l(mLock);
   1299 
   1300     SensorDevice& dev(SensorDevice::getInstance());
   1301     dev.unregisterDirectChannel(c->getHalChannelHandle());
   1302     mDirectConnections.remove(c);
   1303 }
   1304 
   1305 sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
   1306     return mSensors.getInterface(handle);
   1307 }
   1308 
   1309 status_t SensorService::enable(const sp<SensorEventConnection>& connection,
   1310         int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
   1311         const String16& opPackageName) {
   1312     if (mInitCheck != NO_ERROR)
   1313         return mInitCheck;
   1314 
   1315     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
   1316     if (sensor == nullptr ||
   1317         !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
   1318         return BAD_VALUE;
   1319     }
   1320 
   1321     Mutex::Autolock _l(mLock);
   1322     if (mCurrentOperatingMode != NORMAL
   1323            && !isWhiteListedPackage(connection->getPackageName())) {
   1324         return INVALID_OPERATION;
   1325     }
   1326 
   1327     SensorRecord* rec = mActiveSensors.valueFor(handle);
   1328     if (rec == 0) {
   1329         rec = new SensorRecord(connection);
   1330         mActiveSensors.add(handle, rec);
   1331         if (sensor->isVirtual()) {
   1332             mActiveVirtualSensors.emplace(handle);
   1333         }
   1334     } else {
   1335         if (rec->addConnection(connection)) {
   1336             // this sensor is already activated, but we are adding a connection that uses it.
   1337             // Immediately send down the last known value of the requested sensor if it's not a
   1338             // "continuous" sensor.
   1339             if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
   1340                 // NOTE: The wake_up flag of this event may get set to
   1341                 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
   1342 
   1343                 auto logger = mRecentEvent.find(handle);
   1344                 if (logger != mRecentEvent.end()) {
   1345                     sensors_event_t event;
   1346                     // It is unlikely that this buffer is empty as the sensor is already active.
   1347                     // One possible corner case may be two applications activating an on-change
   1348                     // sensor at the same time.
   1349                     if(logger->second->populateLastEvent(&event)) {
   1350                         event.sensor = handle;
   1351                         if (event.version == sizeof(sensors_event_t)) {
   1352                             if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
   1353                                 setWakeLockAcquiredLocked(true);
   1354                             }
   1355                             connection->sendEvents(&event, 1, NULL);
   1356                             if (!connection->needsWakeLock() && mWakeLockAcquired) {
   1357                                 checkWakeLockStateLocked();
   1358                             }
   1359                         }
   1360                     }
   1361                 }
   1362             }
   1363         }
   1364     }
   1365 
   1366     if (connection->addSensor(handle)) {
   1367         BatteryService::enableSensor(connection->getUid(), handle);
   1368         // the sensor was added (which means it wasn't already there)
   1369         // so, see if this connection becomes active
   1370         if (mActiveConnections.indexOf(connection) < 0) {
   1371             mActiveConnections.add(connection);
   1372         }
   1373     } else {
   1374         ALOGW("sensor %08x already enabled in connection %p (ignoring)",
   1375             handle, connection.get());
   1376     }
   1377 
   1378     // Check maximum delay for the sensor.
   1379     nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
   1380     if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
   1381         samplingPeriodNs = maxDelayNs;
   1382     }
   1383 
   1384     nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
   1385     if (samplingPeriodNs < minDelayNs) {
   1386         samplingPeriodNs = minDelayNs;
   1387     }
   1388 
   1389     ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
   1390                                 "rate=%" PRId64 " timeout== %" PRId64"",
   1391              handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
   1392 
   1393     status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
   1394                                  maxBatchReportLatencyNs);
   1395 
   1396     // Call flush() before calling activate() on the sensor. Wait for a first
   1397     // flush complete event before sending events on this connection. Ignore
   1398     // one-shot sensors which don't support flush(). Ignore on-change sensors
   1399     // to maintain the on-change logic (any on-change events except the initial
   1400     // one should be trigger by a change in value). Also if this sensor isn't
   1401     // already active, don't call flush().
   1402     if (err == NO_ERROR &&
   1403             sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
   1404             rec->getNumConnections() > 1) {
   1405         connection->setFirstFlushPending(handle, true);
   1406         status_t err_flush = sensor->flush(connection.get(), handle);
   1407         // Flush may return error if the underlying h/w sensor uses an older HAL.
   1408         if (err_flush == NO_ERROR) {
   1409             rec->addPendingFlushConnection(connection.get());
   1410         } else {
   1411             connection->setFirstFlushPending(handle, false);
   1412         }
   1413     }
   1414 
   1415     if (err == NO_ERROR) {
   1416         ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
   1417         err = sensor->activate(connection.get(), true);
   1418     }
   1419 
   1420     if (err == NO_ERROR) {
   1421         connection->updateLooperRegistration(mLooper);
   1422 
   1423         mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
   1424                 SensorRegistrationInfo(handle, connection->getPackageName(),
   1425                                        samplingPeriodNs, maxBatchReportLatencyNs, true);
   1426         mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
   1427     }
   1428 
   1429     if (err != NO_ERROR) {
   1430         // batch/activate has failed, reset our state.
   1431         cleanupWithoutDisableLocked(connection, handle);
   1432     }
   1433     return err;
   1434 }
   1435 
   1436 status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
   1437     if (mInitCheck != NO_ERROR)
   1438         return mInitCheck;
   1439 
   1440     Mutex::Autolock _l(mLock);
   1441     status_t err = cleanupWithoutDisableLocked(connection, handle);
   1442     if (err == NO_ERROR) {
   1443         sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
   1444         err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
   1445 
   1446     }
   1447     if (err == NO_ERROR) {
   1448         mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
   1449                 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
   1450         mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
   1451     }
   1452     return err;
   1453 }
   1454 
   1455 status_t SensorService::cleanupWithoutDisable(
   1456         const sp<SensorEventConnection>& connection, int handle) {
   1457     Mutex::Autolock _l(mLock);
   1458     return cleanupWithoutDisableLocked(connection, handle);
   1459 }
   1460 
   1461 status_t SensorService::cleanupWithoutDisableLocked(
   1462         const sp<SensorEventConnection>& connection, int handle) {
   1463     SensorRecord* rec = mActiveSensors.valueFor(handle);
   1464     if (rec) {
   1465         // see if this connection becomes inactive
   1466         if (connection->removeSensor(handle)) {
   1467             BatteryService::disableSensor(connection->getUid(), handle);
   1468         }
   1469         if (connection->hasAnySensor() == false) {
   1470             connection->updateLooperRegistration(mLooper);
   1471             mActiveConnections.remove(connection);
   1472         }
   1473         // see if this sensor becomes inactive
   1474         if (rec->removeConnection(connection)) {
   1475             mActiveSensors.removeItem(handle);
   1476             mActiveVirtualSensors.erase(handle);
   1477             delete rec;
   1478         }
   1479         return NO_ERROR;
   1480     }
   1481     return BAD_VALUE;
   1482 }
   1483 
   1484 status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
   1485         int handle, nsecs_t ns, const String16& opPackageName) {
   1486     if (mInitCheck != NO_ERROR)
   1487         return mInitCheck;
   1488 
   1489     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
   1490     if (sensor == nullptr ||
   1491         !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
   1492         return BAD_VALUE;
   1493     }
   1494 
   1495     if (ns < 0)
   1496         return BAD_VALUE;
   1497 
   1498     nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
   1499     if (ns < minDelayNs) {
   1500         ns = minDelayNs;
   1501     }
   1502 
   1503     return sensor->setDelay(connection.get(), handle, ns);
   1504 }
   1505 
   1506 status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
   1507         const String16& opPackageName) {
   1508     if (mInitCheck != NO_ERROR) return mInitCheck;
   1509     SensorDevice& dev(SensorDevice::getInstance());
   1510     const int halVersion = dev.getHalDeviceVersion();
   1511     status_t err(NO_ERROR);
   1512     Mutex::Autolock _l(mLock);
   1513     // Loop through all sensors for this connection and call flush on each of them.
   1514     for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
   1515         const int handle = connection->mSensorInfo.keyAt(i);
   1516         sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
   1517         if (sensor == nullptr) {
   1518             continue;
   1519         }
   1520         if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
   1521             ALOGE("flush called on a one-shot sensor");
   1522             err = INVALID_OPERATION;
   1523             continue;
   1524         }
   1525         if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
   1526             // For older devices just increment pending flush count which will send a trivial
   1527             // flush complete event.
   1528             connection->incrementPendingFlushCount(handle);
   1529         } else {
   1530             if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
   1531                 err = INVALID_OPERATION;
   1532                 continue;
   1533             }
   1534             status_t err_flush = sensor->flush(connection.get(), handle);
   1535             if (err_flush == NO_ERROR) {
   1536                 SensorRecord* rec = mActiveSensors.valueFor(handle);
   1537                 if (rec != NULL) rec->addPendingFlushConnection(connection);
   1538             }
   1539             err = (err_flush != NO_ERROR) ? err_flush : err;
   1540         }
   1541     }
   1542     return err;
   1543 }
   1544 
   1545 bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
   1546         const String16& opPackageName) {
   1547     const String8& requiredPermission = sensor.getRequiredPermission();
   1548 
   1549     if (requiredPermission.length() <= 0) {
   1550         return true;
   1551     }
   1552 
   1553     bool hasPermission = false;
   1554 
   1555     // Runtime permissions can't use the cache as they may change.
   1556     if (sensor.isRequiredPermissionRuntime()) {
   1557         hasPermission = checkPermission(String16(requiredPermission),
   1558                 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
   1559     } else {
   1560         hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
   1561     }
   1562 
   1563     if (!hasPermission) {
   1564         ALOGE("%s a sensor (%s) without holding its required permission: %s",
   1565                 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
   1566         return false;
   1567     }
   1568 
   1569     const int32_t opCode = sensor.getRequiredAppOp();
   1570     if (opCode >= 0) {
   1571         AppOpsManager appOps;
   1572         if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
   1573                         != AppOpsManager::MODE_ALLOWED) {
   1574             ALOGE("%s a sensor (%s) without enabled required app op: %d",
   1575                     operation, sensor.getName().string(), opCode);
   1576             return false;
   1577         }
   1578     }
   1579 
   1580     return true;
   1581 }
   1582 
   1583 void SensorService::checkWakeLockState() {
   1584     Mutex::Autolock _l(mLock);
   1585     checkWakeLockStateLocked();
   1586 }
   1587 
   1588 void SensorService::checkWakeLockStateLocked() {
   1589     if (!mWakeLockAcquired) {
   1590         return;
   1591     }
   1592     bool releaseLock = true;
   1593     for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
   1594         sp<SensorEventConnection> connection(mActiveConnections[i].promote());
   1595         if (connection != 0) {
   1596             if (connection->needsWakeLock()) {
   1597                 releaseLock = false;
   1598                 break;
   1599             }
   1600         }
   1601     }
   1602     if (releaseLock) {
   1603         setWakeLockAcquiredLocked(false);
   1604     }
   1605 }
   1606 
   1607 void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
   1608     Mutex::Autolock _l(mLock);
   1609     connection->writeToSocketFromCache();
   1610     if (connection->needsWakeLock()) {
   1611         setWakeLockAcquiredLocked(true);
   1612     }
   1613 }
   1614 
   1615 void SensorService::populateActiveConnections(
   1616         SortedVector< sp<SensorEventConnection> >* activeConnections) {
   1617     Mutex::Autolock _l(mLock);
   1618     for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
   1619         sp<SensorEventConnection> connection(mActiveConnections[i].promote());
   1620         if (connection != 0) {
   1621             activeConnections->add(connection);
   1622         }
   1623     }
   1624 }
   1625 
   1626 bool SensorService::isWhiteListedPackage(const String8& packageName) {
   1627     return (packageName.contains(mWhiteListedPackage.string()));
   1628 }
   1629 
   1630 bool SensorService::isOperationRestricted(const String16& opPackageName) {
   1631     Mutex::Autolock _l(mLock);
   1632     if (mCurrentOperatingMode != RESTRICTED) {
   1633         String8 package(opPackageName);
   1634         return !isWhiteListedPackage(package);
   1635     }
   1636     return false;
   1637 }
   1638 
   1639 void SensorService::UidPolicy::registerSelf() {
   1640     ActivityManager am;
   1641     am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
   1642             | ActivityManager::UID_OBSERVER_IDLE
   1643             | ActivityManager::UID_OBSERVER_ACTIVE,
   1644             ActivityManager::PROCESS_STATE_UNKNOWN,
   1645             String16("android"));
   1646 }
   1647 
   1648 void SensorService::UidPolicy::unregisterSelf() {
   1649     ActivityManager am;
   1650     am.unregisterUidObserver(this);
   1651 }
   1652 
   1653 void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
   1654     onUidIdle(uid, disabled);
   1655 }
   1656 
   1657 void SensorService::UidPolicy::onUidActive(uid_t uid) {
   1658     {
   1659         Mutex::Autolock _l(mUidLock);
   1660         mActiveUids.insert(uid);
   1661     }
   1662     sp<SensorService> service = mService.promote();
   1663     if (service != nullptr) {
   1664         service->setSensorAccess(uid, true);
   1665     }
   1666 }
   1667 
   1668 void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
   1669     bool deleted = false;
   1670     {
   1671         Mutex::Autolock _l(mUidLock);
   1672         if (mActiveUids.erase(uid) > 0) {
   1673             deleted = true;
   1674         }
   1675     }
   1676     if (deleted) {
   1677         sp<SensorService> service = mService.promote();
   1678         if (service != nullptr) {
   1679             service->setSensorAccess(uid, false);
   1680         }
   1681     }
   1682 }
   1683 
   1684 void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
   1685     updateOverrideUid(uid, active, true);
   1686 }
   1687 
   1688 void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
   1689     updateOverrideUid(uid, false, false);
   1690 }
   1691 
   1692 void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
   1693     bool wasActive = false;
   1694     bool isActive = false;
   1695     {
   1696         Mutex::Autolock _l(mUidLock);
   1697         wasActive = isUidActiveLocked(uid);
   1698         mOverrideUids.erase(uid);
   1699         if (insert) {
   1700             mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
   1701         }
   1702         isActive = isUidActiveLocked(uid);
   1703     }
   1704     if (wasActive != isActive) {
   1705         sp<SensorService> service = mService.promote();
   1706         if (service != nullptr) {
   1707             service->setSensorAccess(uid, isActive);
   1708         }
   1709     }
   1710 }
   1711 
   1712 bool SensorService::UidPolicy::isUidActive(uid_t uid) {
   1713     // Non-app UIDs are considered always active
   1714     if (uid < FIRST_APPLICATION_UID) {
   1715         return true;
   1716     }
   1717     Mutex::Autolock _l(mUidLock);
   1718     return isUidActiveLocked(uid);
   1719 }
   1720 
   1721 bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
   1722     // Non-app UIDs are considered always active
   1723     if (uid < FIRST_APPLICATION_UID) {
   1724         return true;
   1725     }
   1726     auto it = mOverrideUids.find(uid);
   1727     if (it != mOverrideUids.end()) {
   1728         return it->second;
   1729     }
   1730     return mActiveUids.find(uid) != mActiveUids.end();
   1731 }
   1732 
   1733 }; // namespace android
   1734