• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <aidl/android/hardware/sensors/ISensors.h>
17 #include <android-base/strings.h>
18 #include <android/content/pm/IPackageManagerNative.h>
19 #include <android/util/ProtoOutputStream.h>
20 #include <binder/ActivityManager.h>
21 #include <binder/BinderService.h>
22 #include <binder/IServiceManager.h>
23 #include <binder/PermissionCache.h>
24 #include <binder/PermissionController.h>
25 #include <cutils/ashmem.h>
26 #include <cutils/misc.h>
27 #include <cutils/properties.h>
28 #include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
29 #include <hardware/sensors.h>
30 #include <hardware_legacy/power.h>
31 #include <log/log.h>
32 #include <openssl/digest.h>
33 #include <openssl/hmac.h>
34 #include <openssl/rand.h>
35 #include <sensor/SensorEventQueue.h>
36 #include <sensorprivacy/SensorPrivacyManager.h>
37 #include <utils/SystemClock.h>
38 
39 #include "BatteryService.h"
40 #include "CorrectedGyroSensor.h"
41 #include "GravitySensor.h"
42 #include "LimitedAxesImuSensor.h"
43 #include "LinearAccelerationSensor.h"
44 #include "OrientationSensor.h"
45 #include "RotationVectorSensor.h"
46 #include "SensorFusion.h"
47 #include "SensorInterface.h"
48 
49 #include "SensorService.h"
50 #include "SensorDirectConnection.h"
51 #include "SensorEventAckReceiver.h"
52 #include "SensorEventConnection.h"
53 #include "SensorRecord.h"
54 #include "SensorRegistrationInfo.h"
55 #include "SensorServiceUtils.h"
56 
57 #include <inttypes.h>
58 #include <math.h>
59 #include <sched.h>
60 #include <stdint.h>
61 #include <sys/socket.h>
62 #include <sys/stat.h>
63 #include <sys/types.h>
64 #include <unistd.h>
65 
66 #include <ctime>
67 #include <future>
68 #include <string>
69 
70 #include <private/android_filesystem_config.h>
71 
72 using namespace std::chrono_literals;
73 
74 namespace android {
75 // ---------------------------------------------------------------------------
76 
77 /*
78  * Notes:
79  *
80  * - what about a gyro-corrected magnetic-field sensor?
81  * - run mag sensor from time to time to force calibration
82  * - gravity sensor length is wrong (=> drift in linear-acc sensor)
83  *
84  */
85 
86 const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
87 uint8_t SensorService::sHmacGlobalKey[128] = {};
88 bool SensorService::sHmacGlobalKeyIsValid = false;
89 std::map<String16, int> SensorService::sPackageTargetVersion;
90 Mutex SensorService::sPackageTargetVersionLock;
91 String16 SensorService::sSensorInterfaceDescriptorPrefix =
92         String16("android.frameworks.sensorservice@");
93 AppOpsManager SensorService::sAppOpsManager;
94 std::atomic_uint64_t SensorService::curProxCallbackSeq(0);
95 std::atomic_uint64_t SensorService::completedCallbackSeq(0);
96 
97 #define SENSOR_SERVICE_DIR "/data/system/sensor_service"
98 #define SENSOR_SERVICE_HMAC_KEY_FILE  SENSOR_SERVICE_DIR "/hmac_key"
99 #define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
100 
101 // Permissions.
102 static const String16 sAccessHighSensorSamplingRatePermission(
103         "android.permission.HIGH_SAMPLING_RATE_SENSORS");
104 static const String16 sDumpPermission("android.permission.DUMP");
105 static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
106 static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
107 
108 namespace {
109 
nextRuntimeSensorHandle()110 int32_t nextRuntimeSensorHandle() {
111     using ::aidl::android::hardware::sensors::ISensors;
112     static int32_t nextHandle = ISensors::RUNTIME_SENSORS_HANDLE_BASE;
113     if (nextHandle == ISensors::RUNTIME_SENSORS_HANDLE_END) {
114         return -1;
115     }
116     return nextHandle++;
117 }
118 
119 class RuntimeSensorCallbackProxy : public RuntimeSensor::SensorCallback {
120  public:
RuntimeSensorCallbackProxy(sp<SensorService::RuntimeSensorCallback> callback)121     RuntimeSensorCallbackProxy(sp<SensorService::RuntimeSensorCallback> callback)
122         : mCallback(std::move(callback)) {}
onConfigurationChanged(int handle,bool enabled,int64_t samplingPeriodNs,int64_t batchReportLatencyNs)123     status_t onConfigurationChanged(int handle, bool enabled, int64_t samplingPeriodNs,
124                                     int64_t batchReportLatencyNs) override {
125         return mCallback->onConfigurationChanged(handle, enabled, samplingPeriodNs,
126                 batchReportLatencyNs);
127     }
128  private:
129     sp<SensorService::RuntimeSensorCallback> mCallback;
130 };
131 
132 } // namespace
133 
isAutomotive()134 static bool isAutomotive() {
135     sp<IServiceManager> serviceManager = defaultServiceManager();
136     if (serviceManager.get() == nullptr) {
137         ALOGE("%s: unable to access native ServiceManager", __func__);
138         return false;
139     }
140 
141     sp<content::pm::IPackageManagerNative> packageManager;
142     sp<IBinder> binder = serviceManager->waitForService(String16("package_native"));
143     packageManager = interface_cast<content::pm::IPackageManagerNative>(binder);
144     if (packageManager == nullptr) {
145         ALOGE("%s: unable to access native PackageManager", __func__);
146         return false;
147     }
148 
149     bool isAutomotive = false;
150     binder::Status status =
151         packageManager->hasSystemFeature(String16("android.hardware.type.automotive"), 0,
152                                          &isAutomotive);
153     if (!status.isOk()) {
154         ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str());
155         return false;
156     }
157 
158     return isAutomotive;
159 }
160 
SensorService()161 SensorService::SensorService()
162     : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
163       mWakeLockAcquired(false), mLastReportedProxIsActive(false) {
164     mUidPolicy = new UidPolicy(this);
165     mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
166     mMicSensorPrivacyPolicy = new MicrophonePrivacyPolicy(this);
167 }
168 
registerRuntimeSensor(const sensor_t & sensor,int deviceId,sp<RuntimeSensorCallback> callback)169 int SensorService::registerRuntimeSensor(
170         const sensor_t& sensor, int deviceId, sp<RuntimeSensorCallback> callback) {
171     int handle = 0;
172     while (handle == 0 || !mSensors.isNewHandle(handle)) {
173         handle = nextRuntimeSensorHandle();
174         if (handle < 0) {
175             // Ran out of the dedicated range for runtime sensors.
176             return handle;
177         }
178     }
179 
180     ALOGI("Registering runtime sensor handle 0x%x, type %d, name %s",
181             handle, sensor.type, sensor.name);
182 
183     sp<RuntimeSensor::SensorCallback> runtimeSensorCallback(
184             new RuntimeSensorCallbackProxy(callback));
185     sensor_t runtimeSensor = sensor;
186     // force the handle to be consistent
187     runtimeSensor.handle = handle;
188     auto si = std::make_shared<RuntimeSensor>(runtimeSensor, std::move(runtimeSensorCallback));
189 
190     Mutex::Autolock _l(mLock);
191     if (!registerSensor(std::move(si), /* isDebug= */ false, /* isVirtual= */ false, deviceId)) {
192         // The registration was unsuccessful.
193         return mSensors.getNonSensor().getHandle();
194     }
195 
196     if (mRuntimeSensorCallbacks.find(deviceId) == mRuntimeSensorCallbacks.end()) {
197         mRuntimeSensorCallbacks.emplace(deviceId, callback);
198     }
199     return handle;
200 }
201 
unregisterRuntimeSensor(int handle)202 status_t SensorService::unregisterRuntimeSensor(int handle) {
203     ALOGI("Unregistering runtime sensor handle 0x%x disconnected", handle);
204     int deviceId = getDeviceIdFromHandle(handle);
205     {
206         Mutex::Autolock _l(mLock);
207         if (!unregisterDynamicSensorLocked(handle)) {
208             ALOGE("Runtime sensor release error.");
209             return UNKNOWN_ERROR;
210         }
211     }
212 
213     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
214     for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
215         connection->removeSensor(handle);
216     }
217 
218     // If this was the last sensor for this device, remove its callback.
219     bool deviceHasSensors = false;
220     mSensors.forEachEntry(
221             [&deviceId, &deviceHasSensors] (const SensorServiceUtil::SensorList::Entry& e) -> bool {
222                 if (e.deviceId == deviceId) {
223                     deviceHasSensors = true;
224                     return false;  // stop iterating
225                 }
226                 return true;
227             });
228     if (!deviceHasSensors) {
229         mRuntimeSensorCallbacks.erase(deviceId);
230     }
231     return OK;
232 }
233 
sendRuntimeSensorEvent(const sensors_event_t & event)234 status_t SensorService::sendRuntimeSensorEvent(const sensors_event_t& event) {
235     Mutex::Autolock _l(mLock);
236     mRuntimeSensorEventQueue.push(event);
237     return OK;
238 }
239 
initializeHmacKey()240 bool SensorService::initializeHmacKey() {
241     int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
242     if (fd != -1) {
243         int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
244         close(fd);
245         if (result == sizeof(sHmacGlobalKey)) {
246             return true;
247         }
248         ALOGW("Unable to read HMAC key; generating new one.");
249     }
250 
251     if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
252         ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
253         return false;
254     }
255 
256     // We need to make sure this is only readable to us.
257     bool wroteKey = false;
258     mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
259     fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
260               S_IRUSR|S_IWUSR);
261     if (fd != -1) {
262         int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
263         close(fd);
264         wroteKey = (result == sizeof(sHmacGlobalKey));
265     }
266     if (wroteKey) {
267         ALOGI("Generated new HMAC key.");
268     } else {
269         ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
270               "after reboot.");
271     }
272     // Even if we failed to write the key we return true, because we did
273     // initialize the HMAC key.
274     return true;
275 }
276 
277 // Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
enableSchedFifoMode()278 void SensorService::enableSchedFifoMode() {
279     struct sched_param param = {0};
280     param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
281     if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
282         ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
283     }
284 }
285 
onFirstRef()286 void SensorService::onFirstRef() {
287     ALOGD("nuSensorService starting...");
288     SensorDevice& dev(SensorDevice::getInstance());
289 
290     sHmacGlobalKeyIsValid = initializeHmacKey();
291 
292     if (dev.initCheck() == NO_ERROR) {
293         sensor_t const* list;
294         ssize_t count = dev.getSensorList(&list);
295         if (count > 0) {
296             bool hasGyro = false, hasAccel = false, hasMag = false;
297             bool hasGyroUncalibrated = false;
298             bool hasAccelUncalibrated = false;
299             uint32_t virtualSensorsNeeds =
300                     (1<<SENSOR_TYPE_GRAVITY) |
301                     (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
302                     (1<<SENSOR_TYPE_ROTATION_VECTOR) |
303                     (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
304                     (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
305 
306             for (ssize_t i=0 ; i<count ; i++) {
307                 bool useThisSensor = true;
308 
309                 switch (list[i].type) {
310                     case SENSOR_TYPE_ACCELEROMETER:
311                         hasAccel = true;
312                         break;
313                     case SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED:
314                         hasAccelUncalibrated = true;
315                         break;
316                     case SENSOR_TYPE_MAGNETIC_FIELD:
317                         hasMag = true;
318                         break;
319                     case SENSOR_TYPE_GYROSCOPE:
320                         hasGyro = true;
321                         break;
322                     case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
323                         hasGyroUncalibrated = true;
324                         break;
325                     case SENSOR_TYPE_GRAVITY:
326                     case SENSOR_TYPE_LINEAR_ACCELERATION:
327                     case SENSOR_TYPE_ROTATION_VECTOR:
328                     case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
329                     case SENSOR_TYPE_GAME_ROTATION_VECTOR:
330                         if (IGNORE_HARDWARE_FUSION) {
331                             useThisSensor = false;
332                         } else {
333                             virtualSensorsNeeds &= ~(1<<list[i].type);
334                         }
335                         break;
336                     default:
337                         break;
338                 }
339                 if (useThisSensor) {
340                     if (list[i].type == SENSOR_TYPE_PROXIMITY) {
341                         auto s = std::make_shared<ProximitySensor>(list[i], *this);
342                         const int handle = s->getSensor().getHandle();
343                         if (registerSensor(std::move(s))) {
344                             mProxSensorHandles.push_back(handle);
345                         }
346                     } else {
347                         registerSensor(std::make_shared<HardwareSensor>(list[i]));
348                     }
349                 }
350             }
351 
352             // it's safe to instantiate the SensorFusion object here
353             // (it wants to be instantiated after h/w sensors have been
354             // registered)
355             SensorFusion::getInstance();
356 
357             if ((hasGyro || hasGyroUncalibrated) && hasAccel && hasMag) {
358                 // Add Android virtual sensors if they're not already
359                 // available in the HAL
360                 bool needRotationVector =
361                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
362                 registerVirtualSensor(std::make_shared<RotationVectorSensor>(),
363                                       /* isDebug= */ !needRotationVector);
364                 registerVirtualSensor(std::make_shared<OrientationSensor>(),
365                                       /* isDebug= */ !needRotationVector);
366 
367                 // virtual debugging sensors are not for user
368                 registerVirtualSensor(std::make_shared<CorrectedGyroSensor>(list, count),
369                                       /* isDebug= */ true);
370                 registerVirtualSensor(std::make_shared<GyroDriftSensor>(), /* isDebug= */ true);
371             }
372 
373             if (hasAccel && (hasGyro || hasGyroUncalibrated)) {
374                 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
375                 registerVirtualSensor(std::make_shared<GravitySensor>(list, count),
376                                       /* isDebug= */ !needGravitySensor);
377 
378                 bool needLinearAcceleration =
379                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
380                 registerVirtualSensor(std::make_shared<LinearAccelerationSensor>(list, count),
381                                       /* isDebug= */ !needLinearAcceleration);
382 
383                 bool needGameRotationVector =
384                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
385                 registerVirtualSensor(std::make_shared<GameRotationVectorSensor>(),
386                                       /* isDebug= */ !needGameRotationVector);
387             }
388 
389             if (hasAccel && hasMag) {
390                 bool needGeoMagRotationVector =
391                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
392                 registerVirtualSensor(std::make_shared<GeoMagRotationVectorSensor>(),
393                                       /* isDebug= */ !needGeoMagRotationVector);
394             }
395 
396             if (isAutomotive()) {
397                 if (hasAccel) {
398                     registerVirtualSensor(
399                             std::make_shared<LimitedAxesImuSensor>(
400                                     list, count, SENSOR_TYPE_ACCELEROMETER));
401                }
402 
403                if (hasGyro) {
404                     registerVirtualSensor(
405                             std::make_shared<LimitedAxesImuSensor>(
406                                     list, count, SENSOR_TYPE_GYROSCOPE));
407                }
408 
409                if (hasAccelUncalibrated) {
410                     registerVirtualSensor(
411                             std::make_shared<LimitedAxesImuSensor>(
412                                     list, count, SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED));
413                }
414 
415                if (hasGyroUncalibrated) {
416                     registerVirtualSensor(
417                             std::make_shared<LimitedAxesImuSensor>(
418                                     list, count, SENSOR_TYPE_GYROSCOPE_UNCALIBRATED));
419                }
420             }
421 
422             // Check if the device really supports batching by looking at the FIFO event
423             // counts for each sensor.
424             bool batchingSupported = false;
425             mSensors.forEachSensor(
426                     [&batchingSupported] (const Sensor& s) -> bool {
427                         if (s.getFifoMaxEventCount() > 0) {
428                             batchingSupported = true;
429                         }
430                         return !batchingSupported;
431                     });
432 
433             if (batchingSupported) {
434                 // Increase socket buffer size to a max of 100 KB for batching capabilities.
435                 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
436             } else {
437                 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
438             }
439 
440             // Compare the socketBufferSize value against the system limits and limit
441             // it to maxSystemSocketBufferSize if necessary.
442             FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
443             char line[128];
444             if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
445                 line[sizeof(line) - 1] = '\0';
446                 size_t maxSystemSocketBufferSize;
447                 sscanf(line, "%zu", &maxSystemSocketBufferSize);
448                 if (mSocketBufferSize > maxSystemSocketBufferSize) {
449                     mSocketBufferSize = maxSystemSocketBufferSize;
450                 }
451             }
452             if (fp) {
453                 fclose(fp);
454             }
455 
456             mWakeLockAcquired = false;
457             mLooper = new Looper(false);
458             const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
459             mSensorEventBuffer = new sensors_event_t[minBufferSize];
460             mSensorEventScratch = new sensors_event_t[minBufferSize];
461             mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
462             mCurrentOperatingMode = NORMAL;
463 
464             mNextSensorRegIndex = 0;
465             for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
466                 mLastNSensorRegistrations.push();
467             }
468 
469             mInitCheck = NO_ERROR;
470             mAckReceiver = new SensorEventAckReceiver(this);
471             mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
472             run("SensorService", PRIORITY_URGENT_DISPLAY);
473 
474             // priority can only be changed after run
475             enableSchedFifoMode();
476 
477             // Start watching UID changes to apply policy.
478             mUidPolicy->registerSelf();
479 
480             // Start watching sensor privacy changes
481             mSensorPrivacyPolicy->registerSelf();
482 
483             // Start watching mic sensor privacy changes
484             mMicSensorPrivacyPolicy->registerSelf();
485         }
486     }
487 }
488 
onUidStateChanged(uid_t uid,UidState state)489 void SensorService::onUidStateChanged(uid_t uid, UidState state) {
490     SensorDevice& dev(SensorDevice::getInstance());
491 
492     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
493     for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
494         if (conn->getUid() == uid) {
495             dev.setUidStateForConnection(conn.get(), state);
496         }
497     }
498 
499     for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
500         if (conn->getUid() == uid) {
501             // Update sensor subscriptions if needed
502             bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
503             conn->onSensorAccessChanged(hasAccess);
504         }
505     }
506     checkAndReportProxStateChangeLocked();
507 }
508 
hasSensorAccess(uid_t uid,const String16 & opPackageName)509 bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
510     Mutex::Autolock _l(mLock);
511     return hasSensorAccessLocked(uid, opPackageName);
512 }
513 
hasSensorAccessLocked(uid_t uid,const String16 & opPackageName)514 bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
515     return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
516         && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
517 }
518 
registerSensor(std::shared_ptr<SensorInterface> s,bool isDebug,bool isVirtual,int deviceId)519 bool SensorService::registerSensor(std::shared_ptr<SensorInterface> s, bool isDebug, bool isVirtual,
520                                    int deviceId) {
521     const int handle = s->getSensor().getHandle();
522     const int type = s->getSensor().getType();
523     if (mSensors.add(handle, std::move(s), isDebug, isVirtual, deviceId)) {
524         mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
525         return true;
526     } else {
527         LOG_FATAL("Failed to register sensor with handle %d", handle);
528         return false;
529     }
530 }
531 
registerDynamicSensorLocked(std::shared_ptr<SensorInterface> s,bool isDebug)532 bool SensorService::registerDynamicSensorLocked(std::shared_ptr<SensorInterface> s, bool isDebug) {
533     return registerSensor(std::move(s), isDebug);
534 }
535 
unregisterDynamicSensorLocked(int handle)536 bool SensorService::unregisterDynamicSensorLocked(int handle) {
537     bool ret = mSensors.remove(handle);
538 
539     const auto i = mRecentEvent.find(handle);
540     if (i != mRecentEvent.end()) {
541         delete i->second;
542         mRecentEvent.erase(i);
543     }
544     return ret;
545 }
546 
registerVirtualSensor(std::shared_ptr<SensorInterface> s,bool isDebug)547 bool SensorService::registerVirtualSensor(std::shared_ptr<SensorInterface> s, bool isDebug) {
548     return registerSensor(std::move(s), isDebug, true);
549 }
550 
~SensorService()551 SensorService::~SensorService() {
552     for (auto && entry : mRecentEvent) {
553         delete entry.second;
554     }
555     mUidPolicy->unregisterSelf();
556     mSensorPrivacyPolicy->unregisterSelf();
557     mMicSensorPrivacyPolicy->unregisterSelf();
558 }
559 
dump(int fd,const Vector<String16> & args)560 status_t SensorService::dump(int fd, const Vector<String16>& args) {
561     String8 result;
562     if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
563         result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
564                 IPCThreadState::self()->getCallingPid(),
565                 IPCThreadState::self()->getCallingUid());
566     } else {
567         bool privileged = IPCThreadState::self()->getCallingUid() == 0;
568         if (args.size() > 2) {
569            return INVALID_OPERATION;
570         }
571         if (args.size() > 0) {
572             Mode targetOperatingMode = NORMAL;
573             std::string inputStringMode = String8(args[0]).string();
574             if (getTargetOperatingMode(inputStringMode, &targetOperatingMode)) {
575               status_t error = changeOperatingMode(args, targetOperatingMode);
576               // Dump the latest state only if no error was encountered.
577               if (error != NO_ERROR) {
578                 return error;
579               }
580             }
581         }
582 
583         ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
584         // Run the following logic if a transition isn't requested above based on the input
585         // argument parsing.
586         if (args.size() == 1 && args[0] == String16("--proto")) {
587             return dumpProtoLocked(fd, &connLock);
588         } else if (!mSensors.hasAnySensor()) {
589             result.append("No Sensors on the device\n");
590             result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
591         } else {
592             // Default dump the sensor list and debugging information.
593             //
594             timespec curTime;
595             clock_gettime(CLOCK_REALTIME, &curTime);
596             struct tm* timeinfo = localtime(&(curTime.tv_sec));
597             result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
598                                 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
599             result.append("Sensor Device:\n");
600             result.append(SensorDevice::getInstance().dump().c_str());
601 
602             result.append("Sensor List:\n");
603             result.append(mSensors.dump().c_str());
604 
605             result.append("Fusion States:\n");
606             SensorFusion::getInstance().dump(result);
607 
608             result.append("Recent Sensor events:\n");
609             for (auto&& i : mRecentEvent) {
610                 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
611                 if (!i.second->isEmpty() && s != nullptr) {
612                     if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
613                         i.second->setFormat("normal");
614                     } else {
615                         i.second->setFormat("mask_data");
616                     }
617                     // if there is events and sensor does not need special permission.
618                     result.appendFormat("%s: ", s->getSensor().getName().string());
619                     result.append(i.second->dump().c_str());
620                 }
621             }
622 
623             result.append("Active sensors:\n");
624             SensorDevice& dev = SensorDevice::getInstance();
625             for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
626                 int handle = mActiveSensors.keyAt(i);
627                 if (dev.isSensorActive(handle)) {
628                     result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
629                             getSensorName(handle).string(),
630                             handle,
631                             mActiveSensors.valueAt(i)->getNumConnections());
632                 }
633             }
634 
635             result.appendFormat("Socket Buffer size = %zd events\n",
636                                 mSocketBufferSize/sizeof(sensors_event_t));
637             result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
638                     "not held");
639             result.appendFormat("Mode :");
640             switch(mCurrentOperatingMode) {
641                case NORMAL:
642                    result.appendFormat(" NORMAL\n");
643                    break;
644                case RESTRICTED:
645                    result.appendFormat(" RESTRICTED : %s\n", mAllowListedPackage.string());
646                    break;
647                case DATA_INJECTION:
648                    result.appendFormat(" DATA_INJECTION : %s\n", mAllowListedPackage.string());
649                    break;
650                case REPLAY_DATA_INJECTION:
651                    result.appendFormat(" REPLAY_DATA_INJECTION : %s\n",
652                             mAllowListedPackage.string());
653                    break;
654                default:
655                    result.appendFormat(" UNKNOWN\n");
656                    break;
657             }
658             result.appendFormat("Sensor Privacy: %s\n",
659                     mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
660 
661             const auto& activeConnections = connLock.getActiveConnections();
662             result.appendFormat("%zd active connections\n", activeConnections.size());
663             for (size_t i=0 ; i < activeConnections.size() ; i++) {
664                 result.appendFormat("Connection Number: %zu \n", i);
665                 activeConnections[i]->dump(result);
666             }
667 
668             const auto& directConnections = connLock.getDirectConnections();
669             result.appendFormat("%zd direct connections\n", directConnections.size());
670             for (size_t i = 0 ; i < directConnections.size() ; i++) {
671                 result.appendFormat("Direct connection %zu:\n", i);
672                 directConnections[i]->dump(result);
673             }
674 
675             result.appendFormat("Previous Registrations:\n");
676             // Log in the reverse chronological order.
677             int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
678                 SENSOR_REGISTRATIONS_BUF_SIZE;
679             const int startIndex = currentIndex;
680             do {
681                 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
682                 if (SensorRegistrationInfo::isSentinel(reg_info)) {
683                     // Ignore sentinel, proceed to next item.
684                     currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
685                         SENSOR_REGISTRATIONS_BUF_SIZE;
686                     continue;
687                 }
688                 result.appendFormat("%s\n", reg_info.dump().c_str());
689                 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
690                         SENSOR_REGISTRATIONS_BUF_SIZE;
691             } while(startIndex != currentIndex);
692         }
693     }
694     write(fd, result.string(), result.size());
695     return NO_ERROR;
696 }
697 
698 /**
699  * Dump debugging information as android.service.SensorServiceProto protobuf message using
700  * ProtoOutputStream.
701  *
702  * See proto definition and some notes about ProtoOutputStream in
703  * frameworks/base/core/proto/android/service/sensor_service.proto
704  */
dumpProtoLocked(int fd,ConnectionSafeAutolock * connLock) const705 status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
706     using namespace service::SensorServiceProto;
707     util::ProtoOutputStream proto;
708     proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
709     if (!mSensors.hasAnySensor()) {
710         return proto.flush(fd) ? OK : UNKNOWN_ERROR;
711     }
712     const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
713 
714     timespec curTime;
715     clock_gettime(CLOCK_REALTIME, &curTime);
716     proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
717 
718     // Write SensorDeviceProto
719     uint64_t token = proto.start(SENSOR_DEVICE);
720     SensorDevice::getInstance().dump(&proto);
721     proto.end(token);
722 
723     // Write SensorListProto
724     token = proto.start(SENSORS);
725     mSensors.dump(&proto);
726     proto.end(token);
727 
728     // Write SensorFusionProto
729     token = proto.start(FUSION_STATE);
730     SensorFusion::getInstance().dump(&proto);
731     proto.end(token);
732 
733     // Write SensorEventsProto
734     token = proto.start(SENSOR_EVENTS);
735     for (auto&& i : mRecentEvent) {
736         std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
737         if (!i.second->isEmpty() && s != nullptr) {
738             i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
739                     "normal" : "mask_data");
740             const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
741             proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
742                     std::string(s->getSensor().getName().string()));
743             i.second->dump(&proto);
744             proto.end(mToken);
745         }
746     }
747     proto.end(token);
748 
749     // Write ActiveSensorProto
750     SensorDevice& dev = SensorDevice::getInstance();
751     for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
752         int handle = mActiveSensors.keyAt(i);
753         if (dev.isSensorActive(handle)) {
754             token = proto.start(ACTIVE_SENSORS);
755             proto.write(service::ActiveSensorProto::NAME,
756                     std::string(getSensorName(handle).string()));
757             proto.write(service::ActiveSensorProto::HANDLE, handle);
758             proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
759                     int(mActiveSensors.valueAt(i)->getNumConnections()));
760             proto.end(token);
761         }
762     }
763 
764     proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
765     proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
766     proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
767 
768     switch(mCurrentOperatingMode) {
769         case NORMAL:
770             proto.write(OPERATING_MODE, OP_MODE_NORMAL);
771             break;
772         case RESTRICTED:
773             proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
774             proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.string()));
775             break;
776         case DATA_INJECTION:
777             proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
778             proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.string()));
779             break;
780         default:
781             proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
782     }
783     proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
784 
785     // Write repeated SensorEventConnectionProto
786     const auto& activeConnections = connLock->getActiveConnections();
787     for (size_t i = 0; i < activeConnections.size(); i++) {
788         token = proto.start(ACTIVE_CONNECTIONS);
789         activeConnections[i]->dump(&proto);
790         proto.end(token);
791     }
792 
793     // Write repeated SensorDirectConnectionProto
794     const auto& directConnections = connLock->getDirectConnections();
795     for (size_t i = 0 ; i < directConnections.size() ; i++) {
796         token = proto.start(DIRECT_CONNECTIONS);
797         directConnections[i]->dump(&proto);
798         proto.end(token);
799     }
800 
801     // Write repeated SensorRegistrationInfoProto
802     const int startIndex = mNextSensorRegIndex;
803     int curr = startIndex;
804     do {
805         const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
806         if (SensorRegistrationInfo::isSentinel(reg_info)) {
807             // Ignore sentinel, proceed to next item.
808             curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
809             continue;
810         }
811         token = proto.start(PREVIOUS_REGISTRATIONS);
812         reg_info.dump(&proto);
813         proto.end(token);
814         curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
815     } while (startIndex != curr);
816 
817     return proto.flush(fd) ? OK : UNKNOWN_ERROR;
818 }
819 
disableAllSensors()820 void SensorService::disableAllSensors() {
821     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
822     disableAllSensorsLocked(&connLock);
823 }
824 
disableAllSensorsLocked(ConnectionSafeAutolock * connLock)825 void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
826     SensorDevice& dev(SensorDevice::getInstance());
827     for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
828         bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
829         conn->onSensorAccessChanged(hasAccess);
830     }
831     dev.disableAllSensors();
832     checkAndReportProxStateChangeLocked();
833     // Clear all pending flush connections for all active sensors. If one of the active
834     // connections has called flush() and the underlying sensor has been disabled before a
835     // flush complete event is returned, we need to remove the connection from this queue.
836     for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
837         mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
838     }
839 }
840 
enableAllSensors()841 void SensorService::enableAllSensors() {
842     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
843     enableAllSensorsLocked(&connLock);
844 }
845 
enableAllSensorsLocked(ConnectionSafeAutolock * connLock)846 void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
847     // sensors should only be enabled if the operating state is not restricted and sensor
848     // privacy is not enabled.
849     if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
850         ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
851               mCurrentOperatingMode,
852               mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
853         return;
854     }
855     SensorDevice& dev(SensorDevice::getInstance());
856     dev.enableAllSensors();
857     for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
858         bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
859         conn->onSensorAccessChanged(hasAccess);
860     }
861     checkAndReportProxStateChangeLocked();
862 }
863 
capRates()864 void SensorService::capRates() {
865     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
866     for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
867         conn->onMicSensorAccessChanged(true);
868     }
869 
870     for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
871         conn->onMicSensorAccessChanged(true);
872     }
873 }
874 
uncapRates()875 void SensorService::uncapRates() {
876     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
877     for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
878         conn->onMicSensorAccessChanged(false);
879     }
880 
881     for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
882         conn->onMicSensorAccessChanged(false);
883     }
884 }
885 
886 // NOTE: This is a remote API - make sure all args are validated
shellCommand(int in,int out,int err,Vector<String16> & args)887 status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
888     if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
889         return PERMISSION_DENIED;
890     }
891     if (args.size() == 0) {
892       return BAD_INDEX;
893     }
894     if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
895         return BAD_VALUE;
896     }
897     if (args[0] == String16("set-uid-state")) {
898         return handleSetUidState(args, err);
899     } else if (args[0] == String16("reset-uid-state")) {
900         return handleResetUidState(args, err);
901     } else if (args[0] == String16("get-uid-state")) {
902         return handleGetUidState(args, out, err);
903     } else if (args[0] == String16("unrestrict-ht")) {
904         mHtRestricted = false;
905         return NO_ERROR;
906     } else if (args[0] == String16("restrict-ht")) {
907         mHtRestricted = true;
908         return NO_ERROR;
909     } else if (args.size() == 1 && args[0] == String16("help")) {
910         printHelp(out);
911         return NO_ERROR;
912     }
913     printHelp(err);
914     return BAD_VALUE;
915 }
916 
getUidForPackage(String16 packageName,int userId,uid_t & uid,int err)917 static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
918     PermissionController pc;
919     uid = pc.getPackageUid(packageName, 0);
920     if (uid <= 0) {
921         ALOGE("Unknown package: '%s'", String8(packageName).string());
922         dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
923         return BAD_VALUE;
924     }
925 
926     if (userId < 0) {
927         ALOGE("Invalid user: %d", userId);
928         dprintf(err, "Invalid user: %d\n", userId);
929         return BAD_VALUE;
930     }
931 
932     uid = multiuser_get_uid(userId, uid);
933     return NO_ERROR;
934 }
935 
handleSetUidState(Vector<String16> & args,int err)936 status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
937     // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
938     if (!(args.size() == 3 || args.size() == 5)) {
939         printHelp(err);
940         return BAD_VALUE;
941     }
942 
943     bool active = false;
944     if (args[2] == String16("active")) {
945         active = true;
946     } else if ((args[2] != String16("idle"))) {
947         ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
948         return BAD_VALUE;
949     }
950 
951     int userId = 0;
952     if (args.size() == 5 && args[3] == String16("--user")) {
953         userId = atoi(String8(args[4]));
954     }
955 
956     uid_t uid;
957     if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
958         return BAD_VALUE;
959     }
960 
961     mUidPolicy->addOverrideUid(uid, active);
962     return NO_ERROR;
963 }
964 
handleResetUidState(Vector<String16> & args,int err)965 status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
966     // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
967     if (!(args.size() == 2 || args.size() == 4)) {
968         printHelp(err);
969         return BAD_VALUE;
970     }
971 
972     int userId = 0;
973     if (args.size() == 4 && args[2] == String16("--user")) {
974         userId = atoi(String8(args[3]));
975     }
976 
977     uid_t uid;
978     if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
979         return BAD_VALUE;
980     }
981 
982     mUidPolicy->removeOverrideUid(uid);
983     return NO_ERROR;
984 }
985 
handleGetUidState(Vector<String16> & args,int out,int err)986 status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
987     // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
988     if (!(args.size() == 2 || args.size() == 4)) {
989         printHelp(err);
990         return BAD_VALUE;
991     }
992 
993     int userId = 0;
994     if (args.size() == 4 && args[2] == String16("--user")) {
995         userId = atoi(String8(args[3]));
996     }
997 
998     uid_t uid;
999     if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1000         return BAD_VALUE;
1001     }
1002 
1003     if (mUidPolicy->isUidActive(uid)) {
1004         return dprintf(out, "active\n");
1005     } else {
1006         return dprintf(out, "idle\n");
1007     }
1008 }
1009 
printHelp(int out)1010 status_t SensorService::printHelp(int out) {
1011     return dprintf(out, "Sensor service commands:\n"
1012         "  get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1013         "  set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1014         "  reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
1015         "  help print this message\n");
1016 }
1017 
1018 //TODO: move to SensorEventConnection later
cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection> & connection,sensors_event_t const * buffer,const int count)1019 void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
1020         sensors_event_t const* buffer, const int count) {
1021     for (int i=0 ; i<count ; i++) {
1022         int handle = buffer[i].sensor;
1023         if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1024             handle = buffer[i].meta_data.sensor;
1025         }
1026         if (connection->hasSensor(handle)) {
1027             std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
1028             // If this buffer has an event from a one_shot sensor and this connection is registered
1029             // for this particular one_shot sensor, try cleaning up the connection.
1030             if (si != nullptr &&
1031                 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1032                 si->autoDisable(connection.get(), handle);
1033                 cleanupWithoutDisableLocked(connection, handle);
1034             }
1035 
1036         }
1037    }
1038 }
1039 
threadLoop()1040 bool SensorService::threadLoop() {
1041     ALOGD("nuSensorService thread starting...");
1042 
1043     // each virtual sensor could generate an event per "real" event, that's why we need to size
1044     // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.  in practice, this is too
1045     // aggressive, but guaranteed to be enough.
1046     const size_t vcount = mSensors.getVirtualSensors().size();
1047     const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
1048     const size_t numEventMax = minBufferSize / (1 + vcount);
1049 
1050     SensorDevice& device(SensorDevice::getInstance());
1051 
1052     const int halVersion = device.getHalDeviceVersion();
1053     do {
1054         ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
1055         if (count < 0) {
1056             if(count == DEAD_OBJECT && device.isReconnecting()) {
1057                 device.reconnect();
1058                 continue;
1059             } else {
1060                 ALOGE("sensor poll failed (%s)", strerror(-count));
1061                 break;
1062             }
1063         }
1064 
1065         // Reset sensors_event_t.flags to zero for all events in the buffer.
1066         for (int i = 0; i < count; i++) {
1067              mSensorEventBuffer[i].flags = 0;
1068         }
1069         ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1070 
1071         // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
1072         // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
1073         // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
1074         // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
1075         // releasing the wakelock.
1076         uint32_t wakeEvents = 0;
1077         for (int i = 0; i < count; i++) {
1078             if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
1079                 wakeEvents++;
1080             }
1081         }
1082 
1083         if (wakeEvents > 0) {
1084             if (!mWakeLockAcquired) {
1085                 setWakeLockAcquiredLocked(true);
1086             }
1087             device.writeWakeLockHandled(wakeEvents);
1088         }
1089         recordLastValueLocked(mSensorEventBuffer, count);
1090 
1091         // handle virtual sensors
1092         bool bufferNeedsSorting = false;
1093         if (count && vcount) {
1094             sensors_event_t const * const event = mSensorEventBuffer;
1095             if (!mActiveVirtualSensors.empty()) {
1096                 size_t k = 0;
1097                 SensorFusion& fusion(SensorFusion::getInstance());
1098                 if (fusion.isEnabled()) {
1099                     for (size_t i=0 ; i<size_t(count) ; i++) {
1100                         fusion.process(event[i]);
1101                     }
1102                 }
1103                 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
1104                     for (int handle : mActiveVirtualSensors) {
1105                         if (count + k >= minBufferSize) {
1106                             ALOGE("buffer too small to hold all events: "
1107                                     "count=%zd, k=%zu, size=%zu",
1108                                     count, k, minBufferSize);
1109                             break;
1110                         }
1111                         sensors_event_t out;
1112                         std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
1113                         if (si == nullptr) {
1114                             ALOGE("handle %d is not an valid virtual sensor", handle);
1115                             continue;
1116                         }
1117 
1118                         if (si->process(&out, event[i])) {
1119                             mSensorEventBuffer[count + k] = out;
1120                             k++;
1121                         }
1122                     }
1123                 }
1124                 if (k) {
1125                     // record the last synthesized values
1126                     recordLastValueLocked(&mSensorEventBuffer[count], k);
1127                     count += k;
1128                     bufferNeedsSorting = true;
1129                 }
1130             }
1131         }
1132 
1133         // handle runtime sensors
1134         {
1135             size_t k = 0;
1136             while (!mRuntimeSensorEventQueue.empty()) {
1137                 if (count + k >= minBufferSize) {
1138                     ALOGE("buffer too small to hold all events: count=%zd, k=%zu, size=%zu",
1139                           count, k, minBufferSize);
1140                     break;
1141                 }
1142                 mSensorEventBuffer[count + k] = mRuntimeSensorEventQueue.front();
1143                 mRuntimeSensorEventQueue.pop();
1144                 k++;
1145             }
1146             if (k) {
1147                 // record the last synthesized values
1148                 recordLastValueLocked(&mSensorEventBuffer[count], k);
1149                 count += k;
1150                 bufferNeedsSorting = true;
1151             }
1152         }
1153 
1154         if (bufferNeedsSorting) {
1155             // sort the buffer by time-stamps
1156             sortEventBuffer(mSensorEventBuffer, count);
1157         }
1158 
1159         // handle backward compatibility for RotationVector sensor
1160         if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
1161             for (int i = 0; i < count; i++) {
1162                 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
1163                     // All the 4 components of the quaternion should be available
1164                     // No heading accuracy. Set it to -1
1165                     mSensorEventBuffer[i].data[4] = -1;
1166                 }
1167             }
1168         }
1169 
1170         // Cache the list of active connections, since we use it in multiple places below but won't
1171         // modify it here
1172         const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
1173 
1174         for (int i = 0; i < count; ++i) {
1175             // Map flush_complete_events in the buffer to SensorEventConnections which called flush
1176             // on the hardware sensor. mapFlushEventsToConnections[i] will be the
1177             // SensorEventConnection mapped to the corresponding flush_complete_event in
1178             // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
1179             mMapFlushEventsToConnections[i] = nullptr;
1180             if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
1181                 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
1182                 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
1183                 if (rec != nullptr) {
1184                     mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
1185                     rec->removeFirstPendingFlushConnection();
1186                 }
1187             }
1188 
1189             // handle dynamic sensor meta events, process registration and unregistration of dynamic
1190             // sensor based on content of event.
1191             if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
1192                 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
1193                     int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1194                     const sensor_t& dynamicSensor =
1195                             *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
1196                     ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
1197                           handle, dynamicSensor.type, dynamicSensor.name);
1198 
1199                     if (mSensors.isNewHandle(handle)) {
1200                         const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
1201                         sensor_t s = dynamicSensor;
1202                         // make sure the dynamic sensor flag is set
1203                         s.flags |= DYNAMIC_SENSOR_MASK;
1204                         // force the handle to be consistent
1205                         s.handle = handle;
1206 
1207                         auto si = std::make_shared<HardwareSensor>(s, uuid);
1208 
1209                         // This will release hold on dynamic sensor meta, so it should be called
1210                         // after Sensor object is created.
1211                         device.handleDynamicSensorConnection(handle, true /*connected*/);
1212                         registerDynamicSensorLocked(std::move(si));
1213                     } else {
1214                         ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
1215                     }
1216                 } else {
1217                     int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1218                     ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1219 
1220                     device.handleDynamicSensorConnection(handle, false /*connected*/);
1221                     if (!unregisterDynamicSensorLocked(handle)) {
1222                         ALOGE("Dynamic sensor release error.");
1223                     }
1224 
1225                     for (const sp<SensorEventConnection>& connection : activeConnections) {
1226                         connection->removeSensor(handle);
1227                     }
1228                 }
1229             }
1230         }
1231 
1232         // Send our events to clients. Check the state of wake lock for each client and release the
1233         // lock if none of the clients need it.
1234         bool needsWakeLock = false;
1235         for (const sp<SensorEventConnection>& connection : activeConnections) {
1236             connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1237                     mMapFlushEventsToConnections);
1238             needsWakeLock |= connection->needsWakeLock();
1239             // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1240             // Early check for one-shot sensors.
1241             if (connection->hasOneShotSensors()) {
1242                 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
1243             }
1244         }
1245 
1246         if (mWakeLockAcquired && !needsWakeLock) {
1247             setWakeLockAcquiredLocked(false);
1248         }
1249     } while (!Thread::exitPending());
1250 
1251     ALOGW("Exiting SensorService::threadLoop => aborting...");
1252     abort();
1253     return false;
1254 }
1255 
getLooper() const1256 sp<Looper> SensorService::getLooper() const {
1257     return mLooper;
1258 }
1259 
resetAllWakeLockRefCounts()1260 void SensorService::resetAllWakeLockRefCounts() {
1261     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1262     for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1263         connection->resetWakeLockRefCount();
1264     }
1265     setWakeLockAcquiredLocked(false);
1266 }
1267 
setWakeLockAcquiredLocked(bool acquire)1268 void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1269     if (acquire) {
1270         if (!mWakeLockAcquired) {
1271             acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1272             mWakeLockAcquired = true;
1273         }
1274         mLooper->wake();
1275     } else {
1276         if (mWakeLockAcquired) {
1277             release_wake_lock(WAKE_LOCK_NAME);
1278             mWakeLockAcquired = false;
1279         }
1280     }
1281 }
1282 
isWakeLockAcquired()1283 bool SensorService::isWakeLockAcquired() {
1284     Mutex::Autolock _l(mLock);
1285     return mWakeLockAcquired;
1286 }
1287 
threadLoop()1288 bool SensorService::SensorEventAckReceiver::threadLoop() {
1289     ALOGD("new thread SensorEventAckReceiver");
1290     sp<Looper> looper = mService->getLooper();
1291     do {
1292         bool wakeLockAcquired = mService->isWakeLockAcquired();
1293         int timeout = -1;
1294         if (wakeLockAcquired) timeout = 5000;
1295         int ret = looper->pollOnce(timeout);
1296         if (ret == ALOOPER_POLL_TIMEOUT) {
1297            mService->resetAllWakeLockRefCounts();
1298         }
1299     } while(!Thread::exitPending());
1300     return false;
1301 }
1302 
recordLastValueLocked(const sensors_event_t * buffer,size_t count)1303 void SensorService::recordLastValueLocked(
1304         const sensors_event_t* buffer, size_t count) {
1305     for (size_t i = 0; i < count; i++) {
1306         if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1307             buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
1308             buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
1309             continue;
1310         }
1311 
1312         auto logger = mRecentEvent.find(buffer[i].sensor);
1313         if (logger != mRecentEvent.end()) {
1314             logger->second->addEvent(buffer[i]);
1315         }
1316     }
1317 }
1318 
sortEventBuffer(sensors_event_t * buffer,size_t count)1319 void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
1320     struct compar {
1321         static int cmp(void const* lhs, void const* rhs) {
1322             sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1323             sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
1324             return l->timestamp - r->timestamp;
1325         }
1326     };
1327     qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1328 }
1329 
getSensorName(int handle) const1330 String8 SensorService::getSensorName(int handle) const {
1331     return mSensors.getName(handle);
1332 }
1333 
getSensorStringType(int handle) const1334 String8 SensorService::getSensorStringType(int handle) const {
1335     return mSensors.getStringType(handle);
1336 }
1337 
isVirtualSensor(int handle) const1338 bool SensorService::isVirtualSensor(int handle) const {
1339     std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1340     return sensor != nullptr && sensor->isVirtual();
1341 }
1342 
isWakeUpSensorEvent(const sensors_event_t & event) const1343 bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
1344     int handle = event.sensor;
1345     if (event.type == SENSOR_TYPE_META_DATA) {
1346         handle = event.meta_data.sensor;
1347     }
1348     std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1349     return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
1350 }
1351 
getIdFromUuid(const Sensor::uuid_t & uuid) const1352 int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1353     if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1354         // UUID is not supported for this device.
1355         return 0;
1356     }
1357     if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1358         // This sensor can be uniquely identified in the system by
1359         // the combination of its type and name.
1360         return -1;
1361     }
1362 
1363     // We have a dynamic sensor.
1364 
1365     if (!sHmacGlobalKeyIsValid) {
1366         // Rather than risk exposing UUIDs, we slow down dynamic sensors.
1367         ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1368         return 0;
1369     }
1370 
1371     // We want each app author/publisher to get a different ID, so that the
1372     // same dynamic sensor cannot be tracked across apps by multiple
1373     // authors/publishers.  So we use both our UUID and our User ID.
1374     // Note potential confusion:
1375     //     UUID => Universally Unique Identifier.
1376     //     UID  => User Identifier.
1377     // We refrain from using "uid" except as needed by API to try to
1378     // keep this distinction clear.
1379 
1380     auto appUserId = IPCThreadState::self()->getCallingUid();
1381     uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1382     memcpy(uuidAndApp, &uuid, sizeof(uuid));
1383     memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1384 
1385     // Now we use our key on our UUID/app combo to get the hash.
1386     uint8_t hash[EVP_MAX_MD_SIZE];
1387     unsigned int hashLen;
1388     if (HMAC(EVP_sha256(),
1389              sHmacGlobalKey, sizeof(sHmacGlobalKey),
1390              uuidAndApp, sizeof(uuidAndApp),
1391              hash, &hashLen) == nullptr) {
1392         // Rather than risk exposing UUIDs, we slow down dynamic sensors.
1393         ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1394         return 0;
1395     }
1396 
1397     int32_t id = 0;
1398     if (hashLen < sizeof(id)) {
1399         // We never expect this case, but out of paranoia, we handle it.
1400         // Our 'id' length is already quite small, we don't want the
1401         // effective length of it to be even smaller.
1402         // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1403         ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1404         return 0;
1405     }
1406 
1407     // This is almost certainly less than all of 'hash', but it's as secure
1408     // as we can be with our current 'id' length.
1409     memcpy(&id, hash, sizeof(id));
1410 
1411     // Note at the beginning of the function that we return the values of
1412     // 0 and -1 to represent special cases.  As a result, we can't return
1413     // those as dynamic sensor IDs.  If we happened to hash to one of those
1414     // values, we change 'id' so we report as a dynamic sensor, and not as
1415     // one of those special cases.
1416     if (id == -1) {
1417         id = -2;
1418     } else if (id == 0) {
1419         id = 1;
1420     }
1421     return id;
1422 }
1423 
makeUuidsIntoIdsForSensorList(Vector<Sensor> & sensorList) const1424 void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1425     for (auto &sensor : sensorList) {
1426         int32_t id = getIdFromUuid(sensor.getUuid());
1427         sensor.setId(id);
1428         // The sensor UUID must always be anonymized here for non privileged clients.
1429         // There is no other checks after this point before returning to client process.
1430         if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1431             sensor.anonymizeUuid();
1432         }
1433     }
1434 }
1435 
getSensorList(const String16 & opPackageName)1436 Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
1437     char value[PROPERTY_VALUE_MAX];
1438     property_get("debug.sensors", value, "0");
1439     const Vector<Sensor>& initialSensorList = (atoi(value)) ?
1440             mSensors.getUserDebugSensors() : mSensors.getUserSensors();
1441     Vector<Sensor> accessibleSensorList;
1442 
1443     resetTargetSdkVersionCache(opPackageName);
1444     bool isCapped = isRateCappedBasedOnPermission(opPackageName);
1445     for (size_t i = 0; i < initialSensorList.size(); i++) {
1446         Sensor sensor = initialSensorList[i];
1447         if (isCapped && isSensorInCappedSet(sensor.getType())) {
1448             sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
1449             sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
1450         }
1451         accessibleSensorList.add(sensor);
1452     }
1453     makeUuidsIntoIdsForSensorList(accessibleSensorList);
1454     return accessibleSensorList;
1455 }
1456 
addSensorIfAccessible(const String16 & opPackageName,const Sensor & sensor,Vector<Sensor> & accessibleSensorList)1457 void SensorService::addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
1458         Vector<Sensor>& accessibleSensorList) {
1459     if (canAccessSensor(sensor, "can't see", opPackageName)) {
1460         accessibleSensorList.add(sensor);
1461     } else if (sensor.getType() != SENSOR_TYPE_HEAD_TRACKER) {
1462         ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1463         sensor.getName().string(), sensor.getRequiredPermission().string(),
1464         sensor.getRequiredAppOp());
1465     }
1466 }
1467 
getDynamicSensorList(const String16 & opPackageName)1468 Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
1469     Vector<Sensor> accessibleSensorList;
1470     mSensors.forEachSensor(
1471             [this, &opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
1472                 if (sensor.isDynamicSensor()) {
1473                     addSensorIfAccessible(opPackageName, sensor, accessibleSensorList);
1474                 }
1475                 return true;
1476             });
1477     makeUuidsIntoIdsForSensorList(accessibleSensorList);
1478     return accessibleSensorList;
1479 }
1480 
getRuntimeSensorList(const String16 & opPackageName,int deviceId)1481 Vector<Sensor> SensorService::getRuntimeSensorList(const String16& opPackageName, int deviceId) {
1482     Vector<Sensor> accessibleSensorList;
1483     mSensors.forEachEntry(
1484             [this, &opPackageName, deviceId, &accessibleSensorList] (
1485                     const SensorServiceUtil::SensorList::Entry& e) -> bool {
1486                 if (e.deviceId == deviceId) {
1487                     addSensorIfAccessible(opPackageName, e.si->getSensor(), accessibleSensorList);
1488                 }
1489                 return true;
1490             });
1491     makeUuidsIntoIdsForSensorList(accessibleSensorList);
1492     return accessibleSensorList;
1493 }
1494 
createSensorEventConnection(const String8 & packageName,int requestedMode,const String16 & opPackageName,const String16 & attributionTag)1495 sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
1496         int requestedMode, const String16& opPackageName, const String16& attributionTag) {
1497     // Only 3 modes supported for a SensorEventConnection ... NORMAL, DATA_INJECTION and
1498     // REPLAY_DATA_INJECTION.
1499     if (requestedMode != NORMAL && requestedMode != DATA_INJECTION &&
1500             requestedMode != REPLAY_DATA_INJECTION) {
1501         return nullptr;
1502     }
1503     resetTargetSdkVersionCache(opPackageName);
1504 
1505     Mutex::Autolock _l(mLock);
1506     // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1507     // operating in DI mode.
1508     if (requestedMode == DATA_INJECTION) {
1509         if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1510         if (!isAllowListedPackage(packageName)) return nullptr;
1511     }
1512 
1513     uid_t uid = IPCThreadState::self()->getCallingUid();
1514     pid_t pid = IPCThreadState::self()->getCallingPid();
1515 
1516     String8 connPackageName =
1517             (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1518     String16 connOpPackageName =
1519             (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1520     sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
1521             requestedMode == DATA_INJECTION || requestedMode == REPLAY_DATA_INJECTION,
1522             connOpPackageName, attributionTag));
1523     if (requestedMode == DATA_INJECTION || requestedMode == REPLAY_DATA_INJECTION) {
1524         mConnectionHolder.addEventConnectionIfNotPresent(result);
1525         // Add the associated file descriptor to the Looper for polling whenever there is data to
1526         // be injected.
1527         result->updateLooperRegistration(mLooper);
1528     }
1529     return result;
1530 }
1531 
isDataInjectionEnabled()1532 int SensorService::isDataInjectionEnabled() {
1533     Mutex::Autolock _l(mLock);
1534     return (mCurrentOperatingMode == DATA_INJECTION);
1535 }
1536 
createSensorDirectConnection(const String16 & opPackageName,int deviceId,uint32_t size,int32_t type,int32_t format,const native_handle * resource)1537 sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1538         const String16& opPackageName, int deviceId, uint32_t size, int32_t type, int32_t format,
1539         const native_handle *resource) {
1540     resetTargetSdkVersionCache(opPackageName);
1541     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1542 
1543     // No new direct connections are allowed when sensor privacy is enabled
1544     if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1545         ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1546         return nullptr;
1547     }
1548 
1549     struct sensors_direct_mem_t mem = {
1550         .type = type,
1551         .format = format,
1552         .size = size,
1553         .handle = resource,
1554     };
1555     uid_t uid = IPCThreadState::self()->getCallingUid();
1556 
1557     if (mem.handle == nullptr) {
1558         ALOGE("Failed to clone resource handle");
1559         return nullptr;
1560     }
1561 
1562     // check format
1563     if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1564         ALOGE("Direct channel format %d is unsupported!", format);
1565         return nullptr;
1566     }
1567 
1568     // check for duplication
1569     for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1570         if (connection->isEquivalent(&mem)) {
1571             ALOGE("Duplicate create channel request for the same share memory");
1572             return nullptr;
1573         }
1574     }
1575 
1576     // check specific to memory type
1577     switch(type) {
1578         case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
1579             if (resource->numFds < 1) {
1580                 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1581                 android_errorWriteLog(0x534e4554, "70986337");  // SafetyNet
1582                 return nullptr;
1583             }
1584             int fd = resource->data[0];
1585             if (!ashmem_valid(fd)) {
1586                 ALOGE("Supplied Ashmem memory region is invalid");
1587                 return nullptr;
1588             }
1589 
1590             int size2 = ashmem_get_size_region(fd);
1591             // check size consistency
1592             if (size2 < static_cast<int64_t>(size)) {
1593                 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1594                       size, size2);
1595                 return nullptr;
1596             }
1597             break;
1598         }
1599         case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
1600             // no specific checks for gralloc
1601             break;
1602         default:
1603             ALOGE("Unknown direct connection memory type %d", type);
1604             return nullptr;
1605     }
1606 
1607     native_handle_t *clone = native_handle_clone(resource);
1608     if (!clone) {
1609         return nullptr;
1610     }
1611     native_handle_set_fdsan_tag(clone);
1612 
1613     sp<SensorDirectConnection> conn;
1614     int channelHandle = 0;
1615     if (deviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
1616         SensorDevice& dev(SensorDevice::getInstance());
1617         channelHandle = dev.registerDirectChannel(&mem);
1618     } else {
1619         auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1620         if (runtimeSensorCallback == mRuntimeSensorCallbacks.end()) {
1621             ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1622         } else {
1623             int fd = dup(clone->data[0]);
1624             channelHandle = runtimeSensorCallback->second->onDirectChannelCreated(fd);
1625         }
1626     }
1627 
1628     if (channelHandle <= 0) {
1629         ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1630     } else {
1631         mem.handle = clone;
1632         conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName, deviceId);
1633     }
1634 
1635     if (conn == nullptr) {
1636         native_handle_close_with_tag(clone);
1637         native_handle_delete(clone);
1638     } else {
1639         // add to list of direct connections
1640         // sensor service should never hold pointer or sp of SensorDirectConnection object.
1641         mConnectionHolder.addDirectConnection(conn);
1642     }
1643     return conn;
1644 }
1645 
configureRuntimeSensorDirectChannel(int sensorHandle,const SensorDirectConnection * c,const sensors_direct_cfg_t * config)1646 int SensorService::configureRuntimeSensorDirectChannel(
1647         int sensorHandle, const SensorDirectConnection* c, const sensors_direct_cfg_t* config) {
1648     int deviceId = c->getDeviceId();
1649     int sensorDeviceId = getDeviceIdFromHandle(sensorHandle);
1650     if (sensorDeviceId != c->getDeviceId()) {
1651         ALOGE("Cannot configure direct channel created for device %d with a sensor that belongs "
1652               "to device %d", c->getDeviceId(), sensorDeviceId);
1653         return BAD_VALUE;
1654     }
1655     auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1656     if (runtimeSensorCallback == mRuntimeSensorCallbacks.end()) {
1657         ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1658         return BAD_VALUE;
1659     }
1660     return runtimeSensorCallback->second->onDirectChannelConfigured(
1661             c->getHalChannelHandle(), sensorHandle, config->rate_level);
1662 }
1663 
setOperationParameter(int32_t handle,int32_t type,const Vector<float> & floats,const Vector<int32_t> & ints)1664 int SensorService::setOperationParameter(
1665             int32_t handle, int32_t type,
1666             const Vector<float> &floats, const Vector<int32_t> &ints) {
1667     Mutex::Autolock _l(mLock);
1668 
1669     if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
1670         return PERMISSION_DENIED;
1671     }
1672 
1673     bool isFloat = true;
1674     bool isCustom = false;
1675     size_t expectSize = INT32_MAX;
1676     switch (type) {
1677         case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1678             isFloat = true;
1679             expectSize = 3;
1680             break;
1681         case AINFO_LOCAL_GRAVITY:
1682             isFloat = true;
1683             expectSize = 1;
1684             break;
1685         case AINFO_DOCK_STATE:
1686         case AINFO_HIGH_PERFORMANCE_MODE:
1687         case AINFO_MAGNETIC_FIELD_CALIBRATION:
1688             isFloat = false;
1689             expectSize = 1;
1690             break;
1691         default:
1692             // CUSTOM events must only contain float data; it may have variable size
1693             if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1694                     ints.size() ||
1695                     sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1696                     handle < 0) {
1697                 return BAD_VALUE;
1698             }
1699             isFloat = true;
1700             isCustom = true;
1701             expectSize = floats.size();
1702             break;
1703     }
1704 
1705     if (!isCustom && handle != -1) {
1706         return BAD_VALUE;
1707     }
1708 
1709     // three events: first one is begin tag, last one is end tag, the one in the middle
1710     // is the payload.
1711     sensors_event_t event[3];
1712     int64_t timestamp = elapsedRealtimeNano();
1713     for (sensors_event_t* i = event; i < event + 3; i++) {
1714         *i = (sensors_event_t) {
1715             .version = sizeof(sensors_event_t),
1716             .sensor = handle,
1717             .type = SENSOR_TYPE_ADDITIONAL_INFO,
1718             .timestamp = timestamp++,
1719             .additional_info = (additional_info_event_t) {
1720                 .serial = 0
1721             }
1722         };
1723     }
1724 
1725     event[0].additional_info.type = AINFO_BEGIN;
1726     event[1].additional_info.type = type;
1727     event[2].additional_info.type = AINFO_END;
1728 
1729     if (isFloat) {
1730         if (floats.size() != expectSize) {
1731             return BAD_VALUE;
1732         }
1733         for (size_t i = 0; i < expectSize; ++i) {
1734             event[1].additional_info.data_float[i] = floats[i];
1735         }
1736     } else {
1737         if (ints.size() != expectSize) {
1738             return BAD_VALUE;
1739         }
1740         for (size_t i = 0; i < expectSize; ++i) {
1741             event[1].additional_info.data_int32[i] = ints[i];
1742         }
1743     }
1744 
1745     SensorDevice& dev(SensorDevice::getInstance());
1746     for (sensors_event_t* i = event; i < event + 3; i++) {
1747         int ret = dev.injectSensorData(i);
1748         if (ret != NO_ERROR) {
1749             return ret;
1750         }
1751     }
1752     return NO_ERROR;
1753 }
1754 
resetToNormalMode()1755 status_t SensorService::resetToNormalMode() {
1756     Mutex::Autolock _l(mLock);
1757     return resetToNormalModeLocked();
1758 }
1759 
resetToNormalModeLocked()1760 status_t SensorService::resetToNormalModeLocked() {
1761     SensorDevice& dev(SensorDevice::getInstance());
1762     status_t err = dev.setMode(NORMAL);
1763     if (err == NO_ERROR) {
1764         mCurrentOperatingMode = NORMAL;
1765         dev.enableAllSensors();
1766         checkAndReportProxStateChangeLocked();
1767     }
1768     return err;
1769 }
1770 
cleanupConnection(SensorEventConnection * c)1771 void SensorService::cleanupConnection(SensorEventConnection* c) {
1772     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1773     const wp<SensorEventConnection> connection(c);
1774     size_t size = mActiveSensors.size();
1775     ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
1776     for (size_t i=0 ; i<size ; ) {
1777         int handle = mActiveSensors.keyAt(i);
1778         if (c->hasSensor(handle)) {
1779             ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
1780             std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1781             if (sensor != nullptr) {
1782                 sensor->activate(c, false);
1783             } else {
1784                 ALOGE("sensor interface of handle=0x%08x is null!", handle);
1785             }
1786             if (c->removeSensor(handle)) {
1787                 BatteryService::disableSensor(c->getUid(), handle);
1788             }
1789         }
1790         SensorRecord* rec = mActiveSensors.valueAt(i);
1791         ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
1792         ALOGD_IF(DEBUG_CONNECTIONS,
1793                 "removing connection %p for sensor[%zu].handle=0x%08x",
1794                 c, i, handle);
1795 
1796         if (rec && rec->removeConnection(connection)) {
1797             ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
1798             mActiveSensors.removeItemsAt(i, 1);
1799             mActiveVirtualSensors.erase(handle);
1800             delete rec;
1801             size--;
1802         } else {
1803             i++;
1804         }
1805     }
1806     c->updateLooperRegistration(mLooper);
1807     mConnectionHolder.removeEventConnection(connection);
1808     if (c->needsWakeLock()) {
1809         checkWakeLockStateLocked(&connLock);
1810     }
1811 
1812     SensorDevice& dev(SensorDevice::getInstance());
1813     dev.notifyConnectionDestroyed(c);
1814 }
1815 
cleanupConnection(SensorDirectConnection * c)1816 void SensorService::cleanupConnection(SensorDirectConnection* c) {
1817     Mutex::Autolock _l(mLock);
1818 
1819     int deviceId = c->getDeviceId();
1820     if (deviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
1821         SensorDevice& dev(SensorDevice::getInstance());
1822         dev.unregisterDirectChannel(c->getHalChannelHandle());
1823     } else {
1824         auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1825         if (runtimeSensorCallback != mRuntimeSensorCallbacks.end()) {
1826             runtimeSensorCallback->second->onDirectChannelDestroyed(c->getHalChannelHandle());
1827         } else {
1828             ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1829         }
1830     }
1831     mConnectionHolder.removeDirectConnection(c);
1832 }
1833 
checkAndReportProxStateChangeLocked()1834 void SensorService::checkAndReportProxStateChangeLocked() {
1835     if (mProxSensorHandles.empty()) return;
1836 
1837     SensorDevice& dev(SensorDevice::getInstance());
1838     bool isActive = false;
1839     for (auto& sensor : mProxSensorHandles) {
1840         if (dev.isSensorActive(sensor)) {
1841             isActive = true;
1842             break;
1843         }
1844     }
1845     if (isActive != mLastReportedProxIsActive) {
1846         notifyProximityStateLocked(isActive, mProximityActiveListeners);
1847         mLastReportedProxIsActive = isActive;
1848     }
1849 }
1850 
notifyProximityStateLocked(const bool isActive,const std::vector<sp<ProximityActiveListener>> & listeners)1851 void SensorService::notifyProximityStateLocked(
1852         const bool isActive,
1853         const std::vector<sp<ProximityActiveListener>>& listeners) {
1854     const uint64_t mySeq = ++curProxCallbackSeq;
1855     std::thread t([isActive, mySeq, listenersCopy = listeners]() {
1856         while (completedCallbackSeq.load() != mySeq - 1)
1857             std::this_thread::sleep_for(1ms);
1858         for (auto& listener : listenersCopy)
1859             listener->onProximityActive(isActive);
1860         completedCallbackSeq++;
1861     });
1862     t.detach();
1863 }
1864 
addProximityActiveListener(const sp<ProximityActiveListener> & callback)1865 status_t SensorService::addProximityActiveListener(const sp<ProximityActiveListener>& callback) {
1866     if (callback == nullptr) {
1867         return BAD_VALUE;
1868     }
1869 
1870     Mutex::Autolock _l(mLock);
1871 
1872     // Check if the callback was already added.
1873     for (const auto& cb : mProximityActiveListeners) {
1874         if (cb == callback) {
1875             return ALREADY_EXISTS;
1876         }
1877     }
1878 
1879     mProximityActiveListeners.push_back(callback);
1880     std::vector<sp<ProximityActiveListener>> listener(1, callback);
1881     notifyProximityStateLocked(mLastReportedProxIsActive, listener);
1882     return OK;
1883 }
1884 
removeProximityActiveListener(const sp<ProximityActiveListener> & callback)1885 status_t SensorService::removeProximityActiveListener(
1886         const sp<ProximityActiveListener>& callback) {
1887     if (callback == nullptr) {
1888         return BAD_VALUE;
1889     }
1890 
1891     Mutex::Autolock _l(mLock);
1892 
1893     for (auto iter = mProximityActiveListeners.begin();
1894          iter != mProximityActiveListeners.end();
1895          ++iter) {
1896         if (*iter == callback) {
1897             mProximityActiveListeners.erase(iter);
1898             return OK;
1899         }
1900     }
1901     return NAME_NOT_FOUND;
1902 }
1903 
getSensorInterfaceFromHandle(int handle) const1904 std::shared_ptr<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
1905     return mSensors.getInterface(handle);
1906 }
1907 
getDeviceIdFromHandle(int handle) const1908 int SensorService::getDeviceIdFromHandle(int handle) const {
1909     int deviceId = RuntimeSensor::DEFAULT_DEVICE_ID;
1910     mSensors.forEachEntry(
1911             [&deviceId, handle] (const SensorServiceUtil::SensorList::Entry& e) -> bool {
1912                 if (e.si->getSensor().getHandle() == handle) {
1913                     deviceId = e.deviceId;
1914                     return false;  // stop iterating
1915                 }
1916                 return true;
1917             });
1918     return deviceId;
1919 }
1920 
enable(const sp<SensorEventConnection> & connection,int handle,nsecs_t samplingPeriodNs,nsecs_t maxBatchReportLatencyNs,int reservedFlags,const String16 & opPackageName)1921 status_t SensorService::enable(const sp<SensorEventConnection>& connection,
1922         int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
1923         const String16& opPackageName) {
1924     if (mInitCheck != NO_ERROR)
1925         return mInitCheck;
1926 
1927     std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1928     if (sensor == nullptr ||
1929         !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
1930         return BAD_VALUE;
1931     }
1932 
1933     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1934     if (mCurrentOperatingMode != NORMAL && mCurrentOperatingMode != REPLAY_DATA_INJECTION &&
1935            !isAllowListedPackage(connection->getPackageName())) {
1936         return INVALID_OPERATION;
1937     }
1938 
1939     SensorRecord* rec = mActiveSensors.valueFor(handle);
1940     if (rec == nullptr) {
1941         rec = new SensorRecord(connection);
1942         mActiveSensors.add(handle, rec);
1943         if (sensor->isVirtual()) {
1944             mActiveVirtualSensors.emplace(handle);
1945         }
1946 
1947         // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1948         // the recent event as stale to ensure that the previous event is not sent to a client. This
1949         // ensures on-change events that were generated during a previous sensor activation are not
1950         // erroneously sent to newly connected clients, especially if a second client registers for
1951         // an on-change sensor before the first client receives the updated event. Once an updated
1952         // event is received, the recent events will be marked as current, and any new clients will
1953         // immediately receive the most recent event.
1954         if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1955             auto logger = mRecentEvent.find(handle);
1956             if (logger != mRecentEvent.end()) {
1957                 logger->second->setLastEventStale();
1958             }
1959         }
1960     } else {
1961         if (rec->addConnection(connection)) {
1962             // this sensor is already activated, but we are adding a connection that uses it.
1963             // Immediately send down the last known value of the requested sensor if it's not a
1964             // "continuous" sensor.
1965             if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1966                 // NOTE: The wake_up flag of this event may get set to
1967                 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
1968 
1969                 auto logger = mRecentEvent.find(handle);
1970                 if (logger != mRecentEvent.end()) {
1971                     sensors_event_t event;
1972                     // Verify that the last sensor event was generated from the current activation
1973                     // of the sensor. If not, it is possible for an on-change sensor to receive a
1974                     // sensor event that is stale if two clients re-activate the sensor
1975                     // simultaneously.
1976                     if(logger->second->populateLastEventIfCurrent(&event)) {
1977                         event.sensor = handle;
1978                         if (event.version == sizeof(sensors_event_t)) {
1979                             if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1980                                 setWakeLockAcquiredLocked(true);
1981                             }
1982                             connection->sendEvents(&event, 1, nullptr);
1983                             if (!connection->needsWakeLock() && mWakeLockAcquired) {
1984                                 checkWakeLockStateLocked(&connLock);
1985                             }
1986                         }
1987                     }
1988                 }
1989             }
1990         }
1991     }
1992 
1993     if (connection->addSensor(handle)) {
1994         BatteryService::enableSensor(connection->getUid(), handle);
1995         // the sensor was added (which means it wasn't already there)
1996         // so, see if this connection becomes active
1997         mConnectionHolder.addEventConnectionIfNotPresent(connection);
1998     } else {
1999         ALOGW("sensor %08x already enabled in connection %p (ignoring)",
2000             handle, connection.get());
2001     }
2002 
2003     // Check maximum delay for the sensor.
2004     nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
2005     if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
2006         samplingPeriodNs = maxDelayNs;
2007     }
2008 
2009     nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2010     if (samplingPeriodNs < minDelayNs) {
2011         samplingPeriodNs = minDelayNs;
2012     }
2013 
2014     ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
2015                                 "rate=%" PRId64 " timeout== %" PRId64"",
2016              handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
2017 
2018     status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
2019                                  maxBatchReportLatencyNs);
2020 
2021     // Call flush() before calling activate() on the sensor. Wait for a first
2022     // flush complete event before sending events on this connection. Ignore
2023     // one-shot sensors which don't support flush(). Ignore on-change sensors
2024     // to maintain the on-change logic (any on-change events except the initial
2025     // one should be trigger by a change in value). Also if this sensor isn't
2026     // already active, don't call flush().
2027     if (err == NO_ERROR &&
2028             sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
2029             rec->getNumConnections() > 1) {
2030         connection->setFirstFlushPending(handle, true);
2031         status_t err_flush = sensor->flush(connection.get(), handle);
2032         // Flush may return error if the underlying h/w sensor uses an older HAL.
2033         if (err_flush == NO_ERROR) {
2034             rec->addPendingFlushConnection(connection.get());
2035         } else {
2036             connection->setFirstFlushPending(handle, false);
2037         }
2038     }
2039 
2040     if (err == NO_ERROR) {
2041         ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
2042         err = sensor->activate(connection.get(), true);
2043     }
2044 
2045     if (err == NO_ERROR) {
2046         connection->updateLooperRegistration(mLooper);
2047 
2048         if (sensor->getSensor().getRequiredPermission().size() > 0 &&
2049                 sensor->getSensor().getRequiredAppOp() >= 0) {
2050             connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
2051         }
2052 
2053         mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2054                 SensorRegistrationInfo(handle, connection->getPackageName(),
2055                                        samplingPeriodNs, maxBatchReportLatencyNs, true);
2056         mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
2057     }
2058 
2059     if (err != NO_ERROR) {
2060         // batch/activate has failed, reset our state.
2061         cleanupWithoutDisableLocked(connection, handle);
2062     }
2063     return err;
2064 }
2065 
disable(const sp<SensorEventConnection> & connection,int handle)2066 status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
2067     if (mInitCheck != NO_ERROR)
2068         return mInitCheck;
2069 
2070     Mutex::Autolock _l(mLock);
2071     status_t err = cleanupWithoutDisableLocked(connection, handle);
2072     if (err == NO_ERROR) {
2073         std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
2074         err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
2075 
2076     }
2077     if (err == NO_ERROR) {
2078         mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2079                 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
2080         mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
2081     }
2082     return err;
2083 }
2084 
cleanupWithoutDisable(const sp<SensorEventConnection> & connection,int handle)2085 status_t SensorService::cleanupWithoutDisable(
2086         const sp<SensorEventConnection>& connection, int handle) {
2087     Mutex::Autolock _l(mLock);
2088     return cleanupWithoutDisableLocked(connection, handle);
2089 }
2090 
cleanupWithoutDisableLocked(const sp<SensorEventConnection> & connection,int handle)2091 status_t SensorService::cleanupWithoutDisableLocked(
2092         const sp<SensorEventConnection>& connection, int handle) {
2093     SensorRecord* rec = mActiveSensors.valueFor(handle);
2094     if (rec) {
2095         // see if this connection becomes inactive
2096         if (connection->removeSensor(handle)) {
2097             BatteryService::disableSensor(connection->getUid(), handle);
2098         }
2099         if (connection->hasAnySensor() == false) {
2100             connection->updateLooperRegistration(mLooper);
2101             mConnectionHolder.removeEventConnection(connection);
2102         }
2103         // see if this sensor becomes inactive
2104         if (rec->removeConnection(connection)) {
2105             mActiveSensors.removeItem(handle);
2106             mActiveVirtualSensors.erase(handle);
2107             delete rec;
2108         }
2109         return NO_ERROR;
2110     }
2111     return BAD_VALUE;
2112 }
2113 
setEventRate(const sp<SensorEventConnection> & connection,int handle,nsecs_t ns,const String16 & opPackageName)2114 status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
2115         int handle, nsecs_t ns, const String16& opPackageName) {
2116     if (mInitCheck != NO_ERROR)
2117         return mInitCheck;
2118 
2119     std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
2120     if (sensor == nullptr ||
2121         !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
2122         return BAD_VALUE;
2123     }
2124 
2125     if (ns < 0)
2126         return BAD_VALUE;
2127 
2128     nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2129     if (ns < minDelayNs) {
2130         ns = minDelayNs;
2131     }
2132 
2133     return sensor->setDelay(connection.get(), handle, ns);
2134 }
2135 
flushSensor(const sp<SensorEventConnection> & connection,const String16 & opPackageName)2136 status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
2137         const String16& opPackageName) {
2138     if (mInitCheck != NO_ERROR) return mInitCheck;
2139     SensorDevice& dev(SensorDevice::getInstance());
2140     const int halVersion = dev.getHalDeviceVersion();
2141     status_t err(NO_ERROR);
2142     Mutex::Autolock _l(mLock);
2143     // Loop through all sensors for this connection and call flush on each of them.
2144     for (int handle : connection->getActiveSensorHandles()) {
2145         std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
2146         if (sensor == nullptr) {
2147             continue;
2148         }
2149         if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
2150             ALOGE("flush called on a one-shot sensor");
2151             err = INVALID_OPERATION;
2152             continue;
2153         }
2154         if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
2155             // For older devices just increment pending flush count which will send a trivial
2156             // flush complete event.
2157             if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
2158                 ALOGE("flush called on an inaccessible sensor");
2159                 err = INVALID_OPERATION;
2160             }
2161         } else {
2162             if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
2163                 err = INVALID_OPERATION;
2164                 continue;
2165             }
2166             status_t err_flush = sensor->flush(connection.get(), handle);
2167             if (err_flush == NO_ERROR) {
2168                 SensorRecord* rec = mActiveSensors.valueFor(handle);
2169                 if (rec != nullptr) rec->addPendingFlushConnection(connection);
2170             }
2171             err = (err_flush != NO_ERROR) ? err_flush : err;
2172         }
2173     }
2174     return err;
2175 }
2176 
canAccessSensor(const Sensor & sensor,const char * operation,const String16 & opPackageName)2177 bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
2178         const String16& opPackageName) {
2179     // Special case for Head Tracker sensor type: currently restricted to system usage only, unless
2180     // the restriction is specially lifted for testing
2181     if (sensor.getType() == SENSOR_TYPE_HEAD_TRACKER &&
2182             !isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
2183         if (!mHtRestricted) {
2184             ALOGI("Permitting access to HT sensor type outside system (%s)",
2185                   String8(opPackageName).string());
2186         } else {
2187             ALOGW("%s %s a sensor (%s) as a non-system client", String8(opPackageName).string(),
2188                   operation, sensor.getName().string());
2189             return false;
2190         }
2191     }
2192 
2193     // Check if a permission is required for this sensor
2194     if (sensor.getRequiredPermission().length() <= 0) {
2195         return true;
2196     }
2197 
2198     const int32_t opCode = sensor.getRequiredAppOp();
2199     int targetSdkVersion = getTargetSdkVersion(opPackageName);
2200 
2201     bool canAccess = false;
2202     if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
2203             (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
2204              sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
2205         // Allow access to step sensors if the application targets pre-Q, which is before the
2206         // requirement to hold the AR permission to access Step Counter and Step Detector events
2207         // was introduced.
2208         canAccess = true;
2209     } else if (hasPermissionForSensor(sensor)) {
2210         // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
2211         if (opCode >= 0) {
2212             const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
2213                     IPCThreadState::self()->getCallingUid(), opPackageName);
2214             canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
2215         } else {
2216             canAccess = true;
2217         }
2218     }
2219 
2220     if (!canAccess) {
2221         ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
2222               operation, sensor.getName().string(), sensor.getRequiredPermission().string());
2223     }
2224 
2225     return canAccess;
2226 }
2227 
hasPermissionForSensor(const Sensor & sensor)2228 bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
2229     bool hasPermission = false;
2230     const String8& requiredPermission = sensor.getRequiredPermission();
2231 
2232     // Runtime permissions can't use the cache as they may change.
2233     if (sensor.isRequiredPermissionRuntime()) {
2234         hasPermission = checkPermission(String16(requiredPermission),
2235                 IPCThreadState::self()->getCallingPid(),
2236                 IPCThreadState::self()->getCallingUid(),
2237                 /*logPermissionFailure=*/ false);
2238     } else {
2239         hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
2240     }
2241     return hasPermission;
2242 }
2243 
getTargetSdkVersion(const String16 & opPackageName)2244 int SensorService::getTargetSdkVersion(const String16& opPackageName) {
2245     // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
2246     // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
2247     // give it elevated privileges.
2248     if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
2249         return -1;
2250     }
2251 
2252     Mutex::Autolock packageLock(sPackageTargetVersionLock);
2253     int targetSdkVersion = -1;
2254     auto entry = sPackageTargetVersion.find(opPackageName);
2255     if (entry != sPackageTargetVersion.end()) {
2256         targetSdkVersion = entry->second;
2257     } else {
2258         sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2259         if (binder != nullptr) {
2260             sp<content::pm::IPackageManagerNative> packageManager =
2261                     interface_cast<content::pm::IPackageManagerNative>(binder);
2262             if (packageManager != nullptr) {
2263                 binder::Status status = packageManager->getTargetSdkVersionForPackage(
2264                         opPackageName, &targetSdkVersion);
2265                 if (!status.isOk()) {
2266                     targetSdkVersion = -1;
2267                 }
2268             }
2269         }
2270         sPackageTargetVersion[opPackageName] = targetSdkVersion;
2271     }
2272     return targetSdkVersion;
2273 }
2274 
resetTargetSdkVersionCache(const String16 & opPackageName)2275 void SensorService::resetTargetSdkVersionCache(const String16& opPackageName) {
2276     Mutex::Autolock packageLock(sPackageTargetVersionLock);
2277     auto iter = sPackageTargetVersion.find(opPackageName);
2278     if (iter != sPackageTargetVersion.end()) {
2279         sPackageTargetVersion.erase(iter);
2280     }
2281 }
2282 
getTargetOperatingMode(const std::string & inputString,Mode * targetModeOut)2283 bool SensorService::getTargetOperatingMode(const std::string &inputString, Mode *targetModeOut) {
2284     if (inputString == std::string("restrict")) {
2285       *targetModeOut = RESTRICTED;
2286       return true;
2287     }
2288     if (inputString == std::string("enable")) {
2289       *targetModeOut = NORMAL;
2290       return true;
2291     }
2292     if (inputString == std::string("data_injection")) {
2293       *targetModeOut = DATA_INJECTION;
2294       return true;
2295     }
2296     if (inputString == std::string("replay_data_injection")) {
2297       *targetModeOut = REPLAY_DATA_INJECTION;
2298       return true;
2299     }
2300     return false;
2301 }
2302 
changeOperatingMode(const Vector<String16> & args,Mode targetOperatingMode)2303 status_t SensorService::changeOperatingMode(const Vector<String16>& args,
2304                                             Mode targetOperatingMode) {
2305     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2306     SensorDevice& dev(SensorDevice::getInstance());
2307     if (mCurrentOperatingMode == targetOperatingMode) {
2308         return NO_ERROR;
2309     }
2310     if (targetOperatingMode != NORMAL && args.size() < 2) {
2311         return INVALID_OPERATION;
2312     }
2313     switch (targetOperatingMode) {
2314       case NORMAL:
2315         // If currently in restricted mode, reset back to NORMAL mode else ignore.
2316         if (mCurrentOperatingMode == RESTRICTED) {
2317             mCurrentOperatingMode = NORMAL;
2318             // enable sensors and recover all sensor direct report
2319             enableAllSensorsLocked(&connLock);
2320         }
2321         if (mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
2322             dev.disableAllSensors();
2323         }
2324         if (mCurrentOperatingMode == DATA_INJECTION ||
2325                 mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
2326           resetToNormalModeLocked();
2327         }
2328         mAllowListedPackage.clear();
2329         return status_t(NO_ERROR);
2330       case RESTRICTED:
2331         // If in any mode other than normal, ignore.
2332         if (mCurrentOperatingMode != NORMAL) {
2333             return INVALID_OPERATION;
2334         }
2335 
2336         mCurrentOperatingMode = RESTRICTED;
2337         // temporarily stop all sensor direct report and disable sensors
2338         disableAllSensorsLocked(&connLock);
2339         mAllowListedPackage.setTo(String8(args[1]));
2340         return status_t(NO_ERROR);
2341       case REPLAY_DATA_INJECTION:
2342         if (SensorServiceUtil::isUserBuild()) {
2343             return INVALID_OPERATION;
2344         }
2345         FALLTHROUGH_INTENDED;
2346       case DATA_INJECTION:
2347         if (mCurrentOperatingMode == NORMAL) {
2348             dev.disableAllSensors();
2349             // Always use DATA_INJECTION here since this value goes to the HAL and the HAL
2350             // doesn't have an understanding of replay vs. normal data injection.
2351             status_t err = dev.setMode(DATA_INJECTION);
2352             if (err == NO_ERROR) {
2353                 mCurrentOperatingMode = targetOperatingMode;
2354             }
2355             if (err != NO_ERROR || targetOperatingMode == REPLAY_DATA_INJECTION) {
2356                 // Re-enable sensors.
2357                 dev.enableAllSensors();
2358             }
2359             mAllowListedPackage.setTo(String8(args[1]));
2360             return NO_ERROR;
2361         } else {
2362             // Transition to data injection mode supported only from NORMAL mode.
2363             return INVALID_OPERATION;
2364         }
2365         break;
2366       default:
2367         break;
2368     }
2369     return NO_ERROR;
2370 }
2371 
checkWakeLockState()2372 void SensorService::checkWakeLockState() {
2373     ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2374     checkWakeLockStateLocked(&connLock);
2375 }
2376 
checkWakeLockStateLocked(ConnectionSafeAutolock * connLock)2377 void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
2378     if (!mWakeLockAcquired) {
2379         return;
2380     }
2381     bool releaseLock = true;
2382     for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
2383         if (connection->needsWakeLock()) {
2384             releaseLock = false;
2385             break;
2386         }
2387     }
2388     if (releaseLock) {
2389         setWakeLockAcquiredLocked(false);
2390     }
2391 }
2392 
sendEventsFromCache(const sp<SensorEventConnection> & connection)2393 void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
2394     Mutex::Autolock _l(mLock);
2395     connection->writeToSocketFromCache();
2396     if (connection->needsWakeLock()) {
2397         setWakeLockAcquiredLocked(true);
2398     }
2399 }
2400 
isAllowListedPackage(const String8 & packageName)2401 bool SensorService::isAllowListedPackage(const String8& packageName) {
2402     return (packageName.contains(mAllowListedPackage.string()));
2403 }
2404 
isOperationRestrictedLocked(const String16 & opPackageName)2405 bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
2406     if (mCurrentOperatingMode == RESTRICTED) {
2407         String8 package(opPackageName);
2408         return !isAllowListedPackage(package);
2409     }
2410     return false;
2411 }
2412 
registerSelf()2413 void SensorService::UidPolicy::registerSelf() {
2414     ActivityManager am;
2415     am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
2416             | ActivityManager::UID_OBSERVER_IDLE
2417             | ActivityManager::UID_OBSERVER_ACTIVE,
2418             ActivityManager::PROCESS_STATE_UNKNOWN,
2419             String16("android"));
2420 }
2421 
unregisterSelf()2422 void SensorService::UidPolicy::unregisterSelf() {
2423     ActivityManager am;
2424     am.unregisterUidObserver(this);
2425 }
2426 
onUidGone(__unused uid_t uid,__unused bool disabled)2427 void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
2428     onUidIdle(uid, disabled);
2429 }
2430 
onUidActive(uid_t uid)2431 void SensorService::UidPolicy::onUidActive(uid_t uid) {
2432     {
2433         Mutex::Autolock _l(mUidLock);
2434         mActiveUids.insert(uid);
2435     }
2436     sp<SensorService> service = mService.promote();
2437     if (service != nullptr) {
2438         service->onUidStateChanged(uid, UID_STATE_ACTIVE);
2439     }
2440 }
2441 
onUidIdle(uid_t uid,__unused bool disabled)2442 void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
2443     bool deleted = false;
2444     {
2445         Mutex::Autolock _l(mUidLock);
2446         if (mActiveUids.erase(uid) > 0) {
2447             deleted = true;
2448         }
2449     }
2450     if (deleted) {
2451         sp<SensorService> service = mService.promote();
2452         if (service != nullptr) {
2453             service->onUidStateChanged(uid, UID_STATE_IDLE);
2454         }
2455     }
2456 }
2457 
addOverrideUid(uid_t uid,bool active)2458 void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
2459     updateOverrideUid(uid, active, true);
2460 }
2461 
removeOverrideUid(uid_t uid)2462 void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
2463     updateOverrideUid(uid, false, false);
2464 }
2465 
updateOverrideUid(uid_t uid,bool active,bool insert)2466 void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
2467     bool wasActive = false;
2468     bool isActive = false;
2469     {
2470         Mutex::Autolock _l(mUidLock);
2471         wasActive = isUidActiveLocked(uid);
2472         mOverrideUids.erase(uid);
2473         if (insert) {
2474             mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2475         }
2476         isActive = isUidActiveLocked(uid);
2477     }
2478     if (wasActive != isActive) {
2479         sp<SensorService> service = mService.promote();
2480         if (service != nullptr) {
2481             service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
2482         }
2483     }
2484 }
2485 
isUidActive(uid_t uid)2486 bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2487     // Non-app UIDs are considered always active
2488     if (uid < FIRST_APPLICATION_UID) {
2489         return true;
2490     }
2491     Mutex::Autolock _l(mUidLock);
2492     return isUidActiveLocked(uid);
2493 }
2494 
isUidActiveLocked(uid_t uid)2495 bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2496     // Non-app UIDs are considered always active
2497     if (uid < FIRST_APPLICATION_UID) {
2498         return true;
2499     }
2500     auto it = mOverrideUids.find(uid);
2501     if (it != mOverrideUids.end()) {
2502         return it->second;
2503     }
2504     return mActiveUids.find(uid) != mActiveUids.end();
2505 }
2506 
isUidActive(uid_t uid)2507 bool SensorService::isUidActive(uid_t uid) {
2508     return mUidPolicy->isUidActive(uid);
2509 }
2510 
isRateCappedBasedOnPermission(const String16 & opPackageName)2511 bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2512     int targetSdk = getTargetSdkVersion(opPackageName);
2513     bool hasSamplingRatePermission = checkPermission(sAccessHighSensorSamplingRatePermission,
2514             IPCThreadState::self()->getCallingPid(),
2515             IPCThreadState::self()->getCallingUid(),
2516             /*logPermissionFailure=*/ false);
2517     if (targetSdk < __ANDROID_API_S__ ||
2518             (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2519         return false;
2520     }
2521     return true;
2522 }
2523 
2524 /**
2525  * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS
2526  * permission.
2527  *
2528  * This needs to be kept in sync with the list defined on the Java side
2529  * in frameworks/base/core/java/android/hardware/SystemSensorManager.java
2530  */
isSensorInCappedSet(int sensorType)2531 bool SensorService::isSensorInCappedSet(int sensorType) {
2532     return (sensorType == SENSOR_TYPE_ACCELEROMETER
2533             || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2534             || sensorType == SENSOR_TYPE_GYROSCOPE
2535             || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2536             || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2537             || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2538 }
2539 
adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t * requestedPeriodNs,const String16 & opPackageName)2540 status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2541         const String16& opPackageName) {
2542     if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2543         return OK;
2544     }
2545     bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
2546     if (shouldCapBasedOnPermission) {
2547         *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2548         if (isPackageDebuggable(opPackageName)) {
2549             return PERMISSION_DENIED;
2550         }
2551         return OK;
2552     }
2553     if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
2554         *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2555         return OK;
2556     }
2557     return OK;
2558 }
2559 
adjustRateLevelBasedOnMicAndPermission(int * requestedRateLevel,const String16 & opPackageName)2560 status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2561         const String16& opPackageName) {
2562     if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2563         return OK;
2564     }
2565     bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
2566     if (shouldCapBasedOnPermission) {
2567         *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2568         if (isPackageDebuggable(opPackageName)) {
2569             return PERMISSION_DENIED;
2570         }
2571         return OK;
2572     }
2573     if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
2574         *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2575         return OK;
2576     }
2577     return OK;
2578 }
2579 
registerSelf()2580 void SensorService::SensorPrivacyPolicy::registerSelf() {
2581     AutoCallerClear acc;
2582     SensorPrivacyManager spm;
2583     mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2584     spm.addSensorPrivacyListener(this);
2585 }
2586 
unregisterSelf()2587 void SensorService::SensorPrivacyPolicy::unregisterSelf() {
2588     AutoCallerClear acc;
2589     SensorPrivacyManager spm;
2590     spm.removeSensorPrivacyListener(this);
2591 }
2592 
isSensorPrivacyEnabled()2593 bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2594     return mSensorPrivacyEnabled;
2595 }
2596 
onSensorPrivacyChanged(int toggleType __unused,int sensor __unused,bool enabled)2597 binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2598         int sensor __unused, bool enabled) {
2599     mSensorPrivacyEnabled = enabled;
2600     sp<SensorService> service = mService.promote();
2601 
2602     if (service != nullptr) {
2603         if (enabled) {
2604             service->disableAllSensors();
2605         } else {
2606             service->enableAllSensors();
2607         }
2608     }
2609     return binder::Status::ok();
2610 }
2611 
registerSelf()2612 void SensorService::MicrophonePrivacyPolicy::registerSelf() {
2613     AutoCallerClear acc;
2614     SensorPrivacyManager spm;
2615     mSensorPrivacyEnabled =
2616             spm.isToggleSensorPrivacyEnabled(
2617                     SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
2618             SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE)
2619                     || spm.isToggleSensorPrivacyEnabled(
2620                             SensorPrivacyManager::TOGGLE_TYPE_HARDWARE,
2621                             SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE);
2622     spm.addToggleSensorPrivacyListener(this);
2623 }
2624 
unregisterSelf()2625 void SensorService::MicrophonePrivacyPolicy::unregisterSelf() {
2626     AutoCallerClear acc;
2627     SensorPrivacyManager spm;
2628     spm.removeToggleSensorPrivacyListener(this);
2629 }
2630 
onSensorPrivacyChanged(int toggleType __unused,int sensor,bool enabled)2631 binder::Status SensorService::MicrophonePrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2632         int sensor, bool enabled) {
2633     if (sensor != SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE) {
2634         return binder::Status::ok();
2635     }
2636     mSensorPrivacyEnabled = enabled;
2637     sp<SensorService> service = mService.promote();
2638 
2639     if (service != nullptr) {
2640         if (enabled) {
2641             service->capRates();
2642         } else {
2643             service->uncapRates();
2644         }
2645     }
2646     return binder::Status::ok();
2647 }
2648 
ConnectionSafeAutolock(SensorService::SensorConnectionHolder & holder,Mutex & mutex)2649 SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2650         SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2651         : mConnectionHolder(holder), mAutolock(mutex) {}
2652 
2653 template<typename ConnectionType>
getConnectionsHelper(const SortedVector<wp<ConnectionType>> & connectionList,std::vector<std::vector<sp<ConnectionType>>> * referenceHolder)2654 const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2655         const SortedVector<wp<ConnectionType>>& connectionList,
2656         std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2657     referenceHolder->emplace_back();
2658     std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2659     for (const wp<ConnectionType>& weakConnection : connectionList){
2660         sp<ConnectionType> connection = weakConnection.promote();
2661         if (connection != nullptr) {
2662             connections.push_back(std::move(connection));
2663         }
2664     }
2665     return connections;
2666 }
2667 
2668 const std::vector<sp<SensorService::SensorEventConnection>>&
getActiveConnections()2669         SensorService::ConnectionSafeAutolock::getActiveConnections() {
2670     return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2671                                 &mReferencedActiveConnections);
2672 }
2673 
2674 const std::vector<sp<SensorService::SensorDirectConnection>>&
getDirectConnections()2675         SensorService::ConnectionSafeAutolock::getDirectConnections() {
2676     return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2677                                 &mReferencedDirectConnections);
2678 }
2679 
addEventConnectionIfNotPresent(const sp<SensorService::SensorEventConnection> & connection)2680 void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2681         const sp<SensorService::SensorEventConnection>& connection) {
2682     if (mActiveConnections.indexOf(connection) < 0) {
2683         mActiveConnections.add(connection);
2684     }
2685 }
2686 
removeEventConnection(const wp<SensorService::SensorEventConnection> & connection)2687 void SensorService::SensorConnectionHolder::removeEventConnection(
2688         const wp<SensorService::SensorEventConnection>& connection) {
2689     mActiveConnections.remove(connection);
2690 }
2691 
addDirectConnection(const sp<SensorService::SensorDirectConnection> & connection)2692 void SensorService::SensorConnectionHolder::addDirectConnection(
2693         const sp<SensorService::SensorDirectConnection>& connection) {
2694     mDirectConnections.add(connection);
2695 }
2696 
removeDirectConnection(const wp<SensorService::SensorDirectConnection> & connection)2697 void SensorService::SensorConnectionHolder::removeDirectConnection(
2698         const wp<SensorService::SensorDirectConnection>& connection) {
2699     mDirectConnections.remove(connection);
2700 }
2701 
lock(Mutex & mutex)2702 SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2703     return ConnectionSafeAutolock(*this, mutex);
2704 }
2705 
isPackageDebuggable(const String16 & opPackageName)2706 bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2707     bool debugMode = false;
2708     sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2709     if (binder != nullptr) {
2710         sp<content::pm::IPackageManagerNative> packageManager =
2711                 interface_cast<content::pm::IPackageManagerNative>(binder);
2712         if (packageManager != nullptr) {
2713             binder::Status status = packageManager->isPackageDebuggable(
2714                 opPackageName, &debugMode);
2715         }
2716     }
2717     return debugMode;
2718 }
2719 } // namespace android
2720