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