blob: 942b7ae76a1b1b1f2c1e7805c81bfe28bf72e4fa [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 */
Anh Phamaf91a912021-02-10 14:10:53 +010016#include <android-base/strings.h>
Brian Stack793f4642019-04-18 17:21:34 -070017#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080018#include <android/util/ProtoOutputStream.h>
19#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080020#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070021#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070022#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070023#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080024#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070025#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080026#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070027#include <cutils/properties.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070028#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070029#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080030#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070031#include <openssl/digest.h>
32#include <openssl/hmac.h>
33#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070034#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080035#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070036#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070037
Mathias Agopian787ac1b2012-09-18 18:49:18 -070038#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070039#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080040#include "GravitySensor.h"
41#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070042#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080043#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070044#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070045#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080046
Mathias Agopian984826c2011-05-17 22:54:42 -070047#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070048#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080049#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080050#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080051#include "SensorRecord.h"
52#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080053
Brian Stack51498e62018-10-03 10:52:21 -070054#include <ctime>
Peng Xueb4d6282015-12-10 18:02:41 -080055#include <inttypes.h>
56#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070057#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080058#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080059#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070060#include <sys/stat.h>
61#include <sys/types.h>
62#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070063
Svet Ganove752a5c2018-01-15 17:14:20 -080064#include <private/android_filesystem_config.h>
65
Mathias Agopianfc328812010-07-14 23:41:37 -070066namespace android {
67// ---------------------------------------------------------------------------
68
Mathias Agopian33015422011-05-27 18:18:13 -070069/*
70 * Notes:
71 *
72 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070073 * - run mag sensor from time to time to force calibration
74 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
75 *
76 */
77
Aravind Akella8ef3c892015-07-10 11:24:28 -070078const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070079uint8_t SensorService::sHmacGlobalKey[128] = {};
80bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070081std::map<String16, int> SensorService::sPackageTargetVersion;
82Mutex SensorService::sPackageTargetVersionLock;
Anthony Stange07eb4212020-08-28 14:50:28 -040083String16 SensorService::sSensorInterfaceDescriptorPrefix =
84 String16("android.frameworks.sensorservice@");
Brian Stack793f4642019-04-18 17:21:34 -070085AppOpsManager SensorService::sAppOpsManager;
Greg Kaiser53ca2e02016-06-21 16:11:14 -070086
87#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
88#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070089#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070090
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070091// Permissions.
Anh Phamaf91a912021-02-10 14:10:53 +010092static const String16 sAccessHighSensorSamplingRatePermission(
93 "android.permission.HIGH_SAMPLING_RATE_SENSORS");
Peng Xudd5c5cb2017-03-16 17:39:43 -070094static const String16 sDumpPermission("android.permission.DUMP");
95static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080096static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070097
Mathias Agopianfc328812010-07-14 23:41:37 -070098SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070099 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -0700100 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +0900101 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800102 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700103}
104
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700105bool SensorService::initializeHmacKey() {
106 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
107 if (fd != -1) {
108 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
109 close(fd);
110 if (result == sizeof(sHmacGlobalKey)) {
111 return true;
112 }
113 ALOGW("Unable to read HMAC key; generating new one.");
114 }
115
116 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
117 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
118 return false;
119 }
120
121 // We need to make sure this is only readable to us.
122 bool wroteKey = false;
123 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
124 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
125 S_IRUSR|S_IWUSR);
126 if (fd != -1) {
127 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
128 close(fd);
129 wroteKey = (result == sizeof(sHmacGlobalKey));
130 }
131 if (wroteKey) {
132 ALOGI("Generated new HMAC key.");
133 } else {
134 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
135 "after reboot.");
136 }
137 // Even if we failed to write the key we return true, because we did
138 // initialize the HMAC key.
139 return true;
140}
141
Peng Xu98d30f62016-08-01 18:12:11 -0700142// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
143void SensorService::enableSchedFifoMode() {
144 struct sched_param param = {0};
145 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
146 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
147 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
148 }
149}
150
Peng Xu47e96012016-03-28 17:55:56 -0700151void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000152 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800153 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700154
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700155 sHmacGlobalKeyIsValid = initializeHmacKey();
156
Mathias Agopianf001c922010-11-11 17:58:51 -0800157 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800158 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700159 ssize_t count = dev.getSensorList(&list);
160 if (count > 0) {
161 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700162 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700163 uint32_t virtualSensorsNeeds =
164 (1<<SENSOR_TYPE_GRAVITY) |
165 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700166 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
167 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
168 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700169
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700170 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700171 bool useThisSensor=true;
172
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700173 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700174 case SENSOR_TYPE_ACCELEROMETER:
175 hasAccel = true;
176 break;
177 case SENSOR_TYPE_MAGNETIC_FIELD:
178 hasMag = true;
179 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700180 case SENSOR_TYPE_ORIENTATION:
181 orientationIndex = i;
182 break;
183 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700184 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700185 hasGyro = true;
186 break;
187 case SENSOR_TYPE_GRAVITY:
188 case SENSOR_TYPE_LINEAR_ACCELERATION:
189 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700190 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
191 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
192 if (IGNORE_HARDWARE_FUSION) {
193 useThisSensor = false;
194 } else {
195 virtualSensorsNeeds &= ~(1<<list[i].type);
196 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700197 break;
198 }
Peng Xuf66684a2015-07-23 11:41:53 -0700199 if (useThisSensor) {
200 registerSensor( new HardwareSensor(list[i]) );
201 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700202 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700203
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700204 // it's safe to instantiate the SensorFusion object here
205 // (it wants to be instantiated after h/w sensors have been
206 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700207 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700208
Aravind Akellaf5047892015-07-20 17:29:33 -0700209 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700210 // Add Android virtual sensors if they're not already
211 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700212 bool needRotationVector =
213 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700214
Peng Xu0cc8f802016-04-05 23:46:03 -0700215 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
216 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700217
Peng Xu0cc8f802016-04-05 23:46:03 -0700218 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700219 registerSensor( new CorrectedGyroSensor(list, count), true, true);
220 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700221 }
222
Peng Xuf66684a2015-07-23 11:41:53 -0700223 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700224 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
225 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700226
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800227 bool needLinearAcceleration =
228 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
229 registerSensor(new LinearAccelerationSensor(list, count),
230 !needLinearAcceleration, true);
231
Peng Xu0cc8f802016-04-05 23:46:03 -0700232 bool needGameRotationVector =
233 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
234 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700235 }
236
237 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700238 bool needGeoMagRotationVector =
239 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
240 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700241 }
242
Aravind Akella5466c3d2014-08-22 16:11:10 -0700243 // Check if the device really supports batching by looking at the FIFO event
244 // counts for each sensor.
245 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700246 mSensors.forEachSensor(
247 [&batchingSupported] (const Sensor& s) -> bool {
248 if (s.getFifoMaxEventCount() > 0) {
249 batchingSupported = true;
250 }
251 return !batchingSupported;
252 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700253
254 if (batchingSupported) {
255 // Increase socket buffer size to a max of 100 KB for batching capabilities.
256 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
257 } else {
258 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
259 }
260
261 // Compare the socketBufferSize value against the system limits and limit
262 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700263 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
264 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700265 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700266 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700267 size_t maxSystemSocketBufferSize;
268 sscanf(line, "%zu", &maxSystemSocketBufferSize);
269 if (mSocketBufferSize > maxSystemSocketBufferSize) {
270 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700271 }
272 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700273 if (fp) {
274 fclose(fp);
275 }
276
Aravind Akella9a844cf2014-02-11 18:58:52 -0800277 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700278 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700279 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
280 mSensorEventBuffer = new sensors_event_t[minBufferSize];
281 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700282 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700283 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700284
Aravind Akella18d6d512015-06-18 14:18:28 -0700285 mNextSensorRegIndex = 0;
286 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
287 mLastNSensorRegistrations.push();
288 }
289
290 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700291 mAckReceiver = new SensorEventAckReceiver(this);
292 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700293 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700294
295 // priority can only be changed after run
296 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800297
298 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800299 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800300
301 // Start watching sensor privacy changes
302 mSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800303 }
304 }
305}
306
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700307void SensorService::onUidStateChanged(uid_t uid, UidState state) {
308 SensorDevice& dev(SensorDevice::getInstance());
309
Brian Duddie967ce172019-06-10 11:08:27 -0700310 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700311 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700312 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700313 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700314 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700315 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700316
317 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
318 if (conn->getUid() == uid) {
319 // Update sensor subscriptions if needed
320 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
321 conn->onSensorAccessChanged(hasAccess);
322 }
323 }
324}
325
326bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
327 Mutex::Autolock _l(mLock);
328 return hasSensorAccessLocked(uid, opPackageName);
329}
330
331bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
332 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
333 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700334}
335
Peng Xu0cc8f802016-04-05 23:46:03 -0700336const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
337 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800338 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700339 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700340 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700341 return s->getSensor();
342 } else {
343 return mSensors.getNonSensor();
344 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800345}
346
Peng Xu6a2d3a02015-12-21 12:00:23 -0800347const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700348 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800349}
350
Peng Xu6a2d3a02015-12-21 12:00:23 -0800351bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700352 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800353
354 const auto i = mRecentEvent.find(handle);
355 if (i != mRecentEvent.end()) {
356 delete i->second;
357 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800358 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700359 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800360}
361
Peng Xu0cc8f802016-04-05 23:46:03 -0700362const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
363 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700364}
365
Peng Xu47e96012016-03-28 17:55:56 -0700366SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800367 for (auto && entry : mRecentEvent) {
368 delete entry.second;
369 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800370 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800371 mSensorPrivacyPolicy->unregisterSelf();
Anh Pham5198c992021-02-10 14:15:30 +0100372 for (auto const& [userId, policy] : mMicSensorPrivacyPolicies) {
373 policy->unregisterSelf();
374 }
Peng Xu47e96012016-03-28 17:55:56 -0700375}
376
377status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700378 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700379 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800380 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700381 IPCThreadState::self()->getCallingPid(),
382 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700383 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700384 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700385 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800386 return INVALID_OPERATION;
387 }
Brian Duddie967ce172019-06-10 11:08:27 -0700388 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800389 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700390 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700391 // If already in restricted mode. Ignore.
392 if (mCurrentOperatingMode == RESTRICTED) {
393 return status_t(NO_ERROR);
394 }
395 // If in any mode other than normal, ignore.
396 if (mCurrentOperatingMode != NORMAL) {
397 return INVALID_OPERATION;
398 }
Peng Xue36e3472016-11-03 11:57:10 -0700399
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700400 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800401 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700402 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700403 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700404 return status_t(NO_ERROR);
405 } else if (args.size() == 1 && args[0] == String16("enable")) {
406 // If currently in restricted mode, reset back to NORMAL mode else ignore.
407 if (mCurrentOperatingMode == RESTRICTED) {
408 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800409 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700410 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700411 }
Aravind Akella841a5922015-06-29 12:37:48 -0700412 if (mCurrentOperatingMode == DATA_INJECTION) {
413 resetToNormalModeLocked();
414 }
415 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700416 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700417 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
418 if (mCurrentOperatingMode == NORMAL) {
419 dev.disableAllSensors();
420 status_t err = dev.setMode(DATA_INJECTION);
421 if (err == NO_ERROR) {
422 mCurrentOperatingMode = DATA_INJECTION;
423 } else {
424 // Re-enable sensors.
425 dev.enableAllSensors();
426 }
427 mWhiteListedPackage.setTo(String8(args[1]));
428 return NO_ERROR;
429 } else if (mCurrentOperatingMode == DATA_INJECTION) {
430 // Already in DATA_INJECTION mode. Treat this as a no_op.
431 return NO_ERROR;
432 } else {
433 // Transition to data injection mode supported only from NORMAL mode.
434 return INVALID_OPERATION;
435 }
Mike Ma24743862020-01-29 00:36:55 -0800436 } else if (args.size() == 1 && args[0] == String16("--proto")) {
437 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700438 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700439 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700440 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700441 } else {
442 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700443 //
Brian Stack51498e62018-10-03 10:52:21 -0700444 timespec curTime;
445 clock_gettime(CLOCK_REALTIME, &curTime);
446 struct tm* timeinfo = localtime(&(curTime.tv_sec));
447 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
448 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800449 result.append("Sensor Device:\n");
450 result.append(SensorDevice::getInstance().dump().c_str());
451
452 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700453 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700454
Peng Xu6a2d3a02015-12-21 12:00:23 -0800455 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700456 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700457
Peng Xu0cc8f802016-04-05 23:46:03 -0700458 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800459 for (auto&& i : mRecentEvent) {
460 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700461 if (!i.second->isEmpty()) {
462 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
463 i.second->setFormat("normal");
464 } else {
465 i.second->setFormat("mask_data");
466 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800467 // if there is events and sensor does not need special permission.
468 result.appendFormat("%s: ", s->getSensor().getName().string());
469 result.append(i.second->dump().c_str());
470 }
471 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700472
Aravind Akella444f2672015-05-07 12:40:52 -0700473 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700474 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700475 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
476 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700477 if (dev.isSensorActive(handle)) {
478 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
479 getSensorName(handle).string(),
480 handle,
481 mActiveSensors.valueAt(i)->getNumConnections());
482 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700483 }
484
Andreas Gamped4036b62015-07-28 13:49:04 -0700485 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700486 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700487 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
488 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700489 result.appendFormat("Mode :");
490 switch(mCurrentOperatingMode) {
491 case NORMAL:
492 result.appendFormat(" NORMAL\n");
493 break;
494 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700495 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700496 break;
497 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700498 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700499 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800500 result.appendFormat("Sensor Privacy: %s\n",
501 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700502
Brian Duddie967ce172019-06-10 11:08:27 -0700503 const auto& activeConnections = connLock.getActiveConnections();
504 result.appendFormat("%zd active connections\n", activeConnections.size());
505 for (size_t i=0 ; i < activeConnections.size() ; i++) {
506 result.appendFormat("Connection Number: %zu \n", i);
507 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700508 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700509
Brian Duddie967ce172019-06-10 11:08:27 -0700510 const auto& directConnections = connLock.getDirectConnections();
511 result.appendFormat("%zd direct connections\n", directConnections.size());
512 for (size_t i = 0 ; i < directConnections.size() ; i++) {
513 result.appendFormat("Direct connection %zu:\n", i);
514 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700515 }
516
Aravind Akella18d6d512015-06-18 14:18:28 -0700517 result.appendFormat("Previous Registrations:\n");
518 // Log in the reverse chronological order.
519 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
520 SENSOR_REGISTRATIONS_BUF_SIZE;
521 const int startIndex = currentIndex;
522 do {
523 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
524 if (SensorRegistrationInfo::isSentinel(reg_info)) {
525 // Ignore sentinel, proceed to next item.
526 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
527 SENSOR_REGISTRATIONS_BUF_SIZE;
528 continue;
529 }
Peng Xu51224682017-03-10 16:57:27 -0800530 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700531 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
532 SENSOR_REGISTRATIONS_BUF_SIZE;
533 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700534 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700535 }
536 write(fd, result.string(), result.size());
537 return NO_ERROR;
538}
539
Mike Ma24743862020-01-29 00:36:55 -0800540/**
541 * Dump debugging information as android.service.SensorServiceProto protobuf message using
542 * ProtoOutputStream.
543 *
544 * See proto definition and some notes about ProtoOutputStream in
545 * frameworks/base/core/proto/android/service/sensor_service.proto
546 */
547status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
548 using namespace service::SensorServiceProto;
549 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800550 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
551 if (!mSensors.hasAnySensor()) {
552 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
553 }
Mike Ma24743862020-01-29 00:36:55 -0800554 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
555
556 timespec curTime;
557 clock_gettime(CLOCK_REALTIME, &curTime);
558 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
559
560 // Write SensorDeviceProto
561 uint64_t token = proto.start(SENSOR_DEVICE);
562 SensorDevice::getInstance().dump(&proto);
563 proto.end(token);
564
565 // Write SensorListProto
566 token = proto.start(SENSORS);
567 mSensors.dump(&proto);
568 proto.end(token);
569
570 // Write SensorFusionProto
571 token = proto.start(FUSION_STATE);
572 SensorFusion::getInstance().dump(&proto);
573 proto.end(token);
574
575 // Write SensorEventsProto
576 token = proto.start(SENSOR_EVENTS);
577 for (auto&& i : mRecentEvent) {
578 sp<SensorInterface> s = mSensors.getInterface(i.first);
579 if (!i.second->isEmpty()) {
580 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
581 "normal" : "mask_data");
582 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
583 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
584 std::string(s->getSensor().getName().string()));
585 i.second->dump(&proto);
586 proto.end(mToken);
587 }
588 }
589 proto.end(token);
590
591 // Write ActiveSensorProto
592 SensorDevice& dev = SensorDevice::getInstance();
593 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
594 int handle = mActiveSensors.keyAt(i);
595 if (dev.isSensorActive(handle)) {
596 token = proto.start(ACTIVE_SENSORS);
597 proto.write(service::ActiveSensorProto::NAME,
598 std::string(getSensorName(handle).string()));
599 proto.write(service::ActiveSensorProto::HANDLE, handle);
600 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
601 int(mActiveSensors.valueAt(i)->getNumConnections()));
602 proto.end(token);
603 }
604 }
605
606 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
607 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
608 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
609
610 switch(mCurrentOperatingMode) {
611 case NORMAL:
612 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
613 break;
614 case RESTRICTED:
615 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
616 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
617 break;
618 case DATA_INJECTION:
619 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
620 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
621 break;
622 default:
623 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
624 }
625 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
626
627 // Write repeated SensorEventConnectionProto
628 const auto& activeConnections = connLock->getActiveConnections();
629 for (size_t i = 0; i < activeConnections.size(); i++) {
630 token = proto.start(ACTIVE_CONNECTIONS);
631 activeConnections[i]->dump(&proto);
632 proto.end(token);
633 }
634
635 // Write repeated SensorDirectConnectionProto
636 const auto& directConnections = connLock->getDirectConnections();
637 for (size_t i = 0 ; i < directConnections.size() ; i++) {
638 token = proto.start(DIRECT_CONNECTIONS);
639 directConnections[i]->dump(&proto);
640 proto.end(token);
641 }
642
643 // Write repeated SensorRegistrationInfoProto
644 const int startIndex = mNextSensorRegIndex;
645 int curr = startIndex;
646 do {
647 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
648 if (SensorRegistrationInfo::isSentinel(reg_info)) {
649 // Ignore sentinel, proceed to next item.
650 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
651 continue;
652 }
653 token = proto.start(PREVIOUS_REGISTRATIONS);
654 reg_info.dump(&proto);
655 proto.end(token);
656 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
657 } while (startIndex != curr);
658
659 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
660}
661
Michael Groover5e1f60b2018-12-04 22:34:29 -0800662void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700663 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
664 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800665}
666
Brian Duddie967ce172019-06-10 11:08:27 -0700667void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800668 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700669 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
670 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
671 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800672 }
673 dev.disableAllSensors();
674 // Clear all pending flush connections for all active sensors. If one of the active
675 // connections has called flush() and the underlying sensor has been disabled before a
676 // flush complete event is returned, we need to remove the connection from this queue.
677 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
678 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
679 }
680}
681
682void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700683 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
684 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800685}
686
Brian Duddie967ce172019-06-10 11:08:27 -0700687void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800688 // sensors should only be enabled if the operating state is not restricted and sensor
689 // privacy is not enabled.
690 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
691 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
692 mCurrentOperatingMode,
693 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
694 return;
695 }
696 SensorDevice& dev(SensorDevice::getInstance());
697 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700698 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
699 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
700 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800701 }
702}
703
Anh Pham5198c992021-02-10 14:15:30 +0100704void SensorService::capRates(userid_t userId) {
705 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
706 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
707 if (conn->getUserId() == userId) {
708 conn->onMicSensorAccessChanged(true);
709 }
710 }
711
712 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
713 if (conn->getUserId() == userId) {
714 conn->onMicSensorAccessChanged(true);
715 }
716 }
717}
718
719void SensorService::uncapRates(userid_t userId) {
720 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
721 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
722 if (conn->getUserId() == userId) {
723 conn->onMicSensorAccessChanged(false);
724 }
725 }
726
727 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
728 if (conn->getUserId() == userId) {
729 conn->onMicSensorAccessChanged(false);
730 }
731 }
732}
Brian Duddie967ce172019-06-10 11:08:27 -0700733
Svet Ganove752a5c2018-01-15 17:14:20 -0800734// NOTE: This is a remote API - make sure all args are validated
735status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
736 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
737 return PERMISSION_DENIED;
738 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700739 if (args.size() == 0) {
740 return BAD_INDEX;
741 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800742 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
743 return BAD_VALUE;
744 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700745 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800746 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700747 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800748 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700749 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800750 return handleGetUidState(args, out, err);
751 } else if (args.size() == 1 && args[0] == String16("help")) {
752 printHelp(out);
753 return NO_ERROR;
754 }
755 printHelp(err);
756 return BAD_VALUE;
757}
758
Tanmay Patild33a1822019-04-11 18:38:55 -0700759static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800760 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700761 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800762 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700763 ALOGE("Unknown package: '%s'", String8(packageName).string());
764 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800765 return BAD_VALUE;
766 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700767
768 if (userId < 0) {
769 ALOGE("Invalid user: %d", userId);
770 dprintf(err, "Invalid user: %d\n", userId);
771 return BAD_VALUE;
772 }
773
774 uid = multiuser_get_uid(userId, uid);
775 return NO_ERROR;
776}
777
778status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
779 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
780 if (!(args.size() == 3 || args.size() == 5)) {
781 printHelp(err);
782 return BAD_VALUE;
783 }
784
Svet Ganove752a5c2018-01-15 17:14:20 -0800785 bool active = false;
786 if (args[2] == String16("active")) {
787 active = true;
788 } else if ((args[2] != String16("idle"))) {
789 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
790 return BAD_VALUE;
791 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700792
793 int userId = 0;
794 if (args.size() == 5 && args[3] == String16("--user")) {
795 userId = atoi(String8(args[4]));
796 }
797
798 uid_t uid;
799 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
800 return BAD_VALUE;
801 }
802
Svet Ganove752a5c2018-01-15 17:14:20 -0800803 mUidPolicy->addOverrideUid(uid, active);
804 return NO_ERROR;
805}
806
807status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700808 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
809 if (!(args.size() == 2 || args.size() == 4)) {
810 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800811 return BAD_VALUE;
812 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700813
814 int userId = 0;
815 if (args.size() == 4 && args[2] == String16("--user")) {
816 userId = atoi(String8(args[3]));
817 }
818
819 uid_t uid;
820 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
821 return BAD_VALUE;
822 }
823
Svet Ganove752a5c2018-01-15 17:14:20 -0800824 mUidPolicy->removeOverrideUid(uid);
825 return NO_ERROR;
826}
827
828status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700829 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
830 if (!(args.size() == 2 || args.size() == 4)) {
831 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800832 return BAD_VALUE;
833 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700834
835 int userId = 0;
836 if (args.size() == 4 && args[2] == String16("--user")) {
837 userId = atoi(String8(args[3]));
838 }
839
840 uid_t uid;
841 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
842 return BAD_VALUE;
843 }
844
Svet Ganove752a5c2018-01-15 17:14:20 -0800845 if (mUidPolicy->isUidActive(uid)) {
846 return dprintf(out, "active\n");
847 } else {
848 return dprintf(out, "idle\n");
849 }
850}
851
852status_t SensorService::printHelp(int out) {
853 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700854 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
855 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
856 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800857 " help print this message\n");
858}
859
Peng Xu0cc8f802016-04-05 23:46:03 -0700860//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800861void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700862 sensors_event_t const* buffer, const int count) {
863 for (int i=0 ; i<count ; i++) {
864 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700865 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
866 handle = buffer[i].meta_data.sensor;
867 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700868 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700869 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700870 // If this buffer has an event from a one_shot sensor and this connection is registered
871 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700872 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700873 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
874 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800875 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700876 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700877
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700878 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700879 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700880}
881
Peng Xu47e96012016-03-28 17:55:56 -0700882bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000883 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700884
Peng Xueb4d6282015-12-10 18:02:41 -0800885 // each virtual sensor could generate an event per "real" event, that's why we need to size
886 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
887 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700888 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700889 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700890 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700891
Mathias Agopianf001c922010-11-11 17:58:51 -0800892 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700893
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700894 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700895 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700896 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
897 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700898 if(count == DEAD_OBJECT && device.isReconnecting()) {
899 device.reconnect();
900 continue;
901 } else {
902 ALOGE("sensor poll failed (%s)", strerror(-count));
903 break;
904 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700905 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700906
907 // Reset sensors_event_t.flags to zero for all events in the buffer.
908 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700909 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700910 }
Brian Duddie967ce172019-06-10 11:08:27 -0700911 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700912
Aravind Akella9a844cf2014-02-11 18:58:52 -0800913 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
914 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
915 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
916 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
917 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700918 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700919 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700920 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700921 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700922 }
923 }
924
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700925 if (wakeEvents > 0) {
926 if (!mWakeLockAcquired) {
927 setWakeLockAcquiredLocked(true);
928 }
929 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800930 }
Aravind Akella8493b792014-09-08 15:45:47 -0700931 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800932
Mathias Agopianf001c922010-11-11 17:58:51 -0800933 // handle virtual sensors
934 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700935 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700936 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800937 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700938 SensorFusion& fusion(SensorFusion::getInstance());
939 if (fusion.isEnabled()) {
940 for (size_t i=0 ; i<size_t(count) ; i++) {
941 fusion.process(event[i]);
942 }
943 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700944 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700945 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700946 if (count + k >= minBufferSize) {
947 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700948 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700949 count, k, minBufferSize);
950 break;
951 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800952 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700953 sp<SensorInterface> si = mSensors.getInterface(handle);
954 if (si == nullptr) {
955 ALOGE("handle %d is not an valid virtual sensor", handle);
956 continue;
957 }
958
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700959 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700960 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800961 k++;
962 }
963 }
964 }
965 if (k) {
966 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700967 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800968 count += k;
969 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700970 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700971 }
972 }
973 }
974
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700975 // handle backward compatibility for RotationVector sensor
976 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
977 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700978 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700979 // All the 4 components of the quaternion should be available
980 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700981 mSensorEventBuffer[i].data[4] = -1;
982 }
983 }
984 }
985
Brian Duddie967ce172019-06-10 11:08:27 -0700986 // Cache the list of active connections, since we use it in multiple places below but won't
987 // modify it here
988 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
989
Aravind Akella8493b792014-09-08 15:45:47 -0700990 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700991 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
992 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
993 // SensorEventConnection mapped to the corresponding flush_complete_event in
994 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700995 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700996 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
997 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
998 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700999 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -07001000 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
1001 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001002 }
1003 }
Peng Xu2576cb62016-01-20 00:22:09 -08001004
1005 // handle dynamic sensor meta events, process registration and unregistration of dynamic
1006 // sensor based on content of event.
1007 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
1008 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
1009 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1010 const sensor_t& dynamicSensor =
1011 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
1012 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
1013 handle, dynamicSensor.type, dynamicSensor.name);
1014
Peng Xu0cc8f802016-04-05 23:46:03 -07001015 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -08001016 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -07001017 sensor_t s = dynamicSensor;
1018 // make sure the dynamic sensor flag is set
1019 s.flags |= DYNAMIC_SENSOR_MASK;
1020 // force the handle to be consistent
1021 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -08001022
1023 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -08001024
Peng Xu0cc8f802016-04-05 23:46:03 -07001025 // This will release hold on dynamic sensor meta, so it should be called
1026 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -07001027 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001028 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -07001029 } else {
1030 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
1031 }
Peng Xu2576cb62016-01-20 00:22:09 -08001032 } else {
1033 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1034 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1035
1036 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001037 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -08001038 ALOGE("Dynamic sensor release error.");
1039 }
1040
Brian Duddie967ce172019-06-10 11:08:27 -07001041 for (const sp<SensorEventConnection>& connection : activeConnections) {
1042 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001043 }
1044 }
1045 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001046 }
1047
Aravind Akella9a844cf2014-02-11 18:58:52 -08001048 // Send our events to clients. Check the state of wake lock for each client and release the
1049 // lock if none of the clients need it.
1050 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001051 for (const sp<SensorEventConnection>& connection : activeConnections) {
1052 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1053 mMapFlushEventsToConnections);
1054 needsWakeLock |= connection->needsWakeLock();
1055 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1056 // Early check for one-shot sensors.
1057 if (connection->hasOneShotSensors()) {
1058 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001059 }
1060 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001061
Aravind Akella9a844cf2014-02-11 18:58:52 -08001062 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001063 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001064 }
Aravind Akella8493b792014-09-08 15:45:47 -07001065 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001066
Steve Block3c20fbe2012-01-05 23:22:43 +00001067 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001068 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001069 return false;
1070}
1071
Aravind Akella56ae4262014-07-10 16:01:10 -07001072sp<Looper> SensorService::getLooper() const {
1073 return mLooper;
1074}
1075
Aravind Akellab4373ac2014-10-29 17:55:20 -07001076void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001077 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1078 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1079 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001080 }
Brian Duddie967ce172019-06-10 11:08:27 -07001081 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001082}
1083
1084void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1085 if (acquire) {
1086 if (!mWakeLockAcquired) {
1087 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1088 mWakeLockAcquired = true;
1089 }
1090 mLooper->wake();
1091 } else {
1092 if (mWakeLockAcquired) {
1093 release_wake_lock(WAKE_LOCK_NAME);
1094 mWakeLockAcquired = false;
1095 }
1096 }
1097}
1098
Aravind Akellab4373ac2014-10-29 17:55:20 -07001099bool SensorService::isWakeLockAcquired() {
1100 Mutex::Autolock _l(mLock);
1101 return mWakeLockAcquired;
1102}
1103
Aravind Akella56ae4262014-07-10 16:01:10 -07001104bool SensorService::SensorEventAckReceiver::threadLoop() {
1105 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001106 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001107 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001108 bool wakeLockAcquired = mService->isWakeLockAcquired();
1109 int timeout = -1;
1110 if (wakeLockAcquired) timeout = 5000;
1111 int ret = looper->pollOnce(timeout);
1112 if (ret == ALOOPER_POLL_TIMEOUT) {
1113 mService->resetAllWakeLockRefCounts();
1114 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001115 } while(!Thread::exitPending());
1116 return false;
1117}
1118
Aravind Akella9a844cf2014-02-11 18:58:52 -08001119void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001120 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001121 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001122 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1123 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001124 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001125 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001126 }
Peng Xu2576cb62016-01-20 00:22:09 -08001127
Peng Xu6a2d3a02015-12-21 12:00:23 -08001128 auto logger = mRecentEvent.find(buffer[i].sensor);
1129 if (logger != mRecentEvent.end()) {
1130 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001131 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001132 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001133}
1134
Peng Xu47e96012016-03-28 17:55:56 -07001135void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001136 struct compar {
1137 static int cmp(void const* lhs, void const* rhs) {
1138 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1139 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001140 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001141 }
1142 };
1143 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1144}
1145
Mathias Agopian5d270722010-07-19 15:20:39 -07001146String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001147 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001148}
1149
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001150String8 SensorService::getSensorStringType(int handle) const {
1151 return mSensors.getStringType(handle);
1152}
1153
Aravind Akellab4099e72013-10-15 15:43:10 -07001154bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001155 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1156 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001157}
1158
Aravind Akella9a844cf2014-02-11 18:58:52 -08001159bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001160 int handle = event.sensor;
1161 if (event.type == SENSOR_TYPE_META_DATA) {
1162 handle = event.meta_data.sensor;
1163 }
Peng Xu755c4512016-04-07 23:15:14 -07001164 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1165 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001166}
1167
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001168int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1169 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1170 // UUID is not supported for this device.
1171 return 0;
1172 }
1173 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1174 // This sensor can be uniquely identified in the system by
1175 // the combination of its type and name.
1176 return -1;
1177 }
1178
1179 // We have a dynamic sensor.
1180
1181 if (!sHmacGlobalKeyIsValid) {
1182 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1183 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1184 return 0;
1185 }
1186
1187 // We want each app author/publisher to get a different ID, so that the
1188 // same dynamic sensor cannot be tracked across apps by multiple
1189 // authors/publishers. So we use both our UUID and our User ID.
1190 // Note potential confusion:
1191 // UUID => Universally Unique Identifier.
1192 // UID => User Identifier.
1193 // We refrain from using "uid" except as needed by API to try to
1194 // keep this distinction clear.
1195
1196 auto appUserId = IPCThreadState::self()->getCallingUid();
1197 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1198 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1199 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1200
1201 // Now we use our key on our UUID/app combo to get the hash.
1202 uint8_t hash[EVP_MAX_MD_SIZE];
1203 unsigned int hashLen;
1204 if (HMAC(EVP_sha256(),
1205 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1206 uuidAndApp, sizeof(uuidAndApp),
1207 hash, &hashLen) == nullptr) {
1208 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1209 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1210 return 0;
1211 }
1212
1213 int32_t id = 0;
1214 if (hashLen < sizeof(id)) {
1215 // We never expect this case, but out of paranoia, we handle it.
1216 // Our 'id' length is already quite small, we don't want the
1217 // effective length of it to be even smaller.
1218 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1219 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1220 return 0;
1221 }
1222
1223 // This is almost certainly less than all of 'hash', but it's as secure
1224 // as we can be with our current 'id' length.
1225 memcpy(&id, hash, sizeof(id));
1226
1227 // Note at the beginning of the function that we return the values of
1228 // 0 and -1 to represent special cases. As a result, we can't return
1229 // those as dynamic sensor IDs. If we happened to hash to one of those
1230 // values, we change 'id' so we report as a dynamic sensor, and not as
1231 // one of those special cases.
1232 if (id == -1) {
1233 id = -2;
1234 } else if (id == 0) {
1235 id = 1;
1236 }
1237 return id;
1238}
1239
1240void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1241 for (auto &sensor : sensorList) {
1242 int32_t id = getIdFromUuid(sensor.getUuid());
1243 sensor.setId(id);
1244 }
1245}
1246
Anh Pham4e291332021-02-10 14:17:56 +01001247Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -07001248 char value[PROPERTY_VALUE_MAX];
1249 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001250 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001251 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001252 Vector<Sensor> accessibleSensorList;
Anh Pham4e291332021-02-10 14:17:56 +01001253
1254 bool isCapped = isRateCappedBasedOnPermission(opPackageName);
Aravind Akella70018042014-04-07 22:52:37 +00001255 for (size_t i = 0; i < initialSensorList.size(); i++) {
1256 Sensor sensor = initialSensorList[i];
Anh Pham4e291332021-02-10 14:17:56 +01001257 if (isCapped && isSensorInCappedSet(sensor.getType())) {
1258 sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
1259 sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
1260 }
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001261 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001262 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001263 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001264 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001265}
1266
Peng Xu47e96012016-03-28 17:55:56 -07001267Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001268 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001269 mSensors.forEachSensor(
1270 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001271 if (sensor.isDynamicSensor()) {
1272 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1273 accessibleSensorList.add(sensor);
1274 } else {
1275 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1276 sensor.getName().string(),
1277 sensor.getRequiredPermission().string(),
1278 sensor.getRequiredAppOp());
1279 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001280 }
1281 return true;
1282 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001283 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001284 return accessibleSensorList;
1285}
1286
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001287sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001288 int requestedMode, const String16& opPackageName, const String16& attributionTag) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001289 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1290 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001291 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001292 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001293
1294 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001295 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1296 // operating in DI mode.
1297 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001298 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1299 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001300 }
1301
Mathias Agopian5307d172012-09-18 17:02:43 -07001302 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001303 pid_t pid = IPCThreadState::self()->getCallingPid();
1304
1305 String8 connPackageName =
1306 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1307 String16 connOpPackageName =
1308 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1309 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001310 requestedMode == DATA_INJECTION, connOpPackageName, attributionTag));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001311 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001312 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001313 // Add the associated file descriptor to the Looper for polling whenever there is data to
1314 // be injected.
1315 result->updateLooperRegistration(mLooper);
1316 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001317 return result;
1318}
1319
Aravind Akella841a5922015-06-29 12:37:48 -07001320int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001321 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001322 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001323}
1324
Peng Xue36e3472016-11-03 11:57:10 -07001325sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1326 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1327 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001328 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001329
Michael Groover5e1f60b2018-12-04 22:34:29 -08001330 // No new direct connections are allowed when sensor privacy is enabled
1331 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1332 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1333 return nullptr;
1334 }
1335
Peng Xue36e3472016-11-03 11:57:10 -07001336 struct sensors_direct_mem_t mem = {
1337 .type = type,
1338 .format = format,
1339 .size = size,
1340 .handle = resource,
1341 };
1342 uid_t uid = IPCThreadState::self()->getCallingUid();
1343
1344 if (mem.handle == nullptr) {
1345 ALOGE("Failed to clone resource handle");
1346 return nullptr;
1347 }
1348
1349 // check format
1350 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1351 ALOGE("Direct channel format %d is unsupported!", format);
1352 return nullptr;
1353 }
1354
1355 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001356 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1357 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001358 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001359 return nullptr;
1360 }
1361 }
1362
1363 // check specific to memory type
1364 switch(type) {
1365 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001366 if (resource->numFds < 1) {
1367 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1368 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1369 return nullptr;
1370 }
Peng Xue36e3472016-11-03 11:57:10 -07001371 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001372 if (!ashmem_valid(fd)) {
1373 ALOGE("Supplied Ashmem memory region is invalid");
1374 return nullptr;
1375 }
1376
Peng Xue36e3472016-11-03 11:57:10 -07001377 int size2 = ashmem_get_size_region(fd);
1378 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001379 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001380 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1381 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001382 return nullptr;
1383 }
1384 break;
1385 }
1386 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001387 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001388 break;
1389 default:
1390 ALOGE("Unknown direct connection memory type %d", type);
1391 return nullptr;
1392 }
1393
1394 native_handle_t *clone = native_handle_clone(resource);
1395 if (!clone) {
1396 return nullptr;
1397 }
1398
Brian Duddie967ce172019-06-10 11:08:27 -07001399 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001400 SensorDevice& dev(SensorDevice::getInstance());
1401 int channelHandle = dev.registerDirectChannel(&mem);
1402
1403 if (channelHandle <= 0) {
1404 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1405 } else {
1406 mem.handle = clone;
1407 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1408 }
1409
1410 if (conn == nullptr) {
1411 native_handle_close(clone);
1412 native_handle_delete(clone);
1413 } else {
1414 // add to list of direct connections
1415 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001416 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001417 }
1418 return conn;
1419}
1420
Peng Xudd5c5cb2017-03-16 17:39:43 -07001421int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001422 int32_t handle, int32_t type,
1423 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001424 Mutex::Autolock _l(mLock);
1425
Alexey Polyudov88711e82017-05-23 19:54:04 -07001426 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001427 return PERMISSION_DENIED;
1428 }
1429
1430 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001431 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001432 size_t expectSize = INT32_MAX;
1433 switch (type) {
1434 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1435 isFloat = true;
1436 expectSize = 3;
1437 break;
1438 case AINFO_LOCAL_GRAVITY:
1439 isFloat = true;
1440 expectSize = 1;
1441 break;
1442 case AINFO_DOCK_STATE:
1443 case AINFO_HIGH_PERFORMANCE_MODE:
1444 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1445 isFloat = false;
1446 expectSize = 1;
1447 break;
1448 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001449 // CUSTOM events must only contain float data; it may have variable size
1450 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1451 ints.size() ||
1452 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1453 handle < 0) {
1454 return BAD_VALUE;
1455 }
1456 isFloat = true;
1457 isCustom = true;
1458 expectSize = floats.size();
1459 break;
1460 }
1461
1462 if (!isCustom && handle != -1) {
1463 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001464 }
1465
1466 // three events: first one is begin tag, last one is end tag, the one in the middle
1467 // is the payload.
1468 sensors_event_t event[3];
1469 int64_t timestamp = elapsedRealtimeNano();
1470 for (sensors_event_t* i = event; i < event + 3; i++) {
1471 *i = (sensors_event_t) {
1472 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001473 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001474 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1475 .timestamp = timestamp++,
1476 .additional_info = (additional_info_event_t) {
1477 .serial = 0
1478 }
1479 };
1480 }
1481
1482 event[0].additional_info.type = AINFO_BEGIN;
1483 event[1].additional_info.type = type;
1484 event[2].additional_info.type = AINFO_END;
1485
1486 if (isFloat) {
1487 if (floats.size() != expectSize) {
1488 return BAD_VALUE;
1489 }
1490 for (size_t i = 0; i < expectSize; ++i) {
1491 event[1].additional_info.data_float[i] = floats[i];
1492 }
1493 } else {
1494 if (ints.size() != expectSize) {
1495 return BAD_VALUE;
1496 }
1497 for (size_t i = 0; i < expectSize; ++i) {
1498 event[1].additional_info.data_int32[i] = ints[i];
1499 }
1500 }
1501
1502 SensorDevice& dev(SensorDevice::getInstance());
1503 for (sensors_event_t* i = event; i < event + 3; i++) {
1504 int ret = dev.injectSensorData(i);
1505 if (ret != NO_ERROR) {
1506 return ret;
1507 }
1508 }
1509 return NO_ERROR;
1510}
1511
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001512status_t SensorService::resetToNormalMode() {
1513 Mutex::Autolock _l(mLock);
1514 return resetToNormalModeLocked();
1515}
1516
1517status_t SensorService::resetToNormalModeLocked() {
1518 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001519 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301520 if (err == NO_ERROR) {
1521 mCurrentOperatingMode = NORMAL;
1522 dev.enableAllSensors();
1523 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001524 return err;
1525}
1526
Peng Xu47e96012016-03-28 17:55:56 -07001527void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001528 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001529 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001530 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001531 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001532 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001533 int handle = mActiveSensors.keyAt(i);
1534 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001535 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001536 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1537 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001538 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001539 } else {
1540 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001541 }
Aravind Akella8a969552014-09-28 17:52:41 -07001542 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001543 }
1544 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001545 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001546 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001547 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001548 c, i, handle);
1549
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001550 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001551 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001552 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001553 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001554 delete rec;
1555 size--;
1556 } else {
1557 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001558 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001559 }
Aravind Akella8a969552014-09-28 17:52:41 -07001560 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001561 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001562 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001563 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001564 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001565 }
Peng Xu4f707f82016-09-26 11:28:32 -07001566
Brian Stack793f4642019-04-18 17:21:34 -07001567 {
1568 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1569 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1570 if (iter != sPackageTargetVersion.end()) {
1571 sPackageTargetVersion.erase(iter);
1572 }
1573 }
1574
Peng Xu4f707f82016-09-26 11:28:32 -07001575 SensorDevice& dev(SensorDevice::getInstance());
1576 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001577}
1578
Peng Xue36e3472016-11-03 11:57:10 -07001579void SensorService::cleanupConnection(SensorDirectConnection* c) {
1580 Mutex::Autolock _l(mLock);
1581
1582 SensorDevice& dev(SensorDevice::getInstance());
1583 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001584 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001585}
1586
Peng Xu755c4512016-04-07 23:15:14 -07001587sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001588 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001589}
1590
Mathias Agopianfc328812010-07-14 23:41:37 -07001591status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001592 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001593 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001594 if (mInitCheck != NO_ERROR)
1595 return mInitCheck;
1596
Peng Xu755c4512016-04-07 23:15:14 -07001597 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1598 if (sensor == nullptr ||
1599 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001600 return BAD_VALUE;
1601 }
1602
Brian Duddie967ce172019-06-10 11:08:27 -07001603 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001604 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001605 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001606 return INVALID_OPERATION;
1607 }
1608
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001609 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001610 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001611 rec = new SensorRecord(connection);
1612 mActiveSensors.add(handle, rec);
1613 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001614 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001615 }
Brian Stack26029ee2019-04-22 17:25:49 -07001616
1617 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1618 // the recent event as stale to ensure that the previous event is not sent to a client. This
1619 // ensures on-change events that were generated during a previous sensor activation are not
1620 // erroneously sent to newly connected clients, especially if a second client registers for
1621 // an on-change sensor before the first client receives the updated event. Once an updated
1622 // event is received, the recent events will be marked as current, and any new clients will
1623 // immediately receive the most recent event.
1624 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1625 auto logger = mRecentEvent.find(handle);
1626 if (logger != mRecentEvent.end()) {
1627 logger->second->setLastEventStale();
1628 }
1629 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001630 } else {
1631 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001632 // this sensor is already activated, but we are adding a connection that uses it.
1633 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001634 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001635 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001636 // NOTE: The wake_up flag of this event may get set to
1637 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001638
1639 auto logger = mRecentEvent.find(handle);
1640 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001641 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001642 // Verify that the last sensor event was generated from the current activation
1643 // of the sensor. If not, it is possible for an on-change sensor to receive a
1644 // sensor event that is stale if two clients re-activate the sensor
1645 // simultaneously.
1646 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001647 event.sensor = handle;
1648 if (event.version == sizeof(sensors_event_t)) {
1649 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1650 setWakeLockAcquiredLocked(true);
1651 }
Yi Kong8f313e32018-07-17 14:13:29 -07001652 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001653 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001654 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001655 }
1656 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001657 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001658 }
1659 }
1660 }
1661 }
1662
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001663 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001664 BatteryService::enableSensor(connection->getUid(), handle);
1665 // the sensor was added (which means it wasn't already there)
1666 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001667 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001668 } else {
1669 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1670 handle, connection.get());
1671 }
1672
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301673 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001674 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301675 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1676 samplingPeriodNs = maxDelayNs;
1677 }
1678
Aravind Akella724d91d2013-06-27 12:04:23 -07001679 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1680 if (samplingPeriodNs < minDelayNs) {
1681 samplingPeriodNs = minDelayNs;
1682 }
1683
Aravind Akella6c2664a2014-08-13 12:24:50 -07001684 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1685 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001686 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1687
Aravind Akella4949c502015-02-11 15:54:35 -08001688 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001689 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001690
Peng Xu20483c42015-10-26 15:14:43 -07001691 // Call flush() before calling activate() on the sensor. Wait for a first
1692 // flush complete event before sending events on this connection. Ignore
1693 // one-shot sensors which don't support flush(). Ignore on-change sensors
1694 // to maintain the on-change logic (any on-change events except the initial
1695 // one should be trigger by a change in value). Also if this sensor isn't
1696 // already active, don't call flush().
1697 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001698 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001699 rec->getNumConnections() > 1) {
1700 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001701 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001702 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001703 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001704 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001705 } else {
1706 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001707 }
1708 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001709
1710 if (err == NO_ERROR) {
1711 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1712 err = sensor->activate(connection.get(), true);
1713 }
1714
Aravind Akella8a969552014-09-28 17:52:41 -07001715 if (err == NO_ERROR) {
1716 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001717
Brian Stack240d1d62019-05-17 09:49:39 -07001718 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1719 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001720 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1721 }
1722
Peng Xu51224682017-03-10 16:57:27 -08001723 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1724 SensorRegistrationInfo(handle, connection->getPackageName(),
1725 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001726 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001727 }
1728
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001729 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001730 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001731 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001732 }
1733 return err;
1734}
1735
Peng Xu47e96012016-03-28 17:55:56 -07001736status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001737 if (mInitCheck != NO_ERROR)
1738 return mInitCheck;
1739
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001740 Mutex::Autolock _l(mLock);
1741 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001742 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001743 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1744 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001745
1746 }
1747 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001748 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1749 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001750 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001751 }
1752 return err;
1753}
1754
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001755status_t SensorService::cleanupWithoutDisable(
1756 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001757 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001758 return cleanupWithoutDisableLocked(connection, handle);
1759}
1760
1761status_t SensorService::cleanupWithoutDisableLocked(
1762 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001763 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001764 if (rec) {
1765 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001766 if (connection->removeSensor(handle)) {
1767 BatteryService::disableSensor(connection->getUid(), handle);
1768 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001769 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001770 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001771 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001772 }
1773 // see if this sensor becomes inactive
1774 if (rec->removeConnection(connection)) {
1775 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001776 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001777 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001778 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001779 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001780 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001781 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001782}
1783
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001784status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001785 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001786 if (mInitCheck != NO_ERROR)
1787 return mInitCheck;
1788
Peng Xu755c4512016-04-07 23:15:14 -07001789 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1790 if (sensor == nullptr ||
1791 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001792 return BAD_VALUE;
1793 }
1794
Mathias Agopian1cd70002010-07-21 15:59:50 -07001795 if (ns < 0)
1796 return BAD_VALUE;
1797
Mathias Agopian62569ec2011-11-07 21:21:47 -08001798 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1799 if (ns < minDelayNs) {
1800 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001801 }
1802
Mathias Agopianf001c922010-11-11 17:58:51 -08001803 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001804}
1805
Svetoslavb412f6e2015-04-29 16:50:41 -07001806status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1807 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001808 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001809 SensorDevice& dev(SensorDevice::getInstance());
1810 const int halVersion = dev.getHalDeviceVersion();
1811 status_t err(NO_ERROR);
1812 Mutex::Autolock _l(mLock);
1813 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07001814 for (int handle : connection->getActiveSensorHandles()) {
Peng Xu755c4512016-04-07 23:15:14 -07001815 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1816 if (sensor == nullptr) {
1817 continue;
1818 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001819 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1820 ALOGE("flush called on a one-shot sensor");
1821 err = INVALID_OPERATION;
1822 continue;
1823 }
Aravind Akella8493b792014-09-08 15:45:47 -07001824 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001825 // For older devices just increment pending flush count which will send a trivial
1826 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07001827 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
1828 ALOGE("flush called on an inaccessible sensor");
1829 err = INVALID_OPERATION;
1830 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001831 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001832 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1833 err = INVALID_OPERATION;
1834 continue;
1835 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001836 status_t err_flush = sensor->flush(connection.get(), handle);
1837 if (err_flush == NO_ERROR) {
1838 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001839 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001840 }
1841 err = (err_flush != NO_ERROR) ? err_flush : err;
1842 }
Aravind Akella70018042014-04-07 22:52:37 +00001843 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07001844 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001845}
Aravind Akella70018042014-04-07 22:52:37 +00001846
Svetoslavb412f6e2015-04-29 16:50:41 -07001847bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1848 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001849 // Check if a permission is required for this sensor
1850 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001851 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001852 }
1853
Brian Stack793f4642019-04-18 17:21:34 -07001854 const int32_t opCode = sensor.getRequiredAppOp();
Brian Duddie457e6392020-06-19 11:38:29 -07001855 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07001856
Brian Stack793f4642019-04-18 17:21:34 -07001857 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07001858 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
1859 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1860 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
1861 // Allow access to step sensors if the application targets pre-Q, which is before the
1862 // requirement to hold the AR permission to access Step Counter and Step Detector events
1863 // was introduced.
1864 canAccess = true;
1865 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07001866 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001867 if (opCode >= 0) {
1868 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1869 IPCThreadState::self()->getCallingUid(), opPackageName);
1870 canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
1871 } else {
Brian Stack793f4642019-04-18 17:21:34 -07001872 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001873 }
Brian Stack793f4642019-04-18 17:21:34 -07001874 }
1875
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001876 if (!canAccess) {
Brian Duddie457e6392020-06-19 11:38:29 -07001877 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
1878 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07001879 }
1880
1881 return canAccess;
1882}
1883
1884bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001885 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001886 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001887
1888 // Runtime permissions can't use the cache as they may change.
1889 if (sensor.isRequiredPermissionRuntime()) {
1890 hasPermission = checkPermission(String16(requiredPermission),
1891 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001892 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001893 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1894 }
Brian Stack793f4642019-04-18 17:21:34 -07001895 return hasPermission;
1896}
Svetoslavb412f6e2015-04-29 16:50:41 -07001897
Brian Stack793f4642019-04-18 17:21:34 -07001898int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Anthony Stange07eb4212020-08-28 14:50:28 -04001899 // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
1900 // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
1901 // give it elevated privileges.
1902 if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
1903 return -1;
1904 }
1905
Brian Stack793f4642019-04-18 17:21:34 -07001906 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1907 int targetSdkVersion = -1;
1908 auto entry = sPackageTargetVersion.find(opPackageName);
1909 if (entry != sPackageTargetVersion.end()) {
1910 targetSdkVersion = entry->second;
1911 } else {
1912 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1913 if (binder != nullptr) {
1914 sp<content::pm::IPackageManagerNative> packageManager =
1915 interface_cast<content::pm::IPackageManagerNative>(binder);
1916 if (packageManager != nullptr) {
1917 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1918 opPackageName, &targetSdkVersion);
1919 if (!status.isOk()) {
1920 targetSdkVersion = -1;
1921 }
1922 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001923 }
Brian Stack793f4642019-04-18 17:21:34 -07001924 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001925 }
Brian Stack793f4642019-04-18 17:21:34 -07001926 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001927}
1928
Aravind Akella9a844cf2014-02-11 18:58:52 -08001929void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001930 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1931 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001932}
1933
Brian Duddie967ce172019-06-10 11:08:27 -07001934void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001935 if (!mWakeLockAcquired) {
1936 return;
1937 }
1938 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001939 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1940 if (connection->needsWakeLock()) {
1941 releaseLock = false;
1942 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001943 }
1944 }
1945 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001946 setWakeLockAcquiredLocked(false);
1947 }
1948}
1949
1950void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1951 Mutex::Autolock _l(mLock);
1952 connection->writeToSocketFromCache();
1953 if (connection->needsWakeLock()) {
1954 setWakeLockAcquiredLocked(true);
1955 }
1956}
1957
Aravind Akella4949c502015-02-11 15:54:35 -08001958bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001959 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001960}
1961
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001962bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08001963 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001964 String8 package(opPackageName);
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001965 return !isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001966 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001967 return false;
Peng Xue36e3472016-11-03 11:57:10 -07001968}
1969
Svet Ganove752a5c2018-01-15 17:14:20 -08001970void SensorService::UidPolicy::registerSelf() {
1971 ActivityManager am;
1972 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1973 | ActivityManager::UID_OBSERVER_IDLE
1974 | ActivityManager::UID_OBSERVER_ACTIVE,
1975 ActivityManager::PROCESS_STATE_UNKNOWN,
1976 String16("android"));
1977}
1978
1979void SensorService::UidPolicy::unregisterSelf() {
1980 ActivityManager am;
1981 am.unregisterUidObserver(this);
1982}
1983
1984void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1985 onUidIdle(uid, disabled);
1986}
1987
1988void SensorService::UidPolicy::onUidActive(uid_t uid) {
1989 {
1990 Mutex::Autolock _l(mUidLock);
1991 mActiveUids.insert(uid);
1992 }
1993 sp<SensorService> service = mService.promote();
1994 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001995 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001996 }
1997}
1998
1999void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
2000 bool deleted = false;
2001 {
2002 Mutex::Autolock _l(mUidLock);
2003 if (mActiveUids.erase(uid) > 0) {
2004 deleted = true;
2005 }
2006 }
2007 if (deleted) {
2008 sp<SensorService> service = mService.promote();
2009 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002010 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002011 }
2012 }
2013}
2014
2015void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
2016 updateOverrideUid(uid, active, true);
2017}
2018
2019void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
2020 updateOverrideUid(uid, false, false);
2021}
2022
2023void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
2024 bool wasActive = false;
2025 bool isActive = false;
2026 {
2027 Mutex::Autolock _l(mUidLock);
2028 wasActive = isUidActiveLocked(uid);
2029 mOverrideUids.erase(uid);
2030 if (insert) {
2031 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2032 }
2033 isActive = isUidActiveLocked(uid);
2034 }
2035 if (wasActive != isActive) {
2036 sp<SensorService> service = mService.promote();
2037 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002038 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002039 }
2040 }
2041}
2042
2043bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2044 // Non-app UIDs are considered always active
2045 if (uid < FIRST_APPLICATION_UID) {
2046 return true;
2047 }
2048 Mutex::Autolock _l(mUidLock);
2049 return isUidActiveLocked(uid);
2050}
2051
2052bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2053 // Non-app UIDs are considered always active
2054 if (uid < FIRST_APPLICATION_UID) {
2055 return true;
2056 }
2057 auto it = mOverrideUids.find(uid);
2058 if (it != mOverrideUids.end()) {
2059 return it->second;
2060 }
2061 return mActiveUids.find(uid) != mActiveUids.end();
2062}
2063
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002064bool SensorService::isUidActive(uid_t uid) {
2065 return mUidPolicy->isUidActive(uid);
2066}
2067
Anh Phamaf91a912021-02-10 14:10:53 +01002068bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2069 int targetSdk = getTargetSdkVersion(opPackageName);
2070 bool hasSamplingRatePermission = PermissionCache::checkCallingPermission(
2071 sAccessHighSensorSamplingRatePermission);
2072 if (targetSdk < __ANDROID_API_S__ ||
2073 (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2074 return false;
2075 }
2076 return true;
2077}
2078
2079bool SensorService::isSensorInCappedSet(int sensorType) {
2080 return (sensorType == SENSOR_TYPE_ACCELEROMETER
2081 || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2082 || sensorType == SENSOR_TYPE_GYROSCOPE
2083 || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2084 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2085 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2086}
2087
2088status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2089 const String16& opPackageName) {
Anh Pham5198c992021-02-10 14:15:30 +01002090 uid_t uid = IPCThreadState::self()->getCallingUid();
Anh Phamaf91a912021-02-10 14:10:53 +01002091 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
2092 if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2093 return OK;
2094 }
2095 if (shouldCapBasedOnPermission) {
2096 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2097 if (isPackageDebuggable(opPackageName)) {
2098 return PERMISSION_DENIED;
2099 }
2100 return OK;
2101 }
Anh Pham5198c992021-02-10 14:15:30 +01002102 if (isMicSensorPrivacyEnabledForUid(uid)) {
2103 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2104 return OK;
2105 }
Anh Phamaf91a912021-02-10 14:10:53 +01002106 return OK;
2107}
2108
2109status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2110 const String16& opPackageName) {
2111 uid_t uid = IPCThreadState::self()->getCallingUid();
2112 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
2113
2114 if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2115 return OK;
2116 }
2117 if (shouldCapBasedOnPermission) {
2118 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2119 if (isPackageDebuggable(opPackageName)) {
2120 return PERMISSION_DENIED;
2121 }
2122 return OK;
2123 }
Anh Pham5198c992021-02-10 14:15:30 +01002124 if (isMicSensorPrivacyEnabledForUid(uid)) {
2125 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2126 return OK;
2127 }
Anh Phamaf91a912021-02-10 14:10:53 +01002128 return OK;
2129}
2130
Michael Groover5e1f60b2018-12-04 22:34:29 -08002131void SensorService::SensorPrivacyPolicy::registerSelf() {
2132 SensorPrivacyManager spm;
2133 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2134 spm.addSensorPrivacyListener(this);
2135}
2136
2137void SensorService::SensorPrivacyPolicy::unregisterSelf() {
2138 SensorPrivacyManager spm;
2139 spm.removeSensorPrivacyListener(this);
2140}
2141
2142bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2143 return mSensorPrivacyEnabled;
2144}
2145
2146binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2147 mSensorPrivacyEnabled = enabled;
2148 sp<SensorService> service = mService.promote();
Anh Pham5198c992021-02-10 14:15:30 +01002149
Michael Groover5e1f60b2018-12-04 22:34:29 -08002150 if (service != nullptr) {
Anh Pham5198c992021-02-10 14:15:30 +01002151 if (mIsIndividualMic) {
2152 if (enabled) {
2153 service->capRates(mUserId);
2154 } else {
2155 service->uncapRates(mUserId);
2156 }
Michael Groover5e1f60b2018-12-04 22:34:29 -08002157 } else {
Anh Pham5198c992021-02-10 14:15:30 +01002158 if (enabled) {
2159 service->disableAllSensors();
2160 } else {
2161 service->enableAllSensors();
2162 }
Michael Groover5e1f60b2018-12-04 22:34:29 -08002163 }
2164 }
2165 return binder::Status::ok();
2166}
Brian Duddie967ce172019-06-10 11:08:27 -07002167
Anh Pham5198c992021-02-10 14:15:30 +01002168status_t SensorService::SensorPrivacyPolicy::registerSelfForIndividual(int userId) {
2169 Mutex::Autolock _l(mSensorPrivacyLock);
2170
2171 SensorPrivacyManager spm;
2172 status_t err = spm.addIndividualSensorPrivacyListener(userId,
2173 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE, this);
2174
2175 if (err != OK) {
2176 ALOGE("Cannot register a mic listener.");
2177 return err;
2178 }
2179 mSensorPrivacyEnabled = spm.isIndividualSensorPrivacyEnabled(userId,
2180 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE);
2181
2182 mIsIndividualMic = true;
2183 mUserId = userId;
2184 return OK;
2185}
2186
2187bool SensorService::isMicSensorPrivacyEnabledForUid(uid_t uid) {
2188 userid_t userId = multiuser_get_user_id(uid);
2189 if (mMicSensorPrivacyPolicies.find(userId) == mMicSensorPrivacyPolicies.end()) {
2190 sp<SensorPrivacyPolicy> userPolicy = new SensorPrivacyPolicy(this);
2191 if (userPolicy->registerSelfForIndividual(userId) != OK) {
2192 return false;
2193 }
2194 mMicSensorPrivacyPolicies[userId] = userPolicy;
2195 }
2196 return mMicSensorPrivacyPolicies[userId]->isSensorPrivacyEnabled();
2197}
2198
Brian Duddie967ce172019-06-10 11:08:27 -07002199SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2200 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2201 : mConnectionHolder(holder), mAutolock(mutex) {}
2202
2203template<typename ConnectionType>
2204const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2205 const SortedVector<wp<ConnectionType>>& connectionList,
2206 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2207 referenceHolder->emplace_back();
2208 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2209 for (const wp<ConnectionType>& weakConnection : connectionList){
2210 sp<ConnectionType> connection = weakConnection.promote();
2211 if (connection != nullptr) {
2212 connections.push_back(std::move(connection));
2213 }
2214 }
2215 return connections;
2216}
2217
2218const std::vector<sp<SensorService::SensorEventConnection>>&
2219 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2220 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2221 &mReferencedActiveConnections);
2222}
2223
2224const std::vector<sp<SensorService::SensorDirectConnection>>&
2225 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2226 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2227 &mReferencedDirectConnections);
2228}
2229
2230void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2231 const sp<SensorService::SensorEventConnection>& connection) {
2232 if (mActiveConnections.indexOf(connection) < 0) {
2233 mActiveConnections.add(connection);
2234 }
2235}
2236
2237void SensorService::SensorConnectionHolder::removeEventConnection(
2238 const wp<SensorService::SensorEventConnection>& connection) {
2239 mActiveConnections.remove(connection);
2240}
2241
2242void SensorService::SensorConnectionHolder::addDirectConnection(
2243 const sp<SensorService::SensorDirectConnection>& connection) {
2244 mDirectConnections.add(connection);
2245}
2246
2247void SensorService::SensorConnectionHolder::removeDirectConnection(
2248 const wp<SensorService::SensorDirectConnection>& connection) {
2249 mDirectConnections.remove(connection);
2250}
2251
2252SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2253 return ConnectionSafeAutolock(*this, mutex);
2254}
2255
Anh Phamaf91a912021-02-10 14:10:53 +01002256bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2257 bool debugMode = false;
2258 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2259 if (binder != nullptr) {
2260 sp<content::pm::IPackageManagerNative> packageManager =
2261 interface_cast<content::pm::IPackageManagerNative>(binder);
2262 if (packageManager != nullptr) {
2263 binder::Status status = packageManager->isPackageDebuggable(
2264 opPackageName, &debugMode);
2265 }
2266 }
2267 return debugMode;
2268}
Brian Duddie967ce172019-06-10 11:08:27 -07002269} // namespace android