blob: cd1521da181630299eb95d8b5325b4f4f58e5663 [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();
Peng Xu47e96012016-03-28 17:55:56 -0700372}
373
374status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700375 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700376 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800377 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700378 IPCThreadState::self()->getCallingPid(),
379 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700380 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700381 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700382 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800383 return INVALID_OPERATION;
384 }
Brian Duddie967ce172019-06-10 11:08:27 -0700385 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800386 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700387 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700388 // If already in restricted mode. Ignore.
389 if (mCurrentOperatingMode == RESTRICTED) {
390 return status_t(NO_ERROR);
391 }
392 // If in any mode other than normal, ignore.
393 if (mCurrentOperatingMode != NORMAL) {
394 return INVALID_OPERATION;
395 }
Peng Xue36e3472016-11-03 11:57:10 -0700396
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700397 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800398 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700399 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700400 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700401 return status_t(NO_ERROR);
402 } else if (args.size() == 1 && args[0] == String16("enable")) {
403 // If currently in restricted mode, reset back to NORMAL mode else ignore.
404 if (mCurrentOperatingMode == RESTRICTED) {
405 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800406 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700407 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700408 }
Aravind Akella841a5922015-06-29 12:37:48 -0700409 if (mCurrentOperatingMode == DATA_INJECTION) {
410 resetToNormalModeLocked();
411 }
412 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700413 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700414 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
415 if (mCurrentOperatingMode == NORMAL) {
416 dev.disableAllSensors();
417 status_t err = dev.setMode(DATA_INJECTION);
418 if (err == NO_ERROR) {
419 mCurrentOperatingMode = DATA_INJECTION;
420 } else {
421 // Re-enable sensors.
422 dev.enableAllSensors();
423 }
424 mWhiteListedPackage.setTo(String8(args[1]));
425 return NO_ERROR;
426 } else if (mCurrentOperatingMode == DATA_INJECTION) {
427 // Already in DATA_INJECTION mode. Treat this as a no_op.
428 return NO_ERROR;
429 } else {
430 // Transition to data injection mode supported only from NORMAL mode.
431 return INVALID_OPERATION;
432 }
Mike Ma24743862020-01-29 00:36:55 -0800433 } else if (args.size() == 1 && args[0] == String16("--proto")) {
434 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700435 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700436 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700437 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700438 } else {
439 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700440 //
Brian Stack51498e62018-10-03 10:52:21 -0700441 timespec curTime;
442 clock_gettime(CLOCK_REALTIME, &curTime);
443 struct tm* timeinfo = localtime(&(curTime.tv_sec));
444 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
445 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800446 result.append("Sensor Device:\n");
447 result.append(SensorDevice::getInstance().dump().c_str());
448
449 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700450 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700451
Peng Xu6a2d3a02015-12-21 12:00:23 -0800452 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700453 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700454
Peng Xu0cc8f802016-04-05 23:46:03 -0700455 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800456 for (auto&& i : mRecentEvent) {
457 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700458 if (!i.second->isEmpty()) {
459 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
460 i.second->setFormat("normal");
461 } else {
462 i.second->setFormat("mask_data");
463 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800464 // if there is events and sensor does not need special permission.
465 result.appendFormat("%s: ", s->getSensor().getName().string());
466 result.append(i.second->dump().c_str());
467 }
468 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700469
Aravind Akella444f2672015-05-07 12:40:52 -0700470 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700471 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700472 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
473 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700474 if (dev.isSensorActive(handle)) {
475 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
476 getSensorName(handle).string(),
477 handle,
478 mActiveSensors.valueAt(i)->getNumConnections());
479 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700480 }
481
Andreas Gamped4036b62015-07-28 13:49:04 -0700482 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700483 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700484 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
485 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700486 result.appendFormat("Mode :");
487 switch(mCurrentOperatingMode) {
488 case NORMAL:
489 result.appendFormat(" NORMAL\n");
490 break;
491 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700492 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700493 break;
494 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700495 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700496 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800497 result.appendFormat("Sensor Privacy: %s\n",
498 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700499
Brian Duddie967ce172019-06-10 11:08:27 -0700500 const auto& activeConnections = connLock.getActiveConnections();
501 result.appendFormat("%zd active connections\n", activeConnections.size());
502 for (size_t i=0 ; i < activeConnections.size() ; i++) {
503 result.appendFormat("Connection Number: %zu \n", i);
504 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700505 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700506
Brian Duddie967ce172019-06-10 11:08:27 -0700507 const auto& directConnections = connLock.getDirectConnections();
508 result.appendFormat("%zd direct connections\n", directConnections.size());
509 for (size_t i = 0 ; i < directConnections.size() ; i++) {
510 result.appendFormat("Direct connection %zu:\n", i);
511 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700512 }
513
Aravind Akella18d6d512015-06-18 14:18:28 -0700514 result.appendFormat("Previous Registrations:\n");
515 // Log in the reverse chronological order.
516 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
517 SENSOR_REGISTRATIONS_BUF_SIZE;
518 const int startIndex = currentIndex;
519 do {
520 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
521 if (SensorRegistrationInfo::isSentinel(reg_info)) {
522 // Ignore sentinel, proceed to next item.
523 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
524 SENSOR_REGISTRATIONS_BUF_SIZE;
525 continue;
526 }
Peng Xu51224682017-03-10 16:57:27 -0800527 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700528 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
529 SENSOR_REGISTRATIONS_BUF_SIZE;
530 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700531 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700532 }
533 write(fd, result.string(), result.size());
534 return NO_ERROR;
535}
536
Mike Ma24743862020-01-29 00:36:55 -0800537/**
538 * Dump debugging information as android.service.SensorServiceProto protobuf message using
539 * ProtoOutputStream.
540 *
541 * See proto definition and some notes about ProtoOutputStream in
542 * frameworks/base/core/proto/android/service/sensor_service.proto
543 */
544status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
545 using namespace service::SensorServiceProto;
546 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800547 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
548 if (!mSensors.hasAnySensor()) {
549 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
550 }
Mike Ma24743862020-01-29 00:36:55 -0800551 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
552
553 timespec curTime;
554 clock_gettime(CLOCK_REALTIME, &curTime);
555 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
556
557 // Write SensorDeviceProto
558 uint64_t token = proto.start(SENSOR_DEVICE);
559 SensorDevice::getInstance().dump(&proto);
560 proto.end(token);
561
562 // Write SensorListProto
563 token = proto.start(SENSORS);
564 mSensors.dump(&proto);
565 proto.end(token);
566
567 // Write SensorFusionProto
568 token = proto.start(FUSION_STATE);
569 SensorFusion::getInstance().dump(&proto);
570 proto.end(token);
571
572 // Write SensorEventsProto
573 token = proto.start(SENSOR_EVENTS);
574 for (auto&& i : mRecentEvent) {
575 sp<SensorInterface> s = mSensors.getInterface(i.first);
576 if (!i.second->isEmpty()) {
577 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
578 "normal" : "mask_data");
579 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
580 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
581 std::string(s->getSensor().getName().string()));
582 i.second->dump(&proto);
583 proto.end(mToken);
584 }
585 }
586 proto.end(token);
587
588 // Write ActiveSensorProto
589 SensorDevice& dev = SensorDevice::getInstance();
590 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
591 int handle = mActiveSensors.keyAt(i);
592 if (dev.isSensorActive(handle)) {
593 token = proto.start(ACTIVE_SENSORS);
594 proto.write(service::ActiveSensorProto::NAME,
595 std::string(getSensorName(handle).string()));
596 proto.write(service::ActiveSensorProto::HANDLE, handle);
597 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
598 int(mActiveSensors.valueAt(i)->getNumConnections()));
599 proto.end(token);
600 }
601 }
602
603 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
604 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
605 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
606
607 switch(mCurrentOperatingMode) {
608 case NORMAL:
609 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
610 break;
611 case RESTRICTED:
612 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
613 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
614 break;
615 case DATA_INJECTION:
616 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
617 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
618 break;
619 default:
620 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
621 }
622 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
623
624 // Write repeated SensorEventConnectionProto
625 const auto& activeConnections = connLock->getActiveConnections();
626 for (size_t i = 0; i < activeConnections.size(); i++) {
627 token = proto.start(ACTIVE_CONNECTIONS);
628 activeConnections[i]->dump(&proto);
629 proto.end(token);
630 }
631
632 // Write repeated SensorDirectConnectionProto
633 const auto& directConnections = connLock->getDirectConnections();
634 for (size_t i = 0 ; i < directConnections.size() ; i++) {
635 token = proto.start(DIRECT_CONNECTIONS);
636 directConnections[i]->dump(&proto);
637 proto.end(token);
638 }
639
640 // Write repeated SensorRegistrationInfoProto
641 const int startIndex = mNextSensorRegIndex;
642 int curr = startIndex;
643 do {
644 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
645 if (SensorRegistrationInfo::isSentinel(reg_info)) {
646 // Ignore sentinel, proceed to next item.
647 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
648 continue;
649 }
650 token = proto.start(PREVIOUS_REGISTRATIONS);
651 reg_info.dump(&proto);
652 proto.end(token);
653 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
654 } while (startIndex != curr);
655
656 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
657}
658
Michael Groover5e1f60b2018-12-04 22:34:29 -0800659void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700660 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
661 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800662}
663
Brian Duddie967ce172019-06-10 11:08:27 -0700664void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800665 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700666 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
667 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
668 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800669 }
670 dev.disableAllSensors();
671 // Clear all pending flush connections for all active sensors. If one of the active
672 // connections has called flush() and the underlying sensor has been disabled before a
673 // flush complete event is returned, we need to remove the connection from this queue.
674 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
675 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
676 }
677}
678
679void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700680 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
681 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800682}
683
Brian Duddie967ce172019-06-10 11:08:27 -0700684void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800685 // sensors should only be enabled if the operating state is not restricted and sensor
686 // privacy is not enabled.
687 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
688 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
689 mCurrentOperatingMode,
690 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
691 return;
692 }
693 SensorDevice& dev(SensorDevice::getInstance());
694 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700695 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
696 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
697 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800698 }
699}
700
Brian Duddie967ce172019-06-10 11:08:27 -0700701
Svet Ganove752a5c2018-01-15 17:14:20 -0800702// NOTE: This is a remote API - make sure all args are validated
703status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
704 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
705 return PERMISSION_DENIED;
706 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700707 if (args.size() == 0) {
708 return BAD_INDEX;
709 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800710 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
711 return BAD_VALUE;
712 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700713 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800714 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700715 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800716 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700717 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800718 return handleGetUidState(args, out, err);
719 } else if (args.size() == 1 && args[0] == String16("help")) {
720 printHelp(out);
721 return NO_ERROR;
722 }
723 printHelp(err);
724 return BAD_VALUE;
725}
726
Tanmay Patild33a1822019-04-11 18:38:55 -0700727static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800728 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700729 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800730 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700731 ALOGE("Unknown package: '%s'", String8(packageName).string());
732 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800733 return BAD_VALUE;
734 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700735
736 if (userId < 0) {
737 ALOGE("Invalid user: %d", userId);
738 dprintf(err, "Invalid user: %d\n", userId);
739 return BAD_VALUE;
740 }
741
742 uid = multiuser_get_uid(userId, uid);
743 return NO_ERROR;
744}
745
746status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
747 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
748 if (!(args.size() == 3 || args.size() == 5)) {
749 printHelp(err);
750 return BAD_VALUE;
751 }
752
Svet Ganove752a5c2018-01-15 17:14:20 -0800753 bool active = false;
754 if (args[2] == String16("active")) {
755 active = true;
756 } else if ((args[2] != String16("idle"))) {
757 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
758 return BAD_VALUE;
759 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700760
761 int userId = 0;
762 if (args.size() == 5 && args[3] == String16("--user")) {
763 userId = atoi(String8(args[4]));
764 }
765
766 uid_t uid;
767 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
768 return BAD_VALUE;
769 }
770
Svet Ganove752a5c2018-01-15 17:14:20 -0800771 mUidPolicy->addOverrideUid(uid, active);
772 return NO_ERROR;
773}
774
775status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700776 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
777 if (!(args.size() == 2 || args.size() == 4)) {
778 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800779 return BAD_VALUE;
780 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700781
782 int userId = 0;
783 if (args.size() == 4 && args[2] == String16("--user")) {
784 userId = atoi(String8(args[3]));
785 }
786
787 uid_t uid;
788 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
789 return BAD_VALUE;
790 }
791
Svet Ganove752a5c2018-01-15 17:14:20 -0800792 mUidPolicy->removeOverrideUid(uid);
793 return NO_ERROR;
794}
795
796status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700797 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
798 if (!(args.size() == 2 || args.size() == 4)) {
799 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800800 return BAD_VALUE;
801 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700802
803 int userId = 0;
804 if (args.size() == 4 && args[2] == String16("--user")) {
805 userId = atoi(String8(args[3]));
806 }
807
808 uid_t uid;
809 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
810 return BAD_VALUE;
811 }
812
Svet Ganove752a5c2018-01-15 17:14:20 -0800813 if (mUidPolicy->isUidActive(uid)) {
814 return dprintf(out, "active\n");
815 } else {
816 return dprintf(out, "idle\n");
817 }
818}
819
820status_t SensorService::printHelp(int out) {
821 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700822 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
823 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
824 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800825 " help print this message\n");
826}
827
Peng Xu0cc8f802016-04-05 23:46:03 -0700828//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800829void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700830 sensors_event_t const* buffer, const int count) {
831 for (int i=0 ; i<count ; i++) {
832 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700833 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
834 handle = buffer[i].meta_data.sensor;
835 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700836 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700837 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700838 // If this buffer has an event from a one_shot sensor and this connection is registered
839 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700840 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700841 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
842 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800843 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700844 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700845
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700846 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700847 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700848}
849
Peng Xu47e96012016-03-28 17:55:56 -0700850bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000851 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700852
Peng Xueb4d6282015-12-10 18:02:41 -0800853 // each virtual sensor could generate an event per "real" event, that's why we need to size
854 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
855 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700856 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700857 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700858 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700859
Mathias Agopianf001c922010-11-11 17:58:51 -0800860 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700861
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700862 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700863 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700864 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
865 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700866 if(count == DEAD_OBJECT && device.isReconnecting()) {
867 device.reconnect();
868 continue;
869 } else {
870 ALOGE("sensor poll failed (%s)", strerror(-count));
871 break;
872 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700873 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700874
875 // Reset sensors_event_t.flags to zero for all events in the buffer.
876 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700877 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700878 }
Brian Duddie967ce172019-06-10 11:08:27 -0700879 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700880
Aravind Akella9a844cf2014-02-11 18:58:52 -0800881 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
882 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
883 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
884 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
885 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700886 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700887 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700888 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700889 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700890 }
891 }
892
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700893 if (wakeEvents > 0) {
894 if (!mWakeLockAcquired) {
895 setWakeLockAcquiredLocked(true);
896 }
897 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800898 }
Aravind Akella8493b792014-09-08 15:45:47 -0700899 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800900
Mathias Agopianf001c922010-11-11 17:58:51 -0800901 // handle virtual sensors
902 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700903 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700904 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800905 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700906 SensorFusion& fusion(SensorFusion::getInstance());
907 if (fusion.isEnabled()) {
908 for (size_t i=0 ; i<size_t(count) ; i++) {
909 fusion.process(event[i]);
910 }
911 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700912 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700913 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700914 if (count + k >= minBufferSize) {
915 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700916 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700917 count, k, minBufferSize);
918 break;
919 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800920 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700921 sp<SensorInterface> si = mSensors.getInterface(handle);
922 if (si == nullptr) {
923 ALOGE("handle %d is not an valid virtual sensor", handle);
924 continue;
925 }
926
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700927 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700928 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800929 k++;
930 }
931 }
932 }
933 if (k) {
934 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700935 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800936 count += k;
937 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700938 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700939 }
940 }
941 }
942
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700943 // handle backward compatibility for RotationVector sensor
944 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
945 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700946 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700947 // All the 4 components of the quaternion should be available
948 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700949 mSensorEventBuffer[i].data[4] = -1;
950 }
951 }
952 }
953
Brian Duddie967ce172019-06-10 11:08:27 -0700954 // Cache the list of active connections, since we use it in multiple places below but won't
955 // modify it here
956 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
957
Aravind Akella8493b792014-09-08 15:45:47 -0700958 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700959 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
960 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
961 // SensorEventConnection mapped to the corresponding flush_complete_event in
962 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700963 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700964 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
965 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
966 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700967 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700968 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
969 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700970 }
971 }
Peng Xu2576cb62016-01-20 00:22:09 -0800972
973 // handle dynamic sensor meta events, process registration and unregistration of dynamic
974 // sensor based on content of event.
975 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
976 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
977 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
978 const sensor_t& dynamicSensor =
979 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
980 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
981 handle, dynamicSensor.type, dynamicSensor.name);
982
Peng Xu0cc8f802016-04-05 23:46:03 -0700983 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800984 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700985 sensor_t s = dynamicSensor;
986 // make sure the dynamic sensor flag is set
987 s.flags |= DYNAMIC_SENSOR_MASK;
988 // force the handle to be consistent
989 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800990
991 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800992
Peng Xu0cc8f802016-04-05 23:46:03 -0700993 // This will release hold on dynamic sensor meta, so it should be called
994 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700995 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800996 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700997 } else {
998 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
999 }
Peng Xu2576cb62016-01-20 00:22:09 -08001000 } else {
1001 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1002 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1003
1004 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001005 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -08001006 ALOGE("Dynamic sensor release error.");
1007 }
1008
Brian Duddie967ce172019-06-10 11:08:27 -07001009 for (const sp<SensorEventConnection>& connection : activeConnections) {
1010 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001011 }
1012 }
1013 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001014 }
1015
Aravind Akella9a844cf2014-02-11 18:58:52 -08001016 // Send our events to clients. Check the state of wake lock for each client and release the
1017 // lock if none of the clients need it.
1018 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001019 for (const sp<SensorEventConnection>& connection : activeConnections) {
1020 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1021 mMapFlushEventsToConnections);
1022 needsWakeLock |= connection->needsWakeLock();
1023 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1024 // Early check for one-shot sensors.
1025 if (connection->hasOneShotSensors()) {
1026 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001027 }
1028 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001029
Aravind Akella9a844cf2014-02-11 18:58:52 -08001030 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001031 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001032 }
Aravind Akella8493b792014-09-08 15:45:47 -07001033 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001034
Steve Block3c20fbe2012-01-05 23:22:43 +00001035 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001036 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001037 return false;
1038}
1039
Aravind Akella56ae4262014-07-10 16:01:10 -07001040sp<Looper> SensorService::getLooper() const {
1041 return mLooper;
1042}
1043
Aravind Akellab4373ac2014-10-29 17:55:20 -07001044void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001045 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1046 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1047 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001048 }
Brian Duddie967ce172019-06-10 11:08:27 -07001049 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001050}
1051
1052void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1053 if (acquire) {
1054 if (!mWakeLockAcquired) {
1055 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1056 mWakeLockAcquired = true;
1057 }
1058 mLooper->wake();
1059 } else {
1060 if (mWakeLockAcquired) {
1061 release_wake_lock(WAKE_LOCK_NAME);
1062 mWakeLockAcquired = false;
1063 }
1064 }
1065}
1066
Aravind Akellab4373ac2014-10-29 17:55:20 -07001067bool SensorService::isWakeLockAcquired() {
1068 Mutex::Autolock _l(mLock);
1069 return mWakeLockAcquired;
1070}
1071
Aravind Akella56ae4262014-07-10 16:01:10 -07001072bool SensorService::SensorEventAckReceiver::threadLoop() {
1073 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001074 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001075 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001076 bool wakeLockAcquired = mService->isWakeLockAcquired();
1077 int timeout = -1;
1078 if (wakeLockAcquired) timeout = 5000;
1079 int ret = looper->pollOnce(timeout);
1080 if (ret == ALOOPER_POLL_TIMEOUT) {
1081 mService->resetAllWakeLockRefCounts();
1082 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001083 } while(!Thread::exitPending());
1084 return false;
1085}
1086
Aravind Akella9a844cf2014-02-11 18:58:52 -08001087void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001088 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001089 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001090 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1091 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001092 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001093 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001094 }
Peng Xu2576cb62016-01-20 00:22:09 -08001095
Peng Xu6a2d3a02015-12-21 12:00:23 -08001096 auto logger = mRecentEvent.find(buffer[i].sensor);
1097 if (logger != mRecentEvent.end()) {
1098 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001099 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001100 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001101}
1102
Peng Xu47e96012016-03-28 17:55:56 -07001103void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001104 struct compar {
1105 static int cmp(void const* lhs, void const* rhs) {
1106 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1107 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001108 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001109 }
1110 };
1111 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1112}
1113
Mathias Agopian5d270722010-07-19 15:20:39 -07001114String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001115 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001116}
1117
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001118String8 SensorService::getSensorStringType(int handle) const {
1119 return mSensors.getStringType(handle);
1120}
1121
Aravind Akellab4099e72013-10-15 15:43:10 -07001122bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001123 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1124 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001125}
1126
Aravind Akella9a844cf2014-02-11 18:58:52 -08001127bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001128 int handle = event.sensor;
1129 if (event.type == SENSOR_TYPE_META_DATA) {
1130 handle = event.meta_data.sensor;
1131 }
Peng Xu755c4512016-04-07 23:15:14 -07001132 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1133 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001134}
1135
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001136int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1137 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1138 // UUID is not supported for this device.
1139 return 0;
1140 }
1141 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1142 // This sensor can be uniquely identified in the system by
1143 // the combination of its type and name.
1144 return -1;
1145 }
1146
1147 // We have a dynamic sensor.
1148
1149 if (!sHmacGlobalKeyIsValid) {
1150 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1151 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1152 return 0;
1153 }
1154
1155 // We want each app author/publisher to get a different ID, so that the
1156 // same dynamic sensor cannot be tracked across apps by multiple
1157 // authors/publishers. So we use both our UUID and our User ID.
1158 // Note potential confusion:
1159 // UUID => Universally Unique Identifier.
1160 // UID => User Identifier.
1161 // We refrain from using "uid" except as needed by API to try to
1162 // keep this distinction clear.
1163
1164 auto appUserId = IPCThreadState::self()->getCallingUid();
1165 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1166 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1167 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1168
1169 // Now we use our key on our UUID/app combo to get the hash.
1170 uint8_t hash[EVP_MAX_MD_SIZE];
1171 unsigned int hashLen;
1172 if (HMAC(EVP_sha256(),
1173 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1174 uuidAndApp, sizeof(uuidAndApp),
1175 hash, &hashLen) == nullptr) {
1176 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1177 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1178 return 0;
1179 }
1180
1181 int32_t id = 0;
1182 if (hashLen < sizeof(id)) {
1183 // We never expect this case, but out of paranoia, we handle it.
1184 // Our 'id' length is already quite small, we don't want the
1185 // effective length of it to be even smaller.
1186 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1187 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1188 return 0;
1189 }
1190
1191 // This is almost certainly less than all of 'hash', but it's as secure
1192 // as we can be with our current 'id' length.
1193 memcpy(&id, hash, sizeof(id));
1194
1195 // Note at the beginning of the function that we return the values of
1196 // 0 and -1 to represent special cases. As a result, we can't return
1197 // those as dynamic sensor IDs. If we happened to hash to one of those
1198 // values, we change 'id' so we report as a dynamic sensor, and not as
1199 // one of those special cases.
1200 if (id == -1) {
1201 id = -2;
1202 } else if (id == 0) {
1203 id = 1;
1204 }
1205 return id;
1206}
1207
1208void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1209 for (auto &sensor : sensorList) {
1210 int32_t id = getIdFromUuid(sensor.getUuid());
1211 sensor.setId(id);
1212 }
1213}
1214
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001215Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001216 char value[PROPERTY_VALUE_MAX];
1217 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001218 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001219 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001220 Vector<Sensor> accessibleSensorList;
1221 for (size_t i = 0; i < initialSensorList.size(); i++) {
1222 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001223 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001224 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001225 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001226 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001227}
1228
Peng Xu47e96012016-03-28 17:55:56 -07001229Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001230 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001231 mSensors.forEachSensor(
1232 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001233 if (sensor.isDynamicSensor()) {
1234 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1235 accessibleSensorList.add(sensor);
1236 } else {
1237 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1238 sensor.getName().string(),
1239 sensor.getRequiredPermission().string(),
1240 sensor.getRequiredAppOp());
1241 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001242 }
1243 return true;
1244 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001245 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001246 return accessibleSensorList;
1247}
1248
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001249sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001250 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001251 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1252 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001253 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001254 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001255
1256 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001257 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1258 // operating in DI mode.
1259 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001260 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1261 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001262 }
1263
Mathias Agopian5307d172012-09-18 17:02:43 -07001264 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001265 pid_t pid = IPCThreadState::self()->getCallingPid();
1266
1267 String8 connPackageName =
1268 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1269 String16 connOpPackageName =
1270 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1271 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001272 requestedMode == DATA_INJECTION, connOpPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001273 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001274 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001275 // Add the associated file descriptor to the Looper for polling whenever there is data to
1276 // be injected.
1277 result->updateLooperRegistration(mLooper);
1278 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001279 return result;
1280}
1281
Aravind Akella841a5922015-06-29 12:37:48 -07001282int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001283 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001284 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001285}
1286
Peng Xue36e3472016-11-03 11:57:10 -07001287sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1288 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1289 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001290 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001291
Michael Groover5e1f60b2018-12-04 22:34:29 -08001292 // No new direct connections are allowed when sensor privacy is enabled
1293 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1294 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1295 return nullptr;
1296 }
1297
Peng Xue36e3472016-11-03 11:57:10 -07001298 struct sensors_direct_mem_t mem = {
1299 .type = type,
1300 .format = format,
1301 .size = size,
1302 .handle = resource,
1303 };
1304 uid_t uid = IPCThreadState::self()->getCallingUid();
1305
1306 if (mem.handle == nullptr) {
1307 ALOGE("Failed to clone resource handle");
1308 return nullptr;
1309 }
1310
1311 // check format
1312 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1313 ALOGE("Direct channel format %d is unsupported!", format);
1314 return nullptr;
1315 }
1316
1317 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001318 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1319 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001320 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001321 return nullptr;
1322 }
1323 }
1324
1325 // check specific to memory type
1326 switch(type) {
1327 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001328 if (resource->numFds < 1) {
1329 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1330 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1331 return nullptr;
1332 }
Peng Xue36e3472016-11-03 11:57:10 -07001333 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001334 if (!ashmem_valid(fd)) {
1335 ALOGE("Supplied Ashmem memory region is invalid");
1336 return nullptr;
1337 }
1338
Peng Xue36e3472016-11-03 11:57:10 -07001339 int size2 = ashmem_get_size_region(fd);
1340 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001341 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001342 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1343 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001344 return nullptr;
1345 }
1346 break;
1347 }
1348 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001349 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001350 break;
1351 default:
1352 ALOGE("Unknown direct connection memory type %d", type);
1353 return nullptr;
1354 }
1355
1356 native_handle_t *clone = native_handle_clone(resource);
1357 if (!clone) {
1358 return nullptr;
1359 }
1360
Brian Duddie967ce172019-06-10 11:08:27 -07001361 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001362 SensorDevice& dev(SensorDevice::getInstance());
1363 int channelHandle = dev.registerDirectChannel(&mem);
1364
1365 if (channelHandle <= 0) {
1366 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1367 } else {
1368 mem.handle = clone;
1369 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1370 }
1371
1372 if (conn == nullptr) {
1373 native_handle_close(clone);
1374 native_handle_delete(clone);
1375 } else {
1376 // add to list of direct connections
1377 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001378 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001379 }
1380 return conn;
1381}
1382
Peng Xudd5c5cb2017-03-16 17:39:43 -07001383int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001384 int32_t handle, int32_t type,
1385 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001386 Mutex::Autolock _l(mLock);
1387
Alexey Polyudov88711e82017-05-23 19:54:04 -07001388 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001389 return PERMISSION_DENIED;
1390 }
1391
1392 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001393 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001394 size_t expectSize = INT32_MAX;
1395 switch (type) {
1396 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1397 isFloat = true;
1398 expectSize = 3;
1399 break;
1400 case AINFO_LOCAL_GRAVITY:
1401 isFloat = true;
1402 expectSize = 1;
1403 break;
1404 case AINFO_DOCK_STATE:
1405 case AINFO_HIGH_PERFORMANCE_MODE:
1406 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1407 isFloat = false;
1408 expectSize = 1;
1409 break;
1410 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001411 // CUSTOM events must only contain float data; it may have variable size
1412 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1413 ints.size() ||
1414 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1415 handle < 0) {
1416 return BAD_VALUE;
1417 }
1418 isFloat = true;
1419 isCustom = true;
1420 expectSize = floats.size();
1421 break;
1422 }
1423
1424 if (!isCustom && handle != -1) {
1425 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001426 }
1427
1428 // three events: first one is begin tag, last one is end tag, the one in the middle
1429 // is the payload.
1430 sensors_event_t event[3];
1431 int64_t timestamp = elapsedRealtimeNano();
1432 for (sensors_event_t* i = event; i < event + 3; i++) {
1433 *i = (sensors_event_t) {
1434 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001435 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001436 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1437 .timestamp = timestamp++,
1438 .additional_info = (additional_info_event_t) {
1439 .serial = 0
1440 }
1441 };
1442 }
1443
1444 event[0].additional_info.type = AINFO_BEGIN;
1445 event[1].additional_info.type = type;
1446 event[2].additional_info.type = AINFO_END;
1447
1448 if (isFloat) {
1449 if (floats.size() != expectSize) {
1450 return BAD_VALUE;
1451 }
1452 for (size_t i = 0; i < expectSize; ++i) {
1453 event[1].additional_info.data_float[i] = floats[i];
1454 }
1455 } else {
1456 if (ints.size() != expectSize) {
1457 return BAD_VALUE;
1458 }
1459 for (size_t i = 0; i < expectSize; ++i) {
1460 event[1].additional_info.data_int32[i] = ints[i];
1461 }
1462 }
1463
1464 SensorDevice& dev(SensorDevice::getInstance());
1465 for (sensors_event_t* i = event; i < event + 3; i++) {
1466 int ret = dev.injectSensorData(i);
1467 if (ret != NO_ERROR) {
1468 return ret;
1469 }
1470 }
1471 return NO_ERROR;
1472}
1473
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001474status_t SensorService::resetToNormalMode() {
1475 Mutex::Autolock _l(mLock);
1476 return resetToNormalModeLocked();
1477}
1478
1479status_t SensorService::resetToNormalModeLocked() {
1480 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001481 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301482 if (err == NO_ERROR) {
1483 mCurrentOperatingMode = NORMAL;
1484 dev.enableAllSensors();
1485 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001486 return err;
1487}
1488
Peng Xu47e96012016-03-28 17:55:56 -07001489void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001490 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001491 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001492 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001493 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001494 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001495 int handle = mActiveSensors.keyAt(i);
1496 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001497 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001498 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1499 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001500 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001501 } else {
1502 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001503 }
Aravind Akella8a969552014-09-28 17:52:41 -07001504 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001505 }
1506 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001507 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001508 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001509 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001510 c, i, handle);
1511
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001512 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001513 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001514 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001515 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001516 delete rec;
1517 size--;
1518 } else {
1519 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001520 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001521 }
Aravind Akella8a969552014-09-28 17:52:41 -07001522 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001523 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001524 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001525 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001526 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001527 }
Peng Xu4f707f82016-09-26 11:28:32 -07001528
Brian Stack793f4642019-04-18 17:21:34 -07001529 {
1530 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1531 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1532 if (iter != sPackageTargetVersion.end()) {
1533 sPackageTargetVersion.erase(iter);
1534 }
1535 }
1536
Peng Xu4f707f82016-09-26 11:28:32 -07001537 SensorDevice& dev(SensorDevice::getInstance());
1538 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001539}
1540
Peng Xue36e3472016-11-03 11:57:10 -07001541void SensorService::cleanupConnection(SensorDirectConnection* c) {
1542 Mutex::Autolock _l(mLock);
1543
1544 SensorDevice& dev(SensorDevice::getInstance());
1545 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001546 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001547}
1548
Peng Xu755c4512016-04-07 23:15:14 -07001549sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001550 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001551}
1552
Mathias Agopianfc328812010-07-14 23:41:37 -07001553status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001554 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001555 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001556 if (mInitCheck != NO_ERROR)
1557 return mInitCheck;
1558
Peng Xu755c4512016-04-07 23:15:14 -07001559 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1560 if (sensor == nullptr ||
1561 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001562 return BAD_VALUE;
1563 }
1564
Brian Duddie967ce172019-06-10 11:08:27 -07001565 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001566 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001567 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001568 return INVALID_OPERATION;
1569 }
1570
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001571 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001572 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001573 rec = new SensorRecord(connection);
1574 mActiveSensors.add(handle, rec);
1575 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001576 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001577 }
Brian Stack26029ee2019-04-22 17:25:49 -07001578
1579 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1580 // the recent event as stale to ensure that the previous event is not sent to a client. This
1581 // ensures on-change events that were generated during a previous sensor activation are not
1582 // erroneously sent to newly connected clients, especially if a second client registers for
1583 // an on-change sensor before the first client receives the updated event. Once an updated
1584 // event is received, the recent events will be marked as current, and any new clients will
1585 // immediately receive the most recent event.
1586 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1587 auto logger = mRecentEvent.find(handle);
1588 if (logger != mRecentEvent.end()) {
1589 logger->second->setLastEventStale();
1590 }
1591 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001592 } else {
1593 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001594 // this sensor is already activated, but we are adding a connection that uses it.
1595 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001596 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001597 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001598 // NOTE: The wake_up flag of this event may get set to
1599 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001600
1601 auto logger = mRecentEvent.find(handle);
1602 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001603 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001604 // Verify that the last sensor event was generated from the current activation
1605 // of the sensor. If not, it is possible for an on-change sensor to receive a
1606 // sensor event that is stale if two clients re-activate the sensor
1607 // simultaneously.
1608 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001609 event.sensor = handle;
1610 if (event.version == sizeof(sensors_event_t)) {
1611 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1612 setWakeLockAcquiredLocked(true);
1613 }
Yi Kong8f313e32018-07-17 14:13:29 -07001614 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001615 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001616 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001617 }
1618 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001619 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001620 }
1621 }
1622 }
1623 }
1624
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001625 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001626 BatteryService::enableSensor(connection->getUid(), handle);
1627 // the sensor was added (which means it wasn't already there)
1628 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001629 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001630 } else {
1631 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1632 handle, connection.get());
1633 }
1634
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301635 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001636 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301637 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1638 samplingPeriodNs = maxDelayNs;
1639 }
1640
Aravind Akella724d91d2013-06-27 12:04:23 -07001641 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1642 if (samplingPeriodNs < minDelayNs) {
1643 samplingPeriodNs = minDelayNs;
1644 }
1645
Aravind Akella6c2664a2014-08-13 12:24:50 -07001646 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1647 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001648 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1649
Aravind Akella4949c502015-02-11 15:54:35 -08001650 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001651 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001652
Peng Xu20483c42015-10-26 15:14:43 -07001653 // Call flush() before calling activate() on the sensor. Wait for a first
1654 // flush complete event before sending events on this connection. Ignore
1655 // one-shot sensors which don't support flush(). Ignore on-change sensors
1656 // to maintain the on-change logic (any on-change events except the initial
1657 // one should be trigger by a change in value). Also if this sensor isn't
1658 // already active, don't call flush().
1659 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001660 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001661 rec->getNumConnections() > 1) {
1662 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001663 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001664 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001665 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001666 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001667 } else {
1668 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001669 }
1670 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001671
1672 if (err == NO_ERROR) {
1673 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1674 err = sensor->activate(connection.get(), true);
1675 }
1676
Aravind Akella8a969552014-09-28 17:52:41 -07001677 if (err == NO_ERROR) {
1678 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001679
Brian Stack240d1d62019-05-17 09:49:39 -07001680 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1681 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001682 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1683 }
1684
Peng Xu51224682017-03-10 16:57:27 -08001685 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1686 SensorRegistrationInfo(handle, connection->getPackageName(),
1687 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001688 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001689 }
1690
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001691 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001692 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001693 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001694 }
1695 return err;
1696}
1697
Peng Xu47e96012016-03-28 17:55:56 -07001698status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001699 if (mInitCheck != NO_ERROR)
1700 return mInitCheck;
1701
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001702 Mutex::Autolock _l(mLock);
1703 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001704 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001705 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1706 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001707
1708 }
1709 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001710 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1711 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001712 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001713 }
1714 return err;
1715}
1716
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001717status_t SensorService::cleanupWithoutDisable(
1718 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001719 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001720 return cleanupWithoutDisableLocked(connection, handle);
1721}
1722
1723status_t SensorService::cleanupWithoutDisableLocked(
1724 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001725 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001726 if (rec) {
1727 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001728 if (connection->removeSensor(handle)) {
1729 BatteryService::disableSensor(connection->getUid(), handle);
1730 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001731 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001732 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001733 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001734 }
1735 // see if this sensor becomes inactive
1736 if (rec->removeConnection(connection)) {
1737 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001738 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001739 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001740 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001741 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001742 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001743 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001744}
1745
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001746status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001747 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001748 if (mInitCheck != NO_ERROR)
1749 return mInitCheck;
1750
Peng Xu755c4512016-04-07 23:15:14 -07001751 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1752 if (sensor == nullptr ||
1753 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001754 return BAD_VALUE;
1755 }
1756
Mathias Agopian1cd70002010-07-21 15:59:50 -07001757 if (ns < 0)
1758 return BAD_VALUE;
1759
Mathias Agopian62569ec2011-11-07 21:21:47 -08001760 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1761 if (ns < minDelayNs) {
1762 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001763 }
1764
Mathias Agopianf001c922010-11-11 17:58:51 -08001765 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001766}
1767
Svetoslavb412f6e2015-04-29 16:50:41 -07001768status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1769 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001770 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001771 SensorDevice& dev(SensorDevice::getInstance());
1772 const int halVersion = dev.getHalDeviceVersion();
1773 status_t err(NO_ERROR);
1774 Mutex::Autolock _l(mLock);
1775 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07001776 for (int handle : connection->getActiveSensorHandles()) {
Peng Xu755c4512016-04-07 23:15:14 -07001777 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1778 if (sensor == nullptr) {
1779 continue;
1780 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001781 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1782 ALOGE("flush called on a one-shot sensor");
1783 err = INVALID_OPERATION;
1784 continue;
1785 }
Aravind Akella8493b792014-09-08 15:45:47 -07001786 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001787 // For older devices just increment pending flush count which will send a trivial
1788 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07001789 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
1790 ALOGE("flush called on an inaccessible sensor");
1791 err = INVALID_OPERATION;
1792 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001793 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001794 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1795 err = INVALID_OPERATION;
1796 continue;
1797 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001798 status_t err_flush = sensor->flush(connection.get(), handle);
1799 if (err_flush == NO_ERROR) {
1800 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001801 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001802 }
1803 err = (err_flush != NO_ERROR) ? err_flush : err;
1804 }
Aravind Akella70018042014-04-07 22:52:37 +00001805 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07001806 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001807}
Aravind Akella70018042014-04-07 22:52:37 +00001808
Svetoslavb412f6e2015-04-29 16:50:41 -07001809bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1810 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001811 // Check if a permission is required for this sensor
1812 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001813 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001814 }
1815
Brian Stack793f4642019-04-18 17:21:34 -07001816 const int32_t opCode = sensor.getRequiredAppOp();
Brian Duddie457e6392020-06-19 11:38:29 -07001817 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07001818
Brian Stack793f4642019-04-18 17:21:34 -07001819 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07001820 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
1821 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1822 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
1823 // Allow access to step sensors if the application targets pre-Q, which is before the
1824 // requirement to hold the AR permission to access Step Counter and Step Detector events
1825 // was introduced.
1826 canAccess = true;
1827 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07001828 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001829 if (opCode >= 0) {
1830 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1831 IPCThreadState::self()->getCallingUid(), opPackageName);
1832 canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
1833 } else {
Brian Stack793f4642019-04-18 17:21:34 -07001834 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001835 }
Brian Stack793f4642019-04-18 17:21:34 -07001836 }
1837
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001838 if (!canAccess) {
Brian Duddie457e6392020-06-19 11:38:29 -07001839 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
1840 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07001841 }
1842
1843 return canAccess;
1844}
1845
1846bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001847 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001848 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001849
1850 // Runtime permissions can't use the cache as they may change.
1851 if (sensor.isRequiredPermissionRuntime()) {
1852 hasPermission = checkPermission(String16(requiredPermission),
1853 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001854 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001855 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1856 }
Brian Stack793f4642019-04-18 17:21:34 -07001857 return hasPermission;
1858}
Svetoslavb412f6e2015-04-29 16:50:41 -07001859
Brian Stack793f4642019-04-18 17:21:34 -07001860int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Anthony Stange07eb4212020-08-28 14:50:28 -04001861 // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
1862 // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
1863 // give it elevated privileges.
1864 if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
1865 return -1;
1866 }
1867
Brian Stack793f4642019-04-18 17:21:34 -07001868 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1869 int targetSdkVersion = -1;
1870 auto entry = sPackageTargetVersion.find(opPackageName);
1871 if (entry != sPackageTargetVersion.end()) {
1872 targetSdkVersion = entry->second;
1873 } else {
1874 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1875 if (binder != nullptr) {
1876 sp<content::pm::IPackageManagerNative> packageManager =
1877 interface_cast<content::pm::IPackageManagerNative>(binder);
1878 if (packageManager != nullptr) {
1879 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1880 opPackageName, &targetSdkVersion);
1881 if (!status.isOk()) {
1882 targetSdkVersion = -1;
1883 }
1884 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001885 }
Brian Stack793f4642019-04-18 17:21:34 -07001886 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001887 }
Brian Stack793f4642019-04-18 17:21:34 -07001888 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001889}
1890
Aravind Akella9a844cf2014-02-11 18:58:52 -08001891void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001892 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1893 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001894}
1895
Brian Duddie967ce172019-06-10 11:08:27 -07001896void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001897 if (!mWakeLockAcquired) {
1898 return;
1899 }
1900 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001901 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1902 if (connection->needsWakeLock()) {
1903 releaseLock = false;
1904 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001905 }
1906 }
1907 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001908 setWakeLockAcquiredLocked(false);
1909 }
1910}
1911
1912void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1913 Mutex::Autolock _l(mLock);
1914 connection->writeToSocketFromCache();
1915 if (connection->needsWakeLock()) {
1916 setWakeLockAcquiredLocked(true);
1917 }
1918}
1919
Aravind Akella4949c502015-02-11 15:54:35 -08001920bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001921 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001922}
1923
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001924bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08001925 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001926 String8 package(opPackageName);
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001927 return !isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001928 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001929 return false;
Peng Xue36e3472016-11-03 11:57:10 -07001930}
1931
Svet Ganove752a5c2018-01-15 17:14:20 -08001932void SensorService::UidPolicy::registerSelf() {
1933 ActivityManager am;
1934 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1935 | ActivityManager::UID_OBSERVER_IDLE
1936 | ActivityManager::UID_OBSERVER_ACTIVE,
1937 ActivityManager::PROCESS_STATE_UNKNOWN,
1938 String16("android"));
1939}
1940
1941void SensorService::UidPolicy::unregisterSelf() {
1942 ActivityManager am;
1943 am.unregisterUidObserver(this);
1944}
1945
1946void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1947 onUidIdle(uid, disabled);
1948}
1949
1950void SensorService::UidPolicy::onUidActive(uid_t uid) {
1951 {
1952 Mutex::Autolock _l(mUidLock);
1953 mActiveUids.insert(uid);
1954 }
1955 sp<SensorService> service = mService.promote();
1956 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001957 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001958 }
1959}
1960
1961void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1962 bool deleted = false;
1963 {
1964 Mutex::Autolock _l(mUidLock);
1965 if (mActiveUids.erase(uid) > 0) {
1966 deleted = true;
1967 }
1968 }
1969 if (deleted) {
1970 sp<SensorService> service = mService.promote();
1971 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001972 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001973 }
1974 }
1975}
1976
1977void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1978 updateOverrideUid(uid, active, true);
1979}
1980
1981void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1982 updateOverrideUid(uid, false, false);
1983}
1984
1985void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1986 bool wasActive = false;
1987 bool isActive = false;
1988 {
1989 Mutex::Autolock _l(mUidLock);
1990 wasActive = isUidActiveLocked(uid);
1991 mOverrideUids.erase(uid);
1992 if (insert) {
1993 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1994 }
1995 isActive = isUidActiveLocked(uid);
1996 }
1997 if (wasActive != isActive) {
1998 sp<SensorService> service = mService.promote();
1999 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002000 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002001 }
2002 }
2003}
2004
2005bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2006 // Non-app UIDs are considered always active
2007 if (uid < FIRST_APPLICATION_UID) {
2008 return true;
2009 }
2010 Mutex::Autolock _l(mUidLock);
2011 return isUidActiveLocked(uid);
2012}
2013
2014bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2015 // Non-app UIDs are considered always active
2016 if (uid < FIRST_APPLICATION_UID) {
2017 return true;
2018 }
2019 auto it = mOverrideUids.find(uid);
2020 if (it != mOverrideUids.end()) {
2021 return it->second;
2022 }
2023 return mActiveUids.find(uid) != mActiveUids.end();
2024}
2025
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002026bool SensorService::isUidActive(uid_t uid) {
2027 return mUidPolicy->isUidActive(uid);
2028}
2029
Anh Phamaf91a912021-02-10 14:10:53 +01002030bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2031 int targetSdk = getTargetSdkVersion(opPackageName);
2032 bool hasSamplingRatePermission = PermissionCache::checkCallingPermission(
2033 sAccessHighSensorSamplingRatePermission);
2034 if (targetSdk < __ANDROID_API_S__ ||
2035 (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2036 return false;
2037 }
2038 return true;
2039}
2040
2041bool SensorService::isSensorInCappedSet(int sensorType) {
2042 return (sensorType == SENSOR_TYPE_ACCELEROMETER
2043 || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2044 || sensorType == SENSOR_TYPE_GYROSCOPE
2045 || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2046 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2047 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2048}
2049
2050status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2051 const String16& opPackageName) {
2052
2053 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
2054 if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2055 return OK;
2056 }
2057 if (shouldCapBasedOnPermission) {
2058 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2059 if (isPackageDebuggable(opPackageName)) {
2060 return PERMISSION_DENIED;
2061 }
2062 return OK;
2063 }
2064 // Condition based on mic toggle is added later.
2065 return OK;
2066}
2067
2068status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2069 const String16& opPackageName) {
2070 uid_t uid = IPCThreadState::self()->getCallingUid();
2071 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
2072
2073 if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2074 return OK;
2075 }
2076 if (shouldCapBasedOnPermission) {
2077 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2078 if (isPackageDebuggable(opPackageName)) {
2079 return PERMISSION_DENIED;
2080 }
2081 return OK;
2082 }
2083 // Condition based on mic toggle is added later.
2084 return OK;
2085}
2086
Michael Groover5e1f60b2018-12-04 22:34:29 -08002087void SensorService::SensorPrivacyPolicy::registerSelf() {
2088 SensorPrivacyManager spm;
2089 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2090 spm.addSensorPrivacyListener(this);
2091}
2092
2093void SensorService::SensorPrivacyPolicy::unregisterSelf() {
2094 SensorPrivacyManager spm;
2095 spm.removeSensorPrivacyListener(this);
2096}
2097
2098bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2099 return mSensorPrivacyEnabled;
2100}
2101
2102binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2103 mSensorPrivacyEnabled = enabled;
2104 sp<SensorService> service = mService.promote();
2105 if (service != nullptr) {
2106 if (enabled) {
2107 service->disableAllSensors();
2108 } else {
2109 service->enableAllSensors();
2110 }
2111 }
2112 return binder::Status::ok();
2113}
Brian Duddie967ce172019-06-10 11:08:27 -07002114
2115SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2116 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2117 : mConnectionHolder(holder), mAutolock(mutex) {}
2118
2119template<typename ConnectionType>
2120const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2121 const SortedVector<wp<ConnectionType>>& connectionList,
2122 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2123 referenceHolder->emplace_back();
2124 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2125 for (const wp<ConnectionType>& weakConnection : connectionList){
2126 sp<ConnectionType> connection = weakConnection.promote();
2127 if (connection != nullptr) {
2128 connections.push_back(std::move(connection));
2129 }
2130 }
2131 return connections;
2132}
2133
2134const std::vector<sp<SensorService::SensorEventConnection>>&
2135 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2136 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2137 &mReferencedActiveConnections);
2138}
2139
2140const std::vector<sp<SensorService::SensorDirectConnection>>&
2141 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2142 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2143 &mReferencedDirectConnections);
2144}
2145
2146void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2147 const sp<SensorService::SensorEventConnection>& connection) {
2148 if (mActiveConnections.indexOf(connection) < 0) {
2149 mActiveConnections.add(connection);
2150 }
2151}
2152
2153void SensorService::SensorConnectionHolder::removeEventConnection(
2154 const wp<SensorService::SensorEventConnection>& connection) {
2155 mActiveConnections.remove(connection);
2156}
2157
2158void SensorService::SensorConnectionHolder::addDirectConnection(
2159 const sp<SensorService::SensorDirectConnection>& connection) {
2160 mDirectConnections.add(connection);
2161}
2162
2163void SensorService::SensorConnectionHolder::removeDirectConnection(
2164 const wp<SensorService::SensorDirectConnection>& connection) {
2165 mDirectConnections.remove(connection);
2166}
2167
2168SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2169 return ConnectionSafeAutolock(*this, mutex);
2170}
2171
Anh Phamaf91a912021-02-10 14:10:53 +01002172bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2173 bool debugMode = false;
2174 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2175 if (binder != nullptr) {
2176 sp<content::pm::IPackageManagerNative> packageManager =
2177 interface_cast<content::pm::IPackageManagerNative>(binder);
2178 if (packageManager != nullptr) {
2179 binder::Status status = packageManager->isPackageDebuggable(
2180 opPackageName, &debugMode);
2181 }
2182 }
2183 return debugMode;
2184}
Brian Duddie967ce172019-06-10 11:08:27 -07002185} // namespace android