blob: c2e1204b8735050a00d3f0bbfb55af33eef0d5d1 [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];
Anthony Stange3de91192019-11-21 18:35:04 -05001176 if (!ashmem_valid(fd)) {
1177 ALOGE("Supplied Ashmem memory region is invalid");
1178 return nullptr;
1179 }
1180
Peng Xue36e3472016-11-03 11:57:10 -07001181 int size2 = ashmem_get_size_region(fd);
1182 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001183 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001184 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1185 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001186 return nullptr;
1187 }
1188 break;
1189 }
1190 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001191 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001192 break;
1193 default:
1194 ALOGE("Unknown direct connection memory type %d", type);
1195 return nullptr;
1196 }
1197
1198 native_handle_t *clone = native_handle_clone(resource);
1199 if (!clone) {
1200 return nullptr;
1201 }
1202
Brian Duddie967ce172019-06-10 11:08:27 -07001203 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001204 SensorDevice& dev(SensorDevice::getInstance());
1205 int channelHandle = dev.registerDirectChannel(&mem);
1206
1207 if (channelHandle <= 0) {
1208 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1209 } else {
1210 mem.handle = clone;
1211 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1212 }
1213
1214 if (conn == nullptr) {
1215 native_handle_close(clone);
1216 native_handle_delete(clone);
1217 } else {
1218 // add to list of direct connections
1219 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001220 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001221 }
1222 return conn;
1223}
1224
Peng Xudd5c5cb2017-03-16 17:39:43 -07001225int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001226 int32_t handle, int32_t type,
1227 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001228 Mutex::Autolock _l(mLock);
1229
Alexey Polyudov88711e82017-05-23 19:54:04 -07001230 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001231 return PERMISSION_DENIED;
1232 }
1233
1234 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001235 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001236 size_t expectSize = INT32_MAX;
1237 switch (type) {
1238 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1239 isFloat = true;
1240 expectSize = 3;
1241 break;
1242 case AINFO_LOCAL_GRAVITY:
1243 isFloat = true;
1244 expectSize = 1;
1245 break;
1246 case AINFO_DOCK_STATE:
1247 case AINFO_HIGH_PERFORMANCE_MODE:
1248 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1249 isFloat = false;
1250 expectSize = 1;
1251 break;
1252 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001253 // CUSTOM events must only contain float data; it may have variable size
1254 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1255 ints.size() ||
1256 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1257 handle < 0) {
1258 return BAD_VALUE;
1259 }
1260 isFloat = true;
1261 isCustom = true;
1262 expectSize = floats.size();
1263 break;
1264 }
1265
1266 if (!isCustom && handle != -1) {
1267 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001268 }
1269
1270 // three events: first one is begin tag, last one is end tag, the one in the middle
1271 // is the payload.
1272 sensors_event_t event[3];
1273 int64_t timestamp = elapsedRealtimeNano();
1274 for (sensors_event_t* i = event; i < event + 3; i++) {
1275 *i = (sensors_event_t) {
1276 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001277 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001278 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1279 .timestamp = timestamp++,
1280 .additional_info = (additional_info_event_t) {
1281 .serial = 0
1282 }
1283 };
1284 }
1285
1286 event[0].additional_info.type = AINFO_BEGIN;
1287 event[1].additional_info.type = type;
1288 event[2].additional_info.type = AINFO_END;
1289
1290 if (isFloat) {
1291 if (floats.size() != expectSize) {
1292 return BAD_VALUE;
1293 }
1294 for (size_t i = 0; i < expectSize; ++i) {
1295 event[1].additional_info.data_float[i] = floats[i];
1296 }
1297 } else {
1298 if (ints.size() != expectSize) {
1299 return BAD_VALUE;
1300 }
1301 for (size_t i = 0; i < expectSize; ++i) {
1302 event[1].additional_info.data_int32[i] = ints[i];
1303 }
1304 }
1305
1306 SensorDevice& dev(SensorDevice::getInstance());
1307 for (sensors_event_t* i = event; i < event + 3; i++) {
1308 int ret = dev.injectSensorData(i);
1309 if (ret != NO_ERROR) {
1310 return ret;
1311 }
1312 }
1313 return NO_ERROR;
1314}
1315
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001316status_t SensorService::resetToNormalMode() {
1317 Mutex::Autolock _l(mLock);
1318 return resetToNormalModeLocked();
1319}
1320
1321status_t SensorService::resetToNormalModeLocked() {
1322 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001323 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301324 if (err == NO_ERROR) {
1325 mCurrentOperatingMode = NORMAL;
1326 dev.enableAllSensors();
1327 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001328 return err;
1329}
1330
Peng Xu47e96012016-03-28 17:55:56 -07001331void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001332 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001333 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001334 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001335 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001336 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001337 int handle = mActiveSensors.keyAt(i);
1338 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001339 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001340 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1341 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001342 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001343 } else {
1344 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001345 }
Aravind Akella8a969552014-09-28 17:52:41 -07001346 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001347 }
1348 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001349 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001350 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001351 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001352 c, i, handle);
1353
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001354 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001355 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001356 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001357 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001358 delete rec;
1359 size--;
1360 } else {
1361 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001362 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001363 }
Aravind Akella8a969552014-09-28 17:52:41 -07001364 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001365 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001366 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001367 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001368 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001369 }
Peng Xu4f707f82016-09-26 11:28:32 -07001370
Brian Stack793f4642019-04-18 17:21:34 -07001371 {
1372 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1373 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1374 if (iter != sPackageTargetVersion.end()) {
1375 sPackageTargetVersion.erase(iter);
1376 }
1377 }
1378
Peng Xu4f707f82016-09-26 11:28:32 -07001379 SensorDevice& dev(SensorDevice::getInstance());
1380 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001381}
1382
Peng Xue36e3472016-11-03 11:57:10 -07001383void SensorService::cleanupConnection(SensorDirectConnection* c) {
1384 Mutex::Autolock _l(mLock);
1385
1386 SensorDevice& dev(SensorDevice::getInstance());
1387 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001388 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001389}
1390
Peng Xu755c4512016-04-07 23:15:14 -07001391sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001392 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001393}
1394
Mathias Agopianfc328812010-07-14 23:41:37 -07001395status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001396 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001397 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001398 if (mInitCheck != NO_ERROR)
1399 return mInitCheck;
1400
Peng Xu755c4512016-04-07 23:15:14 -07001401 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1402 if (sensor == nullptr ||
1403 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001404 return BAD_VALUE;
1405 }
1406
Brian Duddie967ce172019-06-10 11:08:27 -07001407 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001408 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001409 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001410 return INVALID_OPERATION;
1411 }
1412
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001413 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001414 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001415 rec = new SensorRecord(connection);
1416 mActiveSensors.add(handle, rec);
1417 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001418 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001419 }
Brian Stack26029ee2019-04-22 17:25:49 -07001420
1421 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1422 // the recent event as stale to ensure that the previous event is not sent to a client. This
1423 // ensures on-change events that were generated during a previous sensor activation are not
1424 // erroneously sent to newly connected clients, especially if a second client registers for
1425 // an on-change sensor before the first client receives the updated event. Once an updated
1426 // event is received, the recent events will be marked as current, and any new clients will
1427 // immediately receive the most recent event.
1428 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1429 auto logger = mRecentEvent.find(handle);
1430 if (logger != mRecentEvent.end()) {
1431 logger->second->setLastEventStale();
1432 }
1433 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001434 } else {
1435 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001436 // this sensor is already activated, but we are adding a connection that uses it.
1437 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001438 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001439 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001440 // NOTE: The wake_up flag of this event may get set to
1441 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001442
1443 auto logger = mRecentEvent.find(handle);
1444 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001445 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001446 // Verify that the last sensor event was generated from the current activation
1447 // of the sensor. If not, it is possible for an on-change sensor to receive a
1448 // sensor event that is stale if two clients re-activate the sensor
1449 // simultaneously.
1450 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001451 event.sensor = handle;
1452 if (event.version == sizeof(sensors_event_t)) {
1453 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1454 setWakeLockAcquiredLocked(true);
1455 }
Yi Kong8f313e32018-07-17 14:13:29 -07001456 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001457 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001458 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001459 }
1460 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001461 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001462 }
1463 }
1464 }
1465 }
1466
1467 if (connection->addSensor(handle)) {
1468 BatteryService::enableSensor(connection->getUid(), handle);
1469 // the sensor was added (which means it wasn't already there)
1470 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001471 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001472 } else {
1473 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1474 handle, connection.get());
1475 }
1476
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301477 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001478 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301479 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1480 samplingPeriodNs = maxDelayNs;
1481 }
1482
Aravind Akella724d91d2013-06-27 12:04:23 -07001483 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1484 if (samplingPeriodNs < minDelayNs) {
1485 samplingPeriodNs = minDelayNs;
1486 }
1487
Aravind Akella6c2664a2014-08-13 12:24:50 -07001488 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1489 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001490 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1491
Aravind Akella4949c502015-02-11 15:54:35 -08001492 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001493 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001494
Peng Xu20483c42015-10-26 15:14:43 -07001495 // Call flush() before calling activate() on the sensor. Wait for a first
1496 // flush complete event before sending events on this connection. Ignore
1497 // one-shot sensors which don't support flush(). Ignore on-change sensors
1498 // to maintain the on-change logic (any on-change events except the initial
1499 // one should be trigger by a change in value). Also if this sensor isn't
1500 // already active, don't call flush().
1501 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001502 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001503 rec->getNumConnections() > 1) {
1504 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001505 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001506 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001507 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001508 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001509 } else {
1510 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001511 }
1512 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001513
1514 if (err == NO_ERROR) {
1515 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1516 err = sensor->activate(connection.get(), true);
1517 }
1518
Aravind Akella8a969552014-09-28 17:52:41 -07001519 if (err == NO_ERROR) {
1520 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001521
Brian Stack240d1d62019-05-17 09:49:39 -07001522 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1523 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001524 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1525 }
1526
Peng Xu51224682017-03-10 16:57:27 -08001527 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1528 SensorRegistrationInfo(handle, connection->getPackageName(),
1529 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001530 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001531 }
1532
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001533 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001534 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001535 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001536 }
1537 return err;
1538}
1539
Peng Xu47e96012016-03-28 17:55:56 -07001540status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001541 if (mInitCheck != NO_ERROR)
1542 return mInitCheck;
1543
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001544 Mutex::Autolock _l(mLock);
1545 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001546 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001547 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1548 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001549
1550 }
1551 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001552 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1553 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001554 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001555 }
1556 return err;
1557}
1558
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001559status_t SensorService::cleanupWithoutDisable(
1560 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001561 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001562 return cleanupWithoutDisableLocked(connection, handle);
1563}
1564
1565status_t SensorService::cleanupWithoutDisableLocked(
1566 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001567 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001568 if (rec) {
1569 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001570 if (connection->removeSensor(handle)) {
1571 BatteryService::disableSensor(connection->getUid(), handle);
1572 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001573 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001574 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001575 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001576 }
1577 // see if this sensor becomes inactive
1578 if (rec->removeConnection(connection)) {
1579 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001580 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001581 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001582 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001583 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001584 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001585 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001586}
1587
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001588status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001589 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001590 if (mInitCheck != NO_ERROR)
1591 return mInitCheck;
1592
Peng Xu755c4512016-04-07 23:15:14 -07001593 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1594 if (sensor == nullptr ||
1595 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001596 return BAD_VALUE;
1597 }
1598
Mathias Agopian1cd70002010-07-21 15:59:50 -07001599 if (ns < 0)
1600 return BAD_VALUE;
1601
Mathias Agopian62569ec2011-11-07 21:21:47 -08001602 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1603 if (ns < minDelayNs) {
1604 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001605 }
1606
Mathias Agopianf001c922010-11-11 17:58:51 -08001607 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001608}
1609
Svetoslavb412f6e2015-04-29 16:50:41 -07001610status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1611 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001612 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001613 SensorDevice& dev(SensorDevice::getInstance());
1614 const int halVersion = dev.getHalDeviceVersion();
1615 status_t err(NO_ERROR);
1616 Mutex::Autolock _l(mLock);
1617 // Loop through all sensors for this connection and call flush on each of them.
1618 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1619 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001620 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1621 if (sensor == nullptr) {
1622 continue;
1623 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001624 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1625 ALOGE("flush called on a one-shot sensor");
1626 err = INVALID_OPERATION;
1627 continue;
1628 }
Aravind Akella8493b792014-09-08 15:45:47 -07001629 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001630 // For older devices just increment pending flush count which will send a trivial
1631 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001632 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001633 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001634 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1635 err = INVALID_OPERATION;
1636 continue;
1637 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001638 status_t err_flush = sensor->flush(connection.get(), handle);
1639 if (err_flush == NO_ERROR) {
1640 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001641 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001642 }
1643 err = (err_flush != NO_ERROR) ? err_flush : err;
1644 }
Aravind Akella70018042014-04-07 22:52:37 +00001645 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001646 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001647}
Aravind Akella70018042014-04-07 22:52:37 +00001648
Svetoslavb412f6e2015-04-29 16:50:41 -07001649bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1650 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001651 // Check if a permission is required for this sensor
1652 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001653 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001654 }
1655
Brian Stack793f4642019-04-18 17:21:34 -07001656 const int32_t opCode = sensor.getRequiredAppOp();
1657 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1658 IPCThreadState::self()->getCallingUid(), opPackageName);
Brian Stack6a700f92019-05-08 17:02:53 -07001659 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
Brian Stack793f4642019-04-18 17:21:34 -07001660
Brian Stack793f4642019-04-18 17:21:34 -07001661 bool canAccess = false;
Brian Stack6a700f92019-05-08 17:02:53 -07001662 if (hasPermissionForSensor(sensor)) {
1663 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1664 if (opCode < 0 || appOpAllowed) {
Brian Stack793f4642019-04-18 17:21:34 -07001665 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001666 }
1667 } else if (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1668 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR) {
1669 int targetSdkVersion = getTargetSdkVersion(opPackageName);
1670 // Allow access to the sensor if the application targets pre-Q, which is before the
1671 // requirement to hold the AR permission to access Step Counter and Step Detector events
1672 // was introduced, and the user hasn't revoked the app op.
1673 //
1674 // Verifying the app op is required to ensure that the user hasn't revoked the necessary
1675 // permissions to access the Step Detector and Step Counter when the application targets
1676 // pre-Q. Without this check, if the user revokes the pre-Q install-time GMS Core AR
1677 // permission, the app would still be able to receive Step Counter and Step Detector events.
1678 if (appOpAllowed &&
1679 targetSdkVersion > 0 &&
1680 targetSdkVersion <= __ANDROID_API_P__) {
1681 canAccess = true;
Brian Stack793f4642019-04-18 17:21:34 -07001682 }
1683 }
1684
1685 if (canAccess) {
1686 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1687 } else {
1688 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1689 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1690 }
1691
1692 return canAccess;
1693}
1694
1695bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001696 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001697 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001698
1699 // Runtime permissions can't use the cache as they may change.
1700 if (sensor.isRequiredPermissionRuntime()) {
1701 hasPermission = checkPermission(String16(requiredPermission),
1702 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001703 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001704 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1705 }
Brian Stack793f4642019-04-18 17:21:34 -07001706 return hasPermission;
1707}
Svetoslavb412f6e2015-04-29 16:50:41 -07001708
Brian Stack793f4642019-04-18 17:21:34 -07001709int SensorService::getTargetSdkVersion(const String16& opPackageName) {
1710 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1711 int targetSdkVersion = -1;
1712 auto entry = sPackageTargetVersion.find(opPackageName);
1713 if (entry != sPackageTargetVersion.end()) {
1714 targetSdkVersion = entry->second;
1715 } else {
1716 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1717 if (binder != nullptr) {
1718 sp<content::pm::IPackageManagerNative> packageManager =
1719 interface_cast<content::pm::IPackageManagerNative>(binder);
1720 if (packageManager != nullptr) {
1721 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1722 opPackageName, &targetSdkVersion);
1723 if (!status.isOk()) {
1724 targetSdkVersion = -1;
1725 }
1726 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001727 }
Brian Stack793f4642019-04-18 17:21:34 -07001728 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001729 }
Brian Stack793f4642019-04-18 17:21:34 -07001730 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001731}
1732
Aravind Akella9a844cf2014-02-11 18:58:52 -08001733void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001734 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1735 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001736}
1737
Brian Duddie967ce172019-06-10 11:08:27 -07001738void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001739 if (!mWakeLockAcquired) {
1740 return;
1741 }
1742 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001743 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1744 if (connection->needsWakeLock()) {
1745 releaseLock = false;
1746 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001747 }
1748 }
1749 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001750 setWakeLockAcquiredLocked(false);
1751 }
1752}
1753
1754void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1755 Mutex::Autolock _l(mLock);
1756 connection->writeToSocketFromCache();
1757 if (connection->needsWakeLock()) {
1758 setWakeLockAcquiredLocked(true);
1759 }
1760}
1761
Aravind Akella4949c502015-02-11 15:54:35 -08001762bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001763 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001764}
1765
Brian Stack5180e462019-03-08 17:15:19 -08001766bool SensorService::isOperationPermitted(const String16& opPackageName) {
Peng Xue36e3472016-11-03 11:57:10 -07001767 Mutex::Autolock _l(mLock);
Brian Stack5180e462019-03-08 17:15:19 -08001768 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001769 String8 package(opPackageName);
Brian Stack5180e462019-03-08 17:15:19 -08001770 return isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001771 }
Brian Stack5180e462019-03-08 17:15:19 -08001772 return true;
Peng Xue36e3472016-11-03 11:57:10 -07001773}
1774
Svet Ganove752a5c2018-01-15 17:14:20 -08001775void SensorService::UidPolicy::registerSelf() {
1776 ActivityManager am;
1777 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1778 | ActivityManager::UID_OBSERVER_IDLE
1779 | ActivityManager::UID_OBSERVER_ACTIVE,
1780 ActivityManager::PROCESS_STATE_UNKNOWN,
1781 String16("android"));
1782}
1783
1784void SensorService::UidPolicy::unregisterSelf() {
1785 ActivityManager am;
1786 am.unregisterUidObserver(this);
1787}
1788
1789void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1790 onUidIdle(uid, disabled);
1791}
1792
1793void SensorService::UidPolicy::onUidActive(uid_t uid) {
1794 {
1795 Mutex::Autolock _l(mUidLock);
1796 mActiveUids.insert(uid);
1797 }
1798 sp<SensorService> service = mService.promote();
1799 if (service != nullptr) {
1800 service->setSensorAccess(uid, true);
1801 }
1802}
1803
1804void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1805 bool deleted = false;
1806 {
1807 Mutex::Autolock _l(mUidLock);
1808 if (mActiveUids.erase(uid) > 0) {
1809 deleted = true;
1810 }
1811 }
1812 if (deleted) {
1813 sp<SensorService> service = mService.promote();
1814 if (service != nullptr) {
1815 service->setSensorAccess(uid, false);
1816 }
1817 }
1818}
1819
1820void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1821 updateOverrideUid(uid, active, true);
1822}
1823
1824void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1825 updateOverrideUid(uid, false, false);
1826}
1827
1828void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1829 bool wasActive = false;
1830 bool isActive = false;
1831 {
1832 Mutex::Autolock _l(mUidLock);
1833 wasActive = isUidActiveLocked(uid);
1834 mOverrideUids.erase(uid);
1835 if (insert) {
1836 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1837 }
1838 isActive = isUidActiveLocked(uid);
1839 }
1840 if (wasActive != isActive) {
1841 sp<SensorService> service = mService.promote();
1842 if (service != nullptr) {
1843 service->setSensorAccess(uid, isActive);
1844 }
1845 }
1846}
1847
1848bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1849 // Non-app UIDs are considered always active
1850 if (uid < FIRST_APPLICATION_UID) {
1851 return true;
1852 }
1853 Mutex::Autolock _l(mUidLock);
1854 return isUidActiveLocked(uid);
1855}
1856
1857bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1858 // Non-app UIDs are considered always active
1859 if (uid < FIRST_APPLICATION_UID) {
1860 return true;
1861 }
1862 auto it = mOverrideUids.find(uid);
1863 if (it != mOverrideUids.end()) {
1864 return it->second;
1865 }
1866 return mActiveUids.find(uid) != mActiveUids.end();
1867}
1868
Michael Groover5e1f60b2018-12-04 22:34:29 -08001869void SensorService::SensorPrivacyPolicy::registerSelf() {
1870 SensorPrivacyManager spm;
1871 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1872 spm.addSensorPrivacyListener(this);
1873}
1874
1875void SensorService::SensorPrivacyPolicy::unregisterSelf() {
1876 SensorPrivacyManager spm;
1877 spm.removeSensorPrivacyListener(this);
1878}
1879
1880bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1881 return mSensorPrivacyEnabled;
1882}
1883
1884binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1885 mSensorPrivacyEnabled = enabled;
1886 sp<SensorService> service = mService.promote();
1887 if (service != nullptr) {
1888 if (enabled) {
1889 service->disableAllSensors();
1890 } else {
1891 service->enableAllSensors();
1892 }
1893 }
1894 return binder::Status::ok();
1895}
Brian Duddie967ce172019-06-10 11:08:27 -07001896
1897SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
1898 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
1899 : mConnectionHolder(holder), mAutolock(mutex) {}
1900
1901template<typename ConnectionType>
1902const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
1903 const SortedVector<wp<ConnectionType>>& connectionList,
1904 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
1905 referenceHolder->emplace_back();
1906 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
1907 for (const wp<ConnectionType>& weakConnection : connectionList){
1908 sp<ConnectionType> connection = weakConnection.promote();
1909 if (connection != nullptr) {
1910 connections.push_back(std::move(connection));
1911 }
1912 }
1913 return connections;
1914}
1915
1916const std::vector<sp<SensorService::SensorEventConnection>>&
1917 SensorService::ConnectionSafeAutolock::getActiveConnections() {
1918 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
1919 &mReferencedActiveConnections);
1920}
1921
1922const std::vector<sp<SensorService::SensorDirectConnection>>&
1923 SensorService::ConnectionSafeAutolock::getDirectConnections() {
1924 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
1925 &mReferencedDirectConnections);
1926}
1927
1928void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
1929 const sp<SensorService::SensorEventConnection>& connection) {
1930 if (mActiveConnections.indexOf(connection) < 0) {
1931 mActiveConnections.add(connection);
1932 }
1933}
1934
1935void SensorService::SensorConnectionHolder::removeEventConnection(
1936 const wp<SensorService::SensorEventConnection>& connection) {
1937 mActiveConnections.remove(connection);
1938}
1939
1940void SensorService::SensorConnectionHolder::addDirectConnection(
1941 const sp<SensorService::SensorDirectConnection>& connection) {
1942 mDirectConnections.add(connection);
1943}
1944
1945void SensorService::SensorConnectionHolder::removeDirectConnection(
1946 const wp<SensorService::SensorDirectConnection>& connection) {
1947 mDirectConnections.remove(connection);
1948}
1949
1950SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
1951 return ConnectionSafeAutolock(*this, mutex);
1952}
1953
1954} // namespace android