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