blob: 14ed73deaf32d32b92c0634e71bed96c99e860aa [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
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 */
Brian Stack793f4642019-04-18 17:21:34 -070016#include <android/content/pm/IPackageManagerNative.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080017#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070018#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070019#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070020#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080021#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070022#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080023#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070024#include <cutils/properties.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070025#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070026#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080027#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070028#include <openssl/digest.h>
29#include <openssl/hmac.h>
30#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070031#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080032#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070033#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070034
Mathias Agopian787ac1b2012-09-18 18:49:18 -070035#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070036#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080037#include "GravitySensor.h"
38#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070039#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080040#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070041#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070042#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080043
Mathias Agopian984826c2011-05-17 22:54:42 -070044#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070045#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080046#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080047#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048#include "SensorRecord.h"
49#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080050
Brian Stack51498e62018-10-03 10:52:21 -070051#include <ctime>
Peng Xueb4d6282015-12-10 18:02:41 -080052#include <inttypes.h>
53#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070054#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080055#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080056#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070057#include <sys/stat.h>
58#include <sys/types.h>
59#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070060
Svet Ganove752a5c2018-01-15 17:14:20 -080061#include <private/android_filesystem_config.h>
62
Mathias Agopianfc328812010-07-14 23:41:37 -070063namespace android {
64// ---------------------------------------------------------------------------
65
Mathias Agopian33015422011-05-27 18:18:13 -070066/*
67 * Notes:
68 *
69 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070070 * - run mag sensor from time to time to force calibration
71 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
72 *
73 */
74
Aravind Akella8ef3c892015-07-10 11:24:28 -070075const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070076uint8_t SensorService::sHmacGlobalKey[128] = {};
77bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070078std::map<String16, int> SensorService::sPackageTargetVersion;
79Mutex SensorService::sPackageTargetVersionLock;
80AppOpsManager SensorService::sAppOpsManager;
Greg Kaiser53ca2e02016-06-21 16:11:14 -070081
82#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
83#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070084#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070085
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070086// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070087static const String16 sDumpPermission("android.permission.DUMP");
88static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080089static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070090
Mathias Agopianfc328812010-07-14 23:41:37 -070091SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070092 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070093 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +090094 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -080095 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -070096}
97
Greg Kaiser53ca2e02016-06-21 16:11:14 -070098bool SensorService::initializeHmacKey() {
99 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
100 if (fd != -1) {
101 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
102 close(fd);
103 if (result == sizeof(sHmacGlobalKey)) {
104 return true;
105 }
106 ALOGW("Unable to read HMAC key; generating new one.");
107 }
108
109 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
110 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
111 return false;
112 }
113
114 // We need to make sure this is only readable to us.
115 bool wroteKey = false;
116 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
117 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
118 S_IRUSR|S_IWUSR);
119 if (fd != -1) {
120 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
121 close(fd);
122 wroteKey = (result == sizeof(sHmacGlobalKey));
123 }
124 if (wroteKey) {
125 ALOGI("Generated new HMAC key.");
126 } else {
127 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
128 "after reboot.");
129 }
130 // Even if we failed to write the key we return true, because we did
131 // initialize the HMAC key.
132 return true;
133}
134
Peng Xu98d30f62016-08-01 18:12:11 -0700135// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
136void SensorService::enableSchedFifoMode() {
137 struct sched_param param = {0};
138 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
139 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
140 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
141 }
142}
143
Peng Xu47e96012016-03-28 17:55:56 -0700144void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000145 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800146 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700147
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700148 sHmacGlobalKeyIsValid = initializeHmacKey();
149
Mathias Agopianf001c922010-11-11 17:58:51 -0800150 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800151 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700152 ssize_t count = dev.getSensorList(&list);
153 if (count > 0) {
154 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700155 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700156 uint32_t virtualSensorsNeeds =
157 (1<<SENSOR_TYPE_GRAVITY) |
158 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700159 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
160 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
161 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700162
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700163 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700164 bool useThisSensor=true;
165
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700166 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700167 case SENSOR_TYPE_ACCELEROMETER:
168 hasAccel = true;
169 break;
170 case SENSOR_TYPE_MAGNETIC_FIELD:
171 hasMag = true;
172 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700173 case SENSOR_TYPE_ORIENTATION:
174 orientationIndex = i;
175 break;
176 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700177 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700178 hasGyro = true;
179 break;
180 case SENSOR_TYPE_GRAVITY:
181 case SENSOR_TYPE_LINEAR_ACCELERATION:
182 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700183 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
184 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
185 if (IGNORE_HARDWARE_FUSION) {
186 useThisSensor = false;
187 } else {
188 virtualSensorsNeeds &= ~(1<<list[i].type);
189 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700190 break;
191 }
Peng Xuf66684a2015-07-23 11:41:53 -0700192 if (useThisSensor) {
193 registerSensor( new HardwareSensor(list[i]) );
194 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700195 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700196
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700197 // it's safe to instantiate the SensorFusion object here
198 // (it wants to be instantiated after h/w sensors have been
199 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700200 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700201
Aravind Akellaf5047892015-07-20 17:29:33 -0700202 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700203 // Add Android virtual sensors if they're not already
204 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700205 bool needRotationVector =
206 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700207
Peng Xu0cc8f802016-04-05 23:46:03 -0700208 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
209 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700210
Peng Xu0cc8f802016-04-05 23:46:03 -0700211 bool needLinearAcceleration =
212 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700213
Peng Xu0cc8f802016-04-05 23:46:03 -0700214 registerSensor(new LinearAccelerationSensor(list, count),
215 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700216
Peng Xu0cc8f802016-04-05 23:46:03 -0700217 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700218 registerSensor( new CorrectedGyroSensor(list, count), true, true);
219 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700220 }
221
Peng Xuf66684a2015-07-23 11:41:53 -0700222 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700223 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
224 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700225
Peng Xu0cc8f802016-04-05 23:46:03 -0700226 bool needGameRotationVector =
227 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
228 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700229 }
230
231 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700232 bool needGeoMagRotationVector =
233 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
234 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700235 }
236
Aravind Akella5466c3d2014-08-22 16:11:10 -0700237 // Check if the device really supports batching by looking at the FIFO event
238 // counts for each sensor.
239 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700240 mSensors.forEachSensor(
241 [&batchingSupported] (const Sensor& s) -> bool {
242 if (s.getFifoMaxEventCount() > 0) {
243 batchingSupported = true;
244 }
245 return !batchingSupported;
246 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700247
248 if (batchingSupported) {
249 // Increase socket buffer size to a max of 100 KB for batching capabilities.
250 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
251 } else {
252 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
253 }
254
255 // Compare the socketBufferSize value against the system limits and limit
256 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700257 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
258 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700259 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700260 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700261 size_t maxSystemSocketBufferSize;
262 sscanf(line, "%zu", &maxSystemSocketBufferSize);
263 if (mSocketBufferSize > maxSystemSocketBufferSize) {
264 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700265 }
266 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700267 if (fp) {
268 fclose(fp);
269 }
270
Aravind Akella9a844cf2014-02-11 18:58:52 -0800271 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700272 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700273 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
274 mSensorEventBuffer = new sensors_event_t[minBufferSize];
275 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700276 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700277 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700278
Aravind Akella18d6d512015-06-18 14:18:28 -0700279 mNextSensorRegIndex = 0;
280 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
281 mLastNSensorRegistrations.push();
282 }
283
284 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700285 mAckReceiver = new SensorEventAckReceiver(this);
286 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700287 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700288
289 // priority can only be changed after run
290 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800291
292 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800293 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800294
295 // Start watching sensor privacy changes
296 mSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800297 }
298 }
299}
300
301void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
Brian Duddie967ce172019-06-10 11:08:27 -0700302 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
303 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
304 if (conn->getUid() == uid) {
305 conn->setSensorAccess(hasAccess);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700306 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700307 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700308}
309
Peng Xu0cc8f802016-04-05 23:46:03 -0700310const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
311 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800312 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700313 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700314 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700315 return s->getSensor();
316 } else {
317 return mSensors.getNonSensor();
318 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800319}
320
Peng Xu6a2d3a02015-12-21 12:00:23 -0800321const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700322 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800323}
324
Peng Xu6a2d3a02015-12-21 12:00:23 -0800325bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700326 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800327
328 const auto i = mRecentEvent.find(handle);
329 if (i != mRecentEvent.end()) {
330 delete i->second;
331 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800332 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700333 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800334}
335
Peng Xu0cc8f802016-04-05 23:46:03 -0700336const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
337 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700338}
339
Peng Xu47e96012016-03-28 17:55:56 -0700340SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800341 for (auto && entry : mRecentEvent) {
342 delete entry.second;
343 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800344 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800345 mSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700346}
347
348status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700349 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700350 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800351 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700352 IPCThreadState::self()->getCallingPid(),
353 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700354 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700355 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700356 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800357 return INVALID_OPERATION;
358 }
Brian Duddie967ce172019-06-10 11:08:27 -0700359 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800360 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700361 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700362 // If already in restricted mode. Ignore.
363 if (mCurrentOperatingMode == RESTRICTED) {
364 return status_t(NO_ERROR);
365 }
366 // If in any mode other than normal, ignore.
367 if (mCurrentOperatingMode != NORMAL) {
368 return INVALID_OPERATION;
369 }
Peng Xue36e3472016-11-03 11:57:10 -0700370
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700371 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800372 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700373 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700374 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700375 return status_t(NO_ERROR);
376 } else if (args.size() == 1 && args[0] == String16("enable")) {
377 // If currently in restricted mode, reset back to NORMAL mode else ignore.
378 if (mCurrentOperatingMode == RESTRICTED) {
379 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800380 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700381 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700382 }
Aravind Akella841a5922015-06-29 12:37:48 -0700383 if (mCurrentOperatingMode == DATA_INJECTION) {
384 resetToNormalModeLocked();
385 }
386 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700387 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700388 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
389 if (mCurrentOperatingMode == NORMAL) {
390 dev.disableAllSensors();
391 status_t err = dev.setMode(DATA_INJECTION);
392 if (err == NO_ERROR) {
393 mCurrentOperatingMode = DATA_INJECTION;
394 } else {
395 // Re-enable sensors.
396 dev.enableAllSensors();
397 }
398 mWhiteListedPackage.setTo(String8(args[1]));
399 return NO_ERROR;
400 } else if (mCurrentOperatingMode == DATA_INJECTION) {
401 // Already in DATA_INJECTION mode. Treat this as a no_op.
402 return NO_ERROR;
403 } else {
404 // Transition to data injection mode supported only from NORMAL mode.
405 return INVALID_OPERATION;
406 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700407 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700408 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700409 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700410 } else {
411 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700412 //
Brian Stack51498e62018-10-03 10:52:21 -0700413 timespec curTime;
414 clock_gettime(CLOCK_REALTIME, &curTime);
415 struct tm* timeinfo = localtime(&(curTime.tv_sec));
416 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
417 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800418 result.append("Sensor Device:\n");
419 result.append(SensorDevice::getInstance().dump().c_str());
420
421 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700422 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700423
Peng Xu6a2d3a02015-12-21 12:00:23 -0800424 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700425 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700426
Peng Xu0cc8f802016-04-05 23:46:03 -0700427 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800428 for (auto&& i : mRecentEvent) {
429 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700430 if (!i.second->isEmpty()) {
431 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
432 i.second->setFormat("normal");
433 } else {
434 i.second->setFormat("mask_data");
435 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800436 // if there is events and sensor does not need special permission.
437 result.appendFormat("%s: ", s->getSensor().getName().string());
438 result.append(i.second->dump().c_str());
439 }
440 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700441
Aravind Akella444f2672015-05-07 12:40:52 -0700442 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700443 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700444 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
445 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700446 if (dev.isSensorActive(handle)) {
447 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
448 getSensorName(handle).string(),
449 handle,
450 mActiveSensors.valueAt(i)->getNumConnections());
451 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700452 }
453
Andreas Gamped4036b62015-07-28 13:49:04 -0700454 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700455 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700456 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
457 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700458 result.appendFormat("Mode :");
459 switch(mCurrentOperatingMode) {
460 case NORMAL:
461 result.appendFormat(" NORMAL\n");
462 break;
463 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700464 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700465 break;
466 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700467 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700468 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800469 result.appendFormat("Sensor Privacy: %s\n",
470 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700471
Brian Duddie967ce172019-06-10 11:08:27 -0700472 const auto& activeConnections = connLock.getActiveConnections();
473 result.appendFormat("%zd active connections\n", activeConnections.size());
474 for (size_t i=0 ; i < activeConnections.size() ; i++) {
475 result.appendFormat("Connection Number: %zu \n", i);
476 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700477 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700478
Brian Duddie967ce172019-06-10 11:08:27 -0700479 const auto& directConnections = connLock.getDirectConnections();
480 result.appendFormat("%zd direct connections\n", directConnections.size());
481 for (size_t i = 0 ; i < directConnections.size() ; i++) {
482 result.appendFormat("Direct connection %zu:\n", i);
483 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700484 }
485
Aravind Akella18d6d512015-06-18 14:18:28 -0700486 result.appendFormat("Previous Registrations:\n");
487 // Log in the reverse chronological order.
488 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
489 SENSOR_REGISTRATIONS_BUF_SIZE;
490 const int startIndex = currentIndex;
491 do {
492 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
493 if (SensorRegistrationInfo::isSentinel(reg_info)) {
494 // Ignore sentinel, proceed to next item.
495 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
496 SENSOR_REGISTRATIONS_BUF_SIZE;
497 continue;
498 }
Peng Xu51224682017-03-10 16:57:27 -0800499 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700500 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
501 SENSOR_REGISTRATIONS_BUF_SIZE;
502 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700503 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700504 }
505 write(fd, result.string(), result.size());
506 return NO_ERROR;
507}
508
Michael Groover5e1f60b2018-12-04 22:34:29 -0800509void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700510 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
511 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800512}
513
Brian Duddie967ce172019-06-10 11:08:27 -0700514void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800515 SensorDevice& dev(SensorDevice::getInstance());
Brian Duddie967ce172019-06-10 11:08:27 -0700516 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
517 connection->stopAll(true /* backupRecord */);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800518 }
519 dev.disableAllSensors();
520 // Clear all pending flush connections for all active sensors. If one of the active
521 // connections has called flush() and the underlying sensor has been disabled before a
522 // flush complete event is returned, we need to remove the connection from this queue.
523 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
524 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
525 }
526}
527
528void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700529 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
530 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800531}
532
Brian Duddie967ce172019-06-10 11:08:27 -0700533void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800534 // sensors should only be enabled if the operating state is not restricted and sensor
535 // privacy is not enabled.
536 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
537 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
538 mCurrentOperatingMode,
539 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
540 return;
541 }
542 SensorDevice& dev(SensorDevice::getInstance());
543 dev.enableAllSensors();
Brian Duddie967ce172019-06-10 11:08:27 -0700544 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
545 connection->recoverAll();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800546 }
547}
548
Brian Duddie967ce172019-06-10 11:08:27 -0700549
Svet Ganove752a5c2018-01-15 17:14:20 -0800550// NOTE: This is a remote API - make sure all args are validated
551status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
552 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
553 return PERMISSION_DENIED;
554 }
555 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
556 return BAD_VALUE;
557 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700558 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800559 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700560 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800561 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700562 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800563 return handleGetUidState(args, out, err);
564 } else if (args.size() == 1 && args[0] == String16("help")) {
565 printHelp(out);
566 return NO_ERROR;
567 }
568 printHelp(err);
569 return BAD_VALUE;
570}
571
Tanmay Patild33a1822019-04-11 18:38:55 -0700572static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800573 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700574 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800575 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700576 ALOGE("Unknown package: '%s'", String8(packageName).string());
577 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800578 return BAD_VALUE;
579 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700580
581 if (userId < 0) {
582 ALOGE("Invalid user: %d", userId);
583 dprintf(err, "Invalid user: %d\n", userId);
584 return BAD_VALUE;
585 }
586
587 uid = multiuser_get_uid(userId, uid);
588 return NO_ERROR;
589}
590
591status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
592 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
593 if (!(args.size() == 3 || args.size() == 5)) {
594 printHelp(err);
595 return BAD_VALUE;
596 }
597
Svet Ganove752a5c2018-01-15 17:14:20 -0800598 bool active = false;
599 if (args[2] == String16("active")) {
600 active = true;
601 } else if ((args[2] != String16("idle"))) {
602 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
603 return BAD_VALUE;
604 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700605
606 int userId = 0;
607 if (args.size() == 5 && args[3] == String16("--user")) {
608 userId = atoi(String8(args[4]));
609 }
610
611 uid_t uid;
612 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
613 return BAD_VALUE;
614 }
615
Svet Ganove752a5c2018-01-15 17:14:20 -0800616 mUidPolicy->addOverrideUid(uid, active);
617 return NO_ERROR;
618}
619
620status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700621 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
622 if (!(args.size() == 2 || args.size() == 4)) {
623 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800624 return BAD_VALUE;
625 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700626
627 int userId = 0;
628 if (args.size() == 4 && args[2] == String16("--user")) {
629 userId = atoi(String8(args[3]));
630 }
631
632 uid_t uid;
633 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
634 return BAD_VALUE;
635 }
636
Svet Ganove752a5c2018-01-15 17:14:20 -0800637 mUidPolicy->removeOverrideUid(uid);
638 return NO_ERROR;
639}
640
641status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700642 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
643 if (!(args.size() == 2 || args.size() == 4)) {
644 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800645 return BAD_VALUE;
646 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700647
648 int userId = 0;
649 if (args.size() == 4 && args[2] == String16("--user")) {
650 userId = atoi(String8(args[3]));
651 }
652
653 uid_t uid;
654 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
655 return BAD_VALUE;
656 }
657
Svet Ganove752a5c2018-01-15 17:14:20 -0800658 if (mUidPolicy->isUidActive(uid)) {
659 return dprintf(out, "active\n");
660 } else {
661 return dprintf(out, "idle\n");
662 }
663}
664
665status_t SensorService::printHelp(int out) {
666 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700667 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
668 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
669 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800670 " help print this message\n");
671}
672
Peng Xu0cc8f802016-04-05 23:46:03 -0700673//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800674void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700675 sensors_event_t const* buffer, const int count) {
676 for (int i=0 ; i<count ; i++) {
677 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700678 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
679 handle = buffer[i].meta_data.sensor;
680 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700681 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700682 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700683 // If this buffer has an event from a one_shot sensor and this connection is registered
684 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700685 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700686 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
687 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800688 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700689 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700690
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700691 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700692 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700693}
694
Peng Xu47e96012016-03-28 17:55:56 -0700695bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000696 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700697
Peng Xueb4d6282015-12-10 18:02:41 -0800698 // each virtual sensor could generate an event per "real" event, that's why we need to size
699 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
700 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700701 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700702 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700703 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700704
Mathias Agopianf001c922010-11-11 17:58:51 -0800705 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700706
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700707 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700708 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700709 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
710 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700711 if(count == DEAD_OBJECT && device.isReconnecting()) {
712 device.reconnect();
713 continue;
714 } else {
715 ALOGE("sensor poll failed (%s)", strerror(-count));
716 break;
717 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700718 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700719
720 // Reset sensors_event_t.flags to zero for all events in the buffer.
721 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700722 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700723 }
Brian Duddie967ce172019-06-10 11:08:27 -0700724 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700725
Aravind Akella9a844cf2014-02-11 18:58:52 -0800726 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
727 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
728 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
729 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
730 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700731 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700732 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700733 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700734 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700735 }
736 }
737
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700738 if (wakeEvents > 0) {
739 if (!mWakeLockAcquired) {
740 setWakeLockAcquiredLocked(true);
741 }
742 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800743 }
Aravind Akella8493b792014-09-08 15:45:47 -0700744 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800745
Mathias Agopianf001c922010-11-11 17:58:51 -0800746 // handle virtual sensors
747 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700748 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700749 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800750 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700751 SensorFusion& fusion(SensorFusion::getInstance());
752 if (fusion.isEnabled()) {
753 for (size_t i=0 ; i<size_t(count) ; i++) {
754 fusion.process(event[i]);
755 }
756 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700757 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700758 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700759 if (count + k >= minBufferSize) {
760 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700761 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700762 count, k, minBufferSize);
763 break;
764 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800765 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700766 sp<SensorInterface> si = mSensors.getInterface(handle);
767 if (si == nullptr) {
768 ALOGE("handle %d is not an valid virtual sensor", handle);
769 continue;
770 }
771
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700772 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700773 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800774 k++;
775 }
776 }
777 }
778 if (k) {
779 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700780 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800781 count += k;
782 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700783 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700784 }
785 }
786 }
787
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700788 // handle backward compatibility for RotationVector sensor
789 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
790 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700791 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700792 // All the 4 components of the quaternion should be available
793 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700794 mSensorEventBuffer[i].data[4] = -1;
795 }
796 }
797 }
798
Brian Duddie967ce172019-06-10 11:08:27 -0700799 // Cache the list of active connections, since we use it in multiple places below but won't
800 // modify it here
801 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
802
Aravind Akella8493b792014-09-08 15:45:47 -0700803 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700804 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
805 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
806 // SensorEventConnection mapped to the corresponding flush_complete_event in
807 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700808 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700809 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
810 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
811 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700812 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700813 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
814 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700815 }
816 }
Peng Xu2576cb62016-01-20 00:22:09 -0800817
818 // handle dynamic sensor meta events, process registration and unregistration of dynamic
819 // sensor based on content of event.
820 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
821 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
822 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
823 const sensor_t& dynamicSensor =
824 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
825 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
826 handle, dynamicSensor.type, dynamicSensor.name);
827
Peng Xu0cc8f802016-04-05 23:46:03 -0700828 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800829 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700830 sensor_t s = dynamicSensor;
831 // make sure the dynamic sensor flag is set
832 s.flags |= DYNAMIC_SENSOR_MASK;
833 // force the handle to be consistent
834 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800835
836 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800837
Peng Xu0cc8f802016-04-05 23:46:03 -0700838 // This will release hold on dynamic sensor meta, so it should be called
839 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700840 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800841 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700842 } else {
843 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
844 }
Peng Xu2576cb62016-01-20 00:22:09 -0800845 } else {
846 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
847 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
848
849 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800850 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800851 ALOGE("Dynamic sensor release error.");
852 }
853
Brian Duddie967ce172019-06-10 11:08:27 -0700854 for (const sp<SensorEventConnection>& connection : activeConnections) {
855 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -0800856 }
857 }
858 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700859 }
860
Aravind Akella9a844cf2014-02-11 18:58:52 -0800861 // Send our events to clients. Check the state of wake lock for each client and release the
862 // lock if none of the clients need it.
863 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -0700864 for (const sp<SensorEventConnection>& connection : activeConnections) {
865 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
866 mMapFlushEventsToConnections);
867 needsWakeLock |= connection->needsWakeLock();
868 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
869 // Early check for one-shot sensors.
870 if (connection->hasOneShotSensors()) {
871 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -0800872 }
873 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700874
Aravind Akella9a844cf2014-02-11 18:58:52 -0800875 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700876 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800877 }
Aravind Akella8493b792014-09-08 15:45:47 -0700878 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700879
Steve Block3c20fbe2012-01-05 23:22:43 +0000880 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800881 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700882 return false;
883}
884
Aravind Akella56ae4262014-07-10 16:01:10 -0700885sp<Looper> SensorService::getLooper() const {
886 return mLooper;
887}
888
Aravind Akellab4373ac2014-10-29 17:55:20 -0700889void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -0700890 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
891 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
892 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -0700893 }
Brian Duddie967ce172019-06-10 11:08:27 -0700894 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -0700895}
896
897void SensorService::setWakeLockAcquiredLocked(bool acquire) {
898 if (acquire) {
899 if (!mWakeLockAcquired) {
900 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
901 mWakeLockAcquired = true;
902 }
903 mLooper->wake();
904 } else {
905 if (mWakeLockAcquired) {
906 release_wake_lock(WAKE_LOCK_NAME);
907 mWakeLockAcquired = false;
908 }
909 }
910}
911
Aravind Akellab4373ac2014-10-29 17:55:20 -0700912bool SensorService::isWakeLockAcquired() {
913 Mutex::Autolock _l(mLock);
914 return mWakeLockAcquired;
915}
916
Aravind Akella56ae4262014-07-10 16:01:10 -0700917bool SensorService::SensorEventAckReceiver::threadLoop() {
918 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700919 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700920 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700921 bool wakeLockAcquired = mService->isWakeLockAcquired();
922 int timeout = -1;
923 if (wakeLockAcquired) timeout = 5000;
924 int ret = looper->pollOnce(timeout);
925 if (ret == ALOOPER_POLL_TIMEOUT) {
926 mService->resetAllWakeLockRefCounts();
927 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700928 } while(!Thread::exitPending());
929 return false;
930}
931
Aravind Akella9a844cf2014-02-11 18:58:52 -0800932void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800933 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800934 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800935 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
936 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800937 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800938 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800939 }
Peng Xu2576cb62016-01-20 00:22:09 -0800940
Peng Xu6a2d3a02015-12-21 12:00:23 -0800941 auto logger = mRecentEvent.find(buffer[i].sensor);
942 if (logger != mRecentEvent.end()) {
943 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800944 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800945 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800946}
947
Peng Xu47e96012016-03-28 17:55:56 -0700948void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800949 struct compar {
950 static int cmp(void const* lhs, void const* rhs) {
951 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
952 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700953 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800954 }
955 };
956 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
957}
958
Mathias Agopian5d270722010-07-19 15:20:39 -0700959String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700960 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700961}
962
Aravind Akellab4099e72013-10-15 15:43:10 -0700963bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700964 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
965 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700966}
967
Aravind Akella9a844cf2014-02-11 18:58:52 -0800968bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700969 int handle = event.sensor;
970 if (event.type == SENSOR_TYPE_META_DATA) {
971 handle = event.meta_data.sensor;
972 }
Peng Xu755c4512016-04-07 23:15:14 -0700973 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
974 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800975}
976
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700977int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
978 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
979 // UUID is not supported for this device.
980 return 0;
981 }
982 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
983 // This sensor can be uniquely identified in the system by
984 // the combination of its type and name.
985 return -1;
986 }
987
988 // We have a dynamic sensor.
989
990 if (!sHmacGlobalKeyIsValid) {
991 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
992 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
993 return 0;
994 }
995
996 // We want each app author/publisher to get a different ID, so that the
997 // same dynamic sensor cannot be tracked across apps by multiple
998 // authors/publishers. So we use both our UUID and our User ID.
999 // Note potential confusion:
1000 // UUID => Universally Unique Identifier.
1001 // UID => User Identifier.
1002 // We refrain from using "uid" except as needed by API to try to
1003 // keep this distinction clear.
1004
1005 auto appUserId = IPCThreadState::self()->getCallingUid();
1006 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1007 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1008 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1009
1010 // Now we use our key on our UUID/app combo to get the hash.
1011 uint8_t hash[EVP_MAX_MD_SIZE];
1012 unsigned int hashLen;
1013 if (HMAC(EVP_sha256(),
1014 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1015 uuidAndApp, sizeof(uuidAndApp),
1016 hash, &hashLen) == nullptr) {
1017 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1018 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1019 return 0;
1020 }
1021
1022 int32_t id = 0;
1023 if (hashLen < sizeof(id)) {
1024 // We never expect this case, but out of paranoia, we handle it.
1025 // Our 'id' length is already quite small, we don't want the
1026 // effective length of it to be even smaller.
1027 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1028 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1029 return 0;
1030 }
1031
1032 // This is almost certainly less than all of 'hash', but it's as secure
1033 // as we can be with our current 'id' length.
1034 memcpy(&id, hash, sizeof(id));
1035
1036 // Note at the beginning of the function that we return the values of
1037 // 0 and -1 to represent special cases. As a result, we can't return
1038 // those as dynamic sensor IDs. If we happened to hash to one of those
1039 // values, we change 'id' so we report as a dynamic sensor, and not as
1040 // one of those special cases.
1041 if (id == -1) {
1042 id = -2;
1043 } else if (id == 0) {
1044 id = 1;
1045 }
1046 return id;
1047}
1048
1049void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1050 for (auto &sensor : sensorList) {
1051 int32_t id = getIdFromUuid(sensor.getUuid());
1052 sensor.setId(id);
1053 }
1054}
1055
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001056Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001057 char value[PROPERTY_VALUE_MAX];
1058 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001059 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001060 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001061 Vector<Sensor> accessibleSensorList;
1062 for (size_t i = 0; i < initialSensorList.size(); i++) {
1063 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001064 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001065 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001066 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001067 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001068}
1069
Peng Xu47e96012016-03-28 17:55:56 -07001070Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001071 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001072 mSensors.forEachSensor(
1073 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001074 if (sensor.isDynamicSensor()) {
1075 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1076 accessibleSensorList.add(sensor);
1077 } else {
1078 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1079 sensor.getName().string(),
1080 sensor.getRequiredPermission().string(),
1081 sensor.getRequiredAppOp());
1082 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001083 }
1084 return true;
1085 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001086 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001087 return accessibleSensorList;
1088}
1089
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001090sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001091 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001092 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1093 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001094 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001095 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001096
1097 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001098 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1099 // operating in DI mode.
1100 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001101 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1102 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001103 }
1104
Mathias Agopian5307d172012-09-18 17:02:43 -07001105 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001106 pid_t pid = IPCThreadState::self()->getCallingPid();
1107
1108 String8 connPackageName =
1109 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1110 String16 connOpPackageName =
1111 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001112 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001113 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001114 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001115 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001116 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001117 // Add the associated file descriptor to the Looper for polling whenever there is data to
1118 // be injected.
1119 result->updateLooperRegistration(mLooper);
1120 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001121 return result;
1122}
1123
Aravind Akella841a5922015-06-29 12:37:48 -07001124int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001125 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001126 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001127}
1128
Peng Xue36e3472016-11-03 11:57:10 -07001129sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1130 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1131 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001132 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001133
Michael Groover5e1f60b2018-12-04 22:34:29 -08001134 // No new direct connections are allowed when sensor privacy is enabled
1135 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1136 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1137 return nullptr;
1138 }
1139
Peng Xue36e3472016-11-03 11:57:10 -07001140 struct sensors_direct_mem_t mem = {
1141 .type = type,
1142 .format = format,
1143 .size = size,
1144 .handle = resource,
1145 };
1146 uid_t uid = IPCThreadState::self()->getCallingUid();
1147
1148 if (mem.handle == nullptr) {
1149 ALOGE("Failed to clone resource handle");
1150 return nullptr;
1151 }
1152
1153 // check format
1154 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1155 ALOGE("Direct channel format %d is unsupported!", format);
1156 return nullptr;
1157 }
1158
1159 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001160 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1161 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001162 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001163 return nullptr;
1164 }
1165 }
1166
1167 // check specific to memory type
1168 switch(type) {
1169 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001170 if (resource->numFds < 1) {
1171 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1172 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1173 return nullptr;
1174 }
Peng Xue36e3472016-11-03 11:57:10 -07001175 int fd = resource->data[0];
1176 int size2 = ashmem_get_size_region(fd);
1177 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001178 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001179 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1180 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001181 return nullptr;
1182 }
1183 break;
1184 }
1185 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001186 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001187 break;
1188 default:
1189 ALOGE("Unknown direct connection memory type %d", type);
1190 return nullptr;
1191 }
1192
1193 native_handle_t *clone = native_handle_clone(resource);
1194 if (!clone) {
1195 return nullptr;
1196 }
1197
Brian Duddie967ce172019-06-10 11:08:27 -07001198 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001199 SensorDevice& dev(SensorDevice::getInstance());
1200 int channelHandle = dev.registerDirectChannel(&mem);
1201
1202 if (channelHandle <= 0) {
1203 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1204 } else {
1205 mem.handle = clone;
1206 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1207 }
1208
1209 if (conn == nullptr) {
1210 native_handle_close(clone);
1211 native_handle_delete(clone);
1212 } else {
1213 // add to list of direct connections
1214 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001215 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001216 }
1217 return conn;
1218}
1219
Peng Xudd5c5cb2017-03-16 17:39:43 -07001220int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001221 int32_t handle, int32_t type,
1222 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001223 Mutex::Autolock _l(mLock);
1224
Alexey Polyudov88711e82017-05-23 19:54:04 -07001225 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001226 return PERMISSION_DENIED;
1227 }
1228
1229 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001230 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001231 size_t expectSize = INT32_MAX;
1232 switch (type) {
1233 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1234 isFloat = true;
1235 expectSize = 3;
1236 break;
1237 case AINFO_LOCAL_GRAVITY:
1238 isFloat = true;
1239 expectSize = 1;
1240 break;
1241 case AINFO_DOCK_STATE:
1242 case AINFO_HIGH_PERFORMANCE_MODE:
1243 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1244 isFloat = false;
1245 expectSize = 1;
1246 break;
1247 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001248 // CUSTOM events must only contain float data; it may have variable size
1249 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1250 ints.size() ||
1251 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1252 handle < 0) {
1253 return BAD_VALUE;
1254 }
1255 isFloat = true;
1256 isCustom = true;
1257 expectSize = floats.size();
1258 break;
1259 }
1260
1261 if (!isCustom && handle != -1) {
1262 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001263 }
1264
1265 // three events: first one is begin tag, last one is end tag, the one in the middle
1266 // is the payload.
1267 sensors_event_t event[3];
1268 int64_t timestamp = elapsedRealtimeNano();
1269 for (sensors_event_t* i = event; i < event + 3; i++) {
1270 *i = (sensors_event_t) {
1271 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001272 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001273 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1274 .timestamp = timestamp++,
1275 .additional_info = (additional_info_event_t) {
1276 .serial = 0
1277 }
1278 };
1279 }
1280
1281 event[0].additional_info.type = AINFO_BEGIN;
1282 event[1].additional_info.type = type;
1283 event[2].additional_info.type = AINFO_END;
1284
1285 if (isFloat) {
1286 if (floats.size() != expectSize) {
1287 return BAD_VALUE;
1288 }
1289 for (size_t i = 0; i < expectSize; ++i) {
1290 event[1].additional_info.data_float[i] = floats[i];
1291 }
1292 } else {
1293 if (ints.size() != expectSize) {
1294 return BAD_VALUE;
1295 }
1296 for (size_t i = 0; i < expectSize; ++i) {
1297 event[1].additional_info.data_int32[i] = ints[i];
1298 }
1299 }
1300
1301 SensorDevice& dev(SensorDevice::getInstance());
1302 for (sensors_event_t* i = event; i < event + 3; i++) {
1303 int ret = dev.injectSensorData(i);
1304 if (ret != NO_ERROR) {
1305 return ret;
1306 }
1307 }
1308 return NO_ERROR;
1309}
1310
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001311status_t SensorService::resetToNormalMode() {
1312 Mutex::Autolock _l(mLock);
1313 return resetToNormalModeLocked();
1314}
1315
1316status_t SensorService::resetToNormalModeLocked() {
1317 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001318 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301319 if (err == NO_ERROR) {
1320 mCurrentOperatingMode = NORMAL;
1321 dev.enableAllSensors();
1322 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001323 return err;
1324}
1325
Peng Xu47e96012016-03-28 17:55:56 -07001326void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001327 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001328 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001329 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001330 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001331 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001332 int handle = mActiveSensors.keyAt(i);
1333 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001334 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001335 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1336 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001337 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001338 } else {
1339 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001340 }
Aravind Akella8a969552014-09-28 17:52:41 -07001341 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001342 }
1343 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001344 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001345 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001346 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001347 c, i, handle);
1348
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001349 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001350 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001351 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001352 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001353 delete rec;
1354 size--;
1355 } else {
1356 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001357 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001358 }
Aravind Akella8a969552014-09-28 17:52:41 -07001359 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001360 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001361 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001362 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001363 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001364 }
Peng Xu4f707f82016-09-26 11:28:32 -07001365
Brian Stack793f4642019-04-18 17:21:34 -07001366 {
1367 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1368 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1369 if (iter != sPackageTargetVersion.end()) {
1370 sPackageTargetVersion.erase(iter);
1371 }
1372 }
1373
Peng Xu4f707f82016-09-26 11:28:32 -07001374 SensorDevice& dev(SensorDevice::getInstance());
1375 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001376}
1377
Peng Xue36e3472016-11-03 11:57:10 -07001378void SensorService::cleanupConnection(SensorDirectConnection* c) {
1379 Mutex::Autolock _l(mLock);
1380
1381 SensorDevice& dev(SensorDevice::getInstance());
1382 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001383 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001384}
1385
Peng Xu755c4512016-04-07 23:15:14 -07001386sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001387 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001388}
1389
Mathias Agopianfc328812010-07-14 23:41:37 -07001390status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001391 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001392 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001393 if (mInitCheck != NO_ERROR)
1394 return mInitCheck;
1395
Peng Xu755c4512016-04-07 23:15:14 -07001396 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1397 if (sensor == nullptr ||
1398 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001399 return BAD_VALUE;
1400 }
1401
Brian Duddie967ce172019-06-10 11:08:27 -07001402 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001403 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001404 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001405 return INVALID_OPERATION;
1406 }
1407
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001408 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001409 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001410 rec = new SensorRecord(connection);
1411 mActiveSensors.add(handle, rec);
1412 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001413 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001414 }
Brian Stack26029ee2019-04-22 17:25:49 -07001415
1416 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1417 // the recent event as stale to ensure that the previous event is not sent to a client. This
1418 // ensures on-change events that were generated during a previous sensor activation are not
1419 // erroneously sent to newly connected clients, especially if a second client registers for
1420 // an on-change sensor before the first client receives the updated event. Once an updated
1421 // event is received, the recent events will be marked as current, and any new clients will
1422 // immediately receive the most recent event.
1423 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1424 auto logger = mRecentEvent.find(handle);
1425 if (logger != mRecentEvent.end()) {
1426 logger->second->setLastEventStale();
1427 }
1428 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001429 } else {
1430 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001431 // this sensor is already activated, but we are adding a connection that uses it.
1432 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001433 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001434 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001435 // NOTE: The wake_up flag of this event may get set to
1436 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001437
1438 auto logger = mRecentEvent.find(handle);
1439 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001440 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001441 // Verify that the last sensor event was generated from the current activation
1442 // of the sensor. If not, it is possible for an on-change sensor to receive a
1443 // sensor event that is stale if two clients re-activate the sensor
1444 // simultaneously.
1445 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001446 event.sensor = handle;
1447 if (event.version == sizeof(sensors_event_t)) {
1448 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1449 setWakeLockAcquiredLocked(true);
1450 }
Yi Kong8f313e32018-07-17 14:13:29 -07001451 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001452 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001453 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001454 }
1455 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001456 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001457 }
1458 }
1459 }
1460 }
1461
1462 if (connection->addSensor(handle)) {
1463 BatteryService::enableSensor(connection->getUid(), handle);
1464 // the sensor was added (which means it wasn't already there)
1465 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001466 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001467 } else {
1468 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1469 handle, connection.get());
1470 }
1471
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301472 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001473 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301474 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1475 samplingPeriodNs = maxDelayNs;
1476 }
1477
Aravind Akella724d91d2013-06-27 12:04:23 -07001478 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1479 if (samplingPeriodNs < minDelayNs) {
1480 samplingPeriodNs = minDelayNs;
1481 }
1482
Aravind Akella6c2664a2014-08-13 12:24:50 -07001483 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1484 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001485 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1486
Aravind Akella4949c502015-02-11 15:54:35 -08001487 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001488 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001489
Peng Xu20483c42015-10-26 15:14:43 -07001490 // Call flush() before calling activate() on the sensor. Wait for a first
1491 // flush complete event before sending events on this connection. Ignore
1492 // one-shot sensors which don't support flush(). Ignore on-change sensors
1493 // to maintain the on-change logic (any on-change events except the initial
1494 // one should be trigger by a change in value). Also if this sensor isn't
1495 // already active, don't call flush().
1496 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001497 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001498 rec->getNumConnections() > 1) {
1499 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001500 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001501 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001502 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001503 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001504 } else {
1505 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001506 }
1507 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001508
1509 if (err == NO_ERROR) {
1510 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1511 err = sensor->activate(connection.get(), true);
1512 }
1513
Aravind Akella8a969552014-09-28 17:52:41 -07001514 if (err == NO_ERROR) {
1515 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001516
Brian Stack240d1d62019-05-17 09:49:39 -07001517 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1518 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001519 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1520 }
1521
Peng Xu51224682017-03-10 16:57:27 -08001522 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1523 SensorRegistrationInfo(handle, connection->getPackageName(),
1524 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001525 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001526 }
1527
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001528 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001529 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001530 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001531 }
1532 return err;
1533}
1534
Peng Xu47e96012016-03-28 17:55:56 -07001535status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001536 if (mInitCheck != NO_ERROR)
1537 return mInitCheck;
1538
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001539 Mutex::Autolock _l(mLock);
1540 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001541 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001542 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1543 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001544
1545 }
1546 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001547 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1548 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001549 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001550 }
1551 return err;
1552}
1553
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001554status_t SensorService::cleanupWithoutDisable(
1555 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001556 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001557 return cleanupWithoutDisableLocked(connection, handle);
1558}
1559
1560status_t SensorService::cleanupWithoutDisableLocked(
1561 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001562 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001563 if (rec) {
1564 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001565 if (connection->removeSensor(handle)) {
1566 BatteryService::disableSensor(connection->getUid(), handle);
1567 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001568 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001569 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001570 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001571 }
1572 // see if this sensor becomes inactive
1573 if (rec->removeConnection(connection)) {
1574 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001575 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001576 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001577 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001578 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001579 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001580 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001581}
1582
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001583status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001584 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001585 if (mInitCheck != NO_ERROR)
1586 return mInitCheck;
1587
Peng Xu755c4512016-04-07 23:15:14 -07001588 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1589 if (sensor == nullptr ||
1590 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001591 return BAD_VALUE;
1592 }
1593
Mathias Agopian1cd70002010-07-21 15:59:50 -07001594 if (ns < 0)
1595 return BAD_VALUE;
1596
Mathias Agopian62569ec2011-11-07 21:21:47 -08001597 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1598 if (ns < minDelayNs) {
1599 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001600 }
1601
Mathias Agopianf001c922010-11-11 17:58:51 -08001602 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001603}
1604
Svetoslavb412f6e2015-04-29 16:50:41 -07001605status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1606 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001607 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001608 SensorDevice& dev(SensorDevice::getInstance());
1609 const int halVersion = dev.getHalDeviceVersion();
1610 status_t err(NO_ERROR);
1611 Mutex::Autolock _l(mLock);
1612 // Loop through all sensors for this connection and call flush on each of them.
1613 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1614 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001615 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1616 if (sensor == nullptr) {
1617 continue;
1618 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001619 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1620 ALOGE("flush called on a one-shot sensor");
1621 err = INVALID_OPERATION;
1622 continue;
1623 }
Aravind Akella8493b792014-09-08 15:45:47 -07001624 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001625 // For older devices just increment pending flush count which will send a trivial
1626 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001627 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001628 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001629 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1630 err = INVALID_OPERATION;
1631 continue;
1632 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001633 status_t err_flush = sensor->flush(connection.get(), handle);
1634 if (err_flush == NO_ERROR) {
1635 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001636 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001637 }
1638 err = (err_flush != NO_ERROR) ? err_flush : err;
1639 }
Aravind Akella70018042014-04-07 22:52:37 +00001640 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001641 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001642}
Aravind Akella70018042014-04-07 22:52:37 +00001643
Svetoslavb412f6e2015-04-29 16:50:41 -07001644bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1645 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001646 // Check if a permission is required for this sensor
1647 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001648 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001649 }
1650
Brian Stack793f4642019-04-18 17:21:34 -07001651 const int32_t opCode = sensor.getRequiredAppOp();
1652 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1653 IPCThreadState::self()->getCallingUid(), opPackageName);
Brian Stack6a700f92019-05-08 17:02:53 -07001654 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
Brian Stack793f4642019-04-18 17:21:34 -07001655
Brian Stack793f4642019-04-18 17:21:34 -07001656 bool canAccess = false;
Brian Stack6a700f92019-05-08 17:02:53 -07001657 if (hasPermissionForSensor(sensor)) {
1658 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1659 if (opCode < 0 || appOpAllowed) {
Brian Stack793f4642019-04-18 17:21:34 -07001660 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001661 }
1662 } else if (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1663 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR) {
1664 int targetSdkVersion = getTargetSdkVersion(opPackageName);
1665 // Allow access to the sensor if the application targets pre-Q, which is before the
1666 // requirement to hold the AR permission to access Step Counter and Step Detector events
1667 // was introduced, and the user hasn't revoked the app op.
1668 //
1669 // Verifying the app op is required to ensure that the user hasn't revoked the necessary
1670 // permissions to access the Step Detector and Step Counter when the application targets
1671 // pre-Q. Without this check, if the user revokes the pre-Q install-time GMS Core AR
1672 // permission, the app would still be able to receive Step Counter and Step Detector events.
1673 if (appOpAllowed &&
1674 targetSdkVersion > 0 &&
1675 targetSdkVersion <= __ANDROID_API_P__) {
1676 canAccess = true;
Brian Stack793f4642019-04-18 17:21:34 -07001677 }
1678 }
1679
1680 if (canAccess) {
1681 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1682 } else {
1683 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1684 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1685 }
1686
1687 return canAccess;
1688}
1689
1690bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001691 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001692 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001693
1694 // Runtime permissions can't use the cache as they may change.
1695 if (sensor.isRequiredPermissionRuntime()) {
1696 hasPermission = checkPermission(String16(requiredPermission),
1697 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001698 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001699 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1700 }
Brian Stack793f4642019-04-18 17:21:34 -07001701 return hasPermission;
1702}
Svetoslavb412f6e2015-04-29 16:50:41 -07001703
Brian Stack793f4642019-04-18 17:21:34 -07001704int SensorService::getTargetSdkVersion(const String16& opPackageName) {
1705 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1706 int targetSdkVersion = -1;
1707 auto entry = sPackageTargetVersion.find(opPackageName);
1708 if (entry != sPackageTargetVersion.end()) {
1709 targetSdkVersion = entry->second;
1710 } else {
1711 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1712 if (binder != nullptr) {
1713 sp<content::pm::IPackageManagerNative> packageManager =
1714 interface_cast<content::pm::IPackageManagerNative>(binder);
1715 if (packageManager != nullptr) {
1716 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1717 opPackageName, &targetSdkVersion);
1718 if (!status.isOk()) {
1719 targetSdkVersion = -1;
1720 }
1721 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001722 }
Brian Stack793f4642019-04-18 17:21:34 -07001723 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001724 }
Brian Stack793f4642019-04-18 17:21:34 -07001725 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001726}
1727
Aravind Akella9a844cf2014-02-11 18:58:52 -08001728void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001729 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1730 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001731}
1732
Brian Duddie967ce172019-06-10 11:08:27 -07001733void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001734 if (!mWakeLockAcquired) {
1735 return;
1736 }
1737 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001738 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1739 if (connection->needsWakeLock()) {
1740 releaseLock = false;
1741 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001742 }
1743 }
1744 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001745 setWakeLockAcquiredLocked(false);
1746 }
1747}
1748
1749void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1750 Mutex::Autolock _l(mLock);
1751 connection->writeToSocketFromCache();
1752 if (connection->needsWakeLock()) {
1753 setWakeLockAcquiredLocked(true);
1754 }
1755}
1756
Aravind Akella4949c502015-02-11 15:54:35 -08001757bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001758 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001759}
1760
Brian Stack5180e462019-03-08 17:15:19 -08001761bool SensorService::isOperationPermitted(const String16& opPackageName) {
Peng Xue36e3472016-11-03 11:57:10 -07001762 Mutex::Autolock _l(mLock);
Brian Stack5180e462019-03-08 17:15:19 -08001763 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001764 String8 package(opPackageName);
Brian Stack5180e462019-03-08 17:15:19 -08001765 return isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001766 }
Brian Stack5180e462019-03-08 17:15:19 -08001767 return true;
Peng Xue36e3472016-11-03 11:57:10 -07001768}
1769
Svet Ganove752a5c2018-01-15 17:14:20 -08001770void SensorService::UidPolicy::registerSelf() {
1771 ActivityManager am;
1772 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1773 | ActivityManager::UID_OBSERVER_IDLE
1774 | ActivityManager::UID_OBSERVER_ACTIVE,
1775 ActivityManager::PROCESS_STATE_UNKNOWN,
1776 String16("android"));
1777}
1778
1779void SensorService::UidPolicy::unregisterSelf() {
1780 ActivityManager am;
1781 am.unregisterUidObserver(this);
1782}
1783
1784void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1785 onUidIdle(uid, disabled);
1786}
1787
1788void SensorService::UidPolicy::onUidActive(uid_t uid) {
1789 {
1790 Mutex::Autolock _l(mUidLock);
1791 mActiveUids.insert(uid);
1792 }
1793 sp<SensorService> service = mService.promote();
1794 if (service != nullptr) {
1795 service->setSensorAccess(uid, true);
1796 }
1797}
1798
1799void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1800 bool deleted = false;
1801 {
1802 Mutex::Autolock _l(mUidLock);
1803 if (mActiveUids.erase(uid) > 0) {
1804 deleted = true;
1805 }
1806 }
1807 if (deleted) {
1808 sp<SensorService> service = mService.promote();
1809 if (service != nullptr) {
1810 service->setSensorAccess(uid, false);
1811 }
1812 }
1813}
1814
1815void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1816 updateOverrideUid(uid, active, true);
1817}
1818
1819void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1820 updateOverrideUid(uid, false, false);
1821}
1822
1823void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1824 bool wasActive = false;
1825 bool isActive = false;
1826 {
1827 Mutex::Autolock _l(mUidLock);
1828 wasActive = isUidActiveLocked(uid);
1829 mOverrideUids.erase(uid);
1830 if (insert) {
1831 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1832 }
1833 isActive = isUidActiveLocked(uid);
1834 }
1835 if (wasActive != isActive) {
1836 sp<SensorService> service = mService.promote();
1837 if (service != nullptr) {
1838 service->setSensorAccess(uid, isActive);
1839 }
1840 }
1841}
1842
1843bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1844 // Non-app UIDs are considered always active
1845 if (uid < FIRST_APPLICATION_UID) {
1846 return true;
1847 }
1848 Mutex::Autolock _l(mUidLock);
1849 return isUidActiveLocked(uid);
1850}
1851
1852bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1853 // Non-app UIDs are considered always active
1854 if (uid < FIRST_APPLICATION_UID) {
1855 return true;
1856 }
1857 auto it = mOverrideUids.find(uid);
1858 if (it != mOverrideUids.end()) {
1859 return it->second;
1860 }
1861 return mActiveUids.find(uid) != mActiveUids.end();
1862}
1863
Michael Groover5e1f60b2018-12-04 22:34:29 -08001864void SensorService::SensorPrivacyPolicy::registerSelf() {
1865 SensorPrivacyManager spm;
1866 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1867 spm.addSensorPrivacyListener(this);
1868}
1869
1870void SensorService::SensorPrivacyPolicy::unregisterSelf() {
1871 SensorPrivacyManager spm;
1872 spm.removeSensorPrivacyListener(this);
1873}
1874
1875bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1876 return mSensorPrivacyEnabled;
1877}
1878
1879binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1880 mSensorPrivacyEnabled = enabled;
1881 sp<SensorService> service = mService.promote();
1882 if (service != nullptr) {
1883 if (enabled) {
1884 service->disableAllSensors();
1885 } else {
1886 service->enableAllSensors();
1887 }
1888 }
1889 return binder::Status::ok();
1890}
Brian Duddie967ce172019-06-10 11:08:27 -07001891
1892SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
1893 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
1894 : mConnectionHolder(holder), mAutolock(mutex) {}
1895
1896template<typename ConnectionType>
1897const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
1898 const SortedVector<wp<ConnectionType>>& connectionList,
1899 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
1900 referenceHolder->emplace_back();
1901 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
1902 for (const wp<ConnectionType>& weakConnection : connectionList){
1903 sp<ConnectionType> connection = weakConnection.promote();
1904 if (connection != nullptr) {
1905 connections.push_back(std::move(connection));
1906 }
1907 }
1908 return connections;
1909}
1910
1911const std::vector<sp<SensorService::SensorEventConnection>>&
1912 SensorService::ConnectionSafeAutolock::getActiveConnections() {
1913 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
1914 &mReferencedActiveConnections);
1915}
1916
1917const std::vector<sp<SensorService::SensorDirectConnection>>&
1918 SensorService::ConnectionSafeAutolock::getDirectConnections() {
1919 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
1920 &mReferencedDirectConnections);
1921}
1922
1923void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
1924 const sp<SensorService::SensorEventConnection>& connection) {
1925 if (mActiveConnections.indexOf(connection) < 0) {
1926 mActiveConnections.add(connection);
1927 }
1928}
1929
1930void SensorService::SensorConnectionHolder::removeEventConnection(
1931 const wp<SensorService::SensorEventConnection>& connection) {
1932 mActiveConnections.remove(connection);
1933}
1934
1935void SensorService::SensorConnectionHolder::addDirectConnection(
1936 const sp<SensorService::SensorDirectConnection>& connection) {
1937 mDirectConnections.add(connection);
1938}
1939
1940void SensorService::SensorConnectionHolder::removeDirectConnection(
1941 const wp<SensorService::SensorDirectConnection>& connection) {
1942 mDirectConnections.remove(connection);
1943}
1944
1945SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
1946 return ConnectionSafeAutolock(*this, mutex);
1947}
1948
1949} // namespace android