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