blob: a1c800ed061f2f9854c98c32c741c6a6f5053043 [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
54#include <inttypes.h>
55#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070056#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080057#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080058#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070059#include <sys/stat.h>
60#include <sys/types.h>
61#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070062
Andrew Lehmer3a602572021-03-25 15:19:56 -070063#include <ctime>
64#include <future>
65
Svet Ganove752a5c2018-01-15 17:14:20 -080066#include <private/android_filesystem_config.h>
67
Andrew Lehmer3a602572021-03-25 15:19:56 -070068using namespace std::chrono_literals;
69
Mathias Agopianfc328812010-07-14 23:41:37 -070070namespace android {
71// ---------------------------------------------------------------------------
72
Mathias Agopian33015422011-05-27 18:18:13 -070073/*
74 * Notes:
75 *
76 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070077 * - run mag sensor from time to time to force calibration
78 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
79 *
80 */
81
Aravind Akella8ef3c892015-07-10 11:24:28 -070082const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070083uint8_t SensorService::sHmacGlobalKey[128] = {};
84bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070085std::map<String16, int> SensorService::sPackageTargetVersion;
86Mutex SensorService::sPackageTargetVersionLock;
Anthony Stange07eb4212020-08-28 14:50:28 -040087String16 SensorService::sSensorInterfaceDescriptorPrefix =
88 String16("android.frameworks.sensorservice@");
Brian Stack793f4642019-04-18 17:21:34 -070089AppOpsManager SensorService::sAppOpsManager;
Andrew Lehmer3a602572021-03-25 15:19:56 -070090std::atomic_uint64_t SensorService::curProxCallbackSeq(0);
91std::atomic_uint64_t SensorService::completedCallbackSeq(0);
Greg Kaiser53ca2e02016-06-21 16:11:14 -070092
93#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
94#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070095#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070096
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070097// Permissions.
Anh Phamaf91a912021-02-10 14:10:53 +010098static const String16 sAccessHighSensorSamplingRatePermission(
99 "android.permission.HIGH_SAMPLING_RATE_SENSORS");
Peng Xudd5c5cb2017-03-16 17:39:43 -0700100static const String16 sDumpPermission("android.permission.DUMP");
101static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -0800102static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700103
Mathias Agopianfc328812010-07-14 23:41:37 -0700104SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -0700105 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Andrew Lehmer3a602572021-03-25 15:19:56 -0700106 mWakeLockAcquired(false), mProximityActiveCount(0) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +0900107 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800108 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700109}
110
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700111bool SensorService::initializeHmacKey() {
112 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
113 if (fd != -1) {
114 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
115 close(fd);
116 if (result == sizeof(sHmacGlobalKey)) {
117 return true;
118 }
119 ALOGW("Unable to read HMAC key; generating new one.");
120 }
121
122 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
123 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
124 return false;
125 }
126
127 // We need to make sure this is only readable to us.
128 bool wroteKey = false;
129 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
130 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
131 S_IRUSR|S_IWUSR);
132 if (fd != -1) {
133 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
134 close(fd);
135 wroteKey = (result == sizeof(sHmacGlobalKey));
136 }
137 if (wroteKey) {
138 ALOGI("Generated new HMAC key.");
139 } else {
140 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
141 "after reboot.");
142 }
143 // Even if we failed to write the key we return true, because we did
144 // initialize the HMAC key.
145 return true;
146}
147
Peng Xu98d30f62016-08-01 18:12:11 -0700148// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
149void SensorService::enableSchedFifoMode() {
150 struct sched_param param = {0};
151 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
152 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
153 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
154 }
155}
156
Peng Xu47e96012016-03-28 17:55:56 -0700157void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000158 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800159 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700160
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700161 sHmacGlobalKeyIsValid = initializeHmacKey();
162
Mathias Agopianf001c922010-11-11 17:58:51 -0800163 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800164 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700165 ssize_t count = dev.getSensorList(&list);
166 if (count > 0) {
167 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700168 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700169 uint32_t virtualSensorsNeeds =
170 (1<<SENSOR_TYPE_GRAVITY) |
171 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700172 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
173 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
174 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700175
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700176 for (ssize_t i=0 ; i<count ; i++) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700177 bool useThisSensor = true;
Peng Xuf66684a2015-07-23 11:41:53 -0700178
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700179 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700180 case SENSOR_TYPE_ACCELEROMETER:
181 hasAccel = true;
182 break;
183 case SENSOR_TYPE_MAGNETIC_FIELD:
184 hasMag = true;
185 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700186 case SENSOR_TYPE_ORIENTATION:
187 orientationIndex = i;
188 break;
189 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700190 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700191 hasGyro = true;
192 break;
193 case SENSOR_TYPE_GRAVITY:
194 case SENSOR_TYPE_LINEAR_ACCELERATION:
195 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700196 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
197 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
198 if (IGNORE_HARDWARE_FUSION) {
199 useThisSensor = false;
200 } else {
201 virtualSensorsNeeds &= ~(1<<list[i].type);
202 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700203 break;
204 }
Peng Xuf66684a2015-07-23 11:41:53 -0700205 if (useThisSensor) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700206 if (list[i].type == SENSOR_TYPE_PROXIMITY) {
207 registerSensor(new ProximitySensor(list[i], *this));
208 } else {
209 registerSensor( new HardwareSensor(list[i]) );
210 }
Peng Xuf66684a2015-07-23 11:41:53 -0700211 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700212 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700213
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700214 // it's safe to instantiate the SensorFusion object here
215 // (it wants to be instantiated after h/w sensors have been
216 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700217 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700218
Aravind Akellaf5047892015-07-20 17:29:33 -0700219 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700220 // Add Android virtual sensors if they're not already
221 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700222 bool needRotationVector =
223 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700224
Peng Xu0cc8f802016-04-05 23:46:03 -0700225 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
226 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700227
Peng Xu0cc8f802016-04-05 23:46:03 -0700228 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700229 registerSensor( new CorrectedGyroSensor(list, count), true, true);
230 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700231 }
232
Peng Xuf66684a2015-07-23 11:41:53 -0700233 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700234 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
235 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700236
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800237 bool needLinearAcceleration =
238 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
239 registerSensor(new LinearAccelerationSensor(list, count),
240 !needLinearAcceleration, true);
241
Peng Xu0cc8f802016-04-05 23:46:03 -0700242 bool needGameRotationVector =
243 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
244 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700245 }
246
247 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700248 bool needGeoMagRotationVector =
249 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
250 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700251 }
252
Aravind Akella5466c3d2014-08-22 16:11:10 -0700253 // Check if the device really supports batching by looking at the FIFO event
254 // counts for each sensor.
255 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700256 mSensors.forEachSensor(
257 [&batchingSupported] (const Sensor& s) -> bool {
258 if (s.getFifoMaxEventCount() > 0) {
259 batchingSupported = true;
260 }
261 return !batchingSupported;
262 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700263
264 if (batchingSupported) {
265 // Increase socket buffer size to a max of 100 KB for batching capabilities.
266 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
267 } else {
268 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
269 }
270
271 // Compare the socketBufferSize value against the system limits and limit
272 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700273 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
274 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700275 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700276 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700277 size_t maxSystemSocketBufferSize;
278 sscanf(line, "%zu", &maxSystemSocketBufferSize);
279 if (mSocketBufferSize > maxSystemSocketBufferSize) {
280 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700281 }
282 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700283 if (fp) {
284 fclose(fp);
285 }
286
Aravind Akella9a844cf2014-02-11 18:58:52 -0800287 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700288 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700289 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
290 mSensorEventBuffer = new sensors_event_t[minBufferSize];
291 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700292 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700293 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700294
Aravind Akella18d6d512015-06-18 14:18:28 -0700295 mNextSensorRegIndex = 0;
296 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
297 mLastNSensorRegistrations.push();
298 }
299
300 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700301 mAckReceiver = new SensorEventAckReceiver(this);
302 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700303 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700304
305 // priority can only be changed after run
306 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800307
308 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800309 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800310
311 // Start watching sensor privacy changes
312 mSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800313 }
314 }
315}
316
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700317void SensorService::onUidStateChanged(uid_t uid, UidState state) {
318 SensorDevice& dev(SensorDevice::getInstance());
319
Brian Duddie967ce172019-06-10 11:08:27 -0700320 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700321 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700322 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700323 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700324 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700325 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700326
327 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
328 if (conn->getUid() == uid) {
329 // Update sensor subscriptions if needed
330 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
331 conn->onSensorAccessChanged(hasAccess);
332 }
333 }
334}
335
336bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
337 Mutex::Autolock _l(mLock);
338 return hasSensorAccessLocked(uid, opPackageName);
339}
340
341bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
342 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
343 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700344}
345
Peng Xu0cc8f802016-04-05 23:46:03 -0700346const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
347 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800348 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700349 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700350 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700351 return s->getSensor();
352 } else {
353 return mSensors.getNonSensor();
354 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800355}
356
Peng Xu6a2d3a02015-12-21 12:00:23 -0800357const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700358 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800359}
360
Peng Xu6a2d3a02015-12-21 12:00:23 -0800361bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700362 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800363
364 const auto i = mRecentEvent.find(handle);
365 if (i != mRecentEvent.end()) {
366 delete i->second;
367 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800368 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700369 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800370}
371
Peng Xu0cc8f802016-04-05 23:46:03 -0700372const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
373 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700374}
375
Peng Xu47e96012016-03-28 17:55:56 -0700376SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800377 for (auto && entry : mRecentEvent) {
378 delete entry.second;
379 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800380 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800381 mSensorPrivacyPolicy->unregisterSelf();
Anh Pham5198c992021-02-10 14:15:30 +0100382 for (auto const& [userId, policy] : mMicSensorPrivacyPolicies) {
383 policy->unregisterSelf();
384 }
Peng Xu47e96012016-03-28 17:55:56 -0700385}
386
387status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700388 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700389 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800390 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700391 IPCThreadState::self()->getCallingPid(),
392 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700393 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700394 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700395 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800396 return INVALID_OPERATION;
397 }
Brian Duddie967ce172019-06-10 11:08:27 -0700398 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800399 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700400 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700401 // If already in restricted mode. Ignore.
402 if (mCurrentOperatingMode == RESTRICTED) {
403 return status_t(NO_ERROR);
404 }
405 // If in any mode other than normal, ignore.
406 if (mCurrentOperatingMode != NORMAL) {
407 return INVALID_OPERATION;
408 }
Peng Xue36e3472016-11-03 11:57:10 -0700409
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700410 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800411 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700412 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700413 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700414 return status_t(NO_ERROR);
415 } else if (args.size() == 1 && args[0] == String16("enable")) {
416 // If currently in restricted mode, reset back to NORMAL mode else ignore.
417 if (mCurrentOperatingMode == RESTRICTED) {
418 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800419 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700420 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700421 }
Aravind Akella841a5922015-06-29 12:37:48 -0700422 if (mCurrentOperatingMode == DATA_INJECTION) {
423 resetToNormalModeLocked();
424 }
425 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700426 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700427 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
428 if (mCurrentOperatingMode == NORMAL) {
429 dev.disableAllSensors();
430 status_t err = dev.setMode(DATA_INJECTION);
431 if (err == NO_ERROR) {
432 mCurrentOperatingMode = DATA_INJECTION;
433 } else {
434 // Re-enable sensors.
435 dev.enableAllSensors();
436 }
437 mWhiteListedPackage.setTo(String8(args[1]));
438 return NO_ERROR;
439 } else if (mCurrentOperatingMode == DATA_INJECTION) {
440 // Already in DATA_INJECTION mode. Treat this as a no_op.
441 return NO_ERROR;
442 } else {
443 // Transition to data injection mode supported only from NORMAL mode.
444 return INVALID_OPERATION;
445 }
Mike Ma24743862020-01-29 00:36:55 -0800446 } else if (args.size() == 1 && args[0] == String16("--proto")) {
447 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700448 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700449 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700450 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700451 } else {
452 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700453 //
Brian Stack51498e62018-10-03 10:52:21 -0700454 timespec curTime;
455 clock_gettime(CLOCK_REALTIME, &curTime);
456 struct tm* timeinfo = localtime(&(curTime.tv_sec));
457 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
458 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800459 result.append("Sensor Device:\n");
460 result.append(SensorDevice::getInstance().dump().c_str());
461
462 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700463 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700464
Peng Xu6a2d3a02015-12-21 12:00:23 -0800465 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700466 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700467
Peng Xu0cc8f802016-04-05 23:46:03 -0700468 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800469 for (auto&& i : mRecentEvent) {
470 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700471 if (!i.second->isEmpty()) {
472 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
473 i.second->setFormat("normal");
474 } else {
475 i.second->setFormat("mask_data");
476 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800477 // if there is events and sensor does not need special permission.
478 result.appendFormat("%s: ", s->getSensor().getName().string());
479 result.append(i.second->dump().c_str());
480 }
481 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700482
Aravind Akella444f2672015-05-07 12:40:52 -0700483 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700484 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700485 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
486 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700487 if (dev.isSensorActive(handle)) {
488 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
489 getSensorName(handle).string(),
490 handle,
491 mActiveSensors.valueAt(i)->getNumConnections());
492 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700493 }
494
Andreas Gamped4036b62015-07-28 13:49:04 -0700495 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700496 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700497 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
498 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700499 result.appendFormat("Mode :");
500 switch(mCurrentOperatingMode) {
501 case NORMAL:
502 result.appendFormat(" NORMAL\n");
503 break;
504 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700505 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700506 break;
507 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700508 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700509 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800510 result.appendFormat("Sensor Privacy: %s\n",
511 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700512
Brian Duddie967ce172019-06-10 11:08:27 -0700513 const auto& activeConnections = connLock.getActiveConnections();
514 result.appendFormat("%zd active connections\n", activeConnections.size());
515 for (size_t i=0 ; i < activeConnections.size() ; i++) {
516 result.appendFormat("Connection Number: %zu \n", i);
517 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700518 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700519
Brian Duddie967ce172019-06-10 11:08:27 -0700520 const auto& directConnections = connLock.getDirectConnections();
521 result.appendFormat("%zd direct connections\n", directConnections.size());
522 for (size_t i = 0 ; i < directConnections.size() ; i++) {
523 result.appendFormat("Direct connection %zu:\n", i);
524 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700525 }
526
Aravind Akella18d6d512015-06-18 14:18:28 -0700527 result.appendFormat("Previous Registrations:\n");
528 // Log in the reverse chronological order.
529 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
530 SENSOR_REGISTRATIONS_BUF_SIZE;
531 const int startIndex = currentIndex;
532 do {
533 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
534 if (SensorRegistrationInfo::isSentinel(reg_info)) {
535 // Ignore sentinel, proceed to next item.
536 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
537 SENSOR_REGISTRATIONS_BUF_SIZE;
538 continue;
539 }
Peng Xu51224682017-03-10 16:57:27 -0800540 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700541 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
542 SENSOR_REGISTRATIONS_BUF_SIZE;
543 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700544 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700545 }
546 write(fd, result.string(), result.size());
547 return NO_ERROR;
548}
549
Mike Ma24743862020-01-29 00:36:55 -0800550/**
551 * Dump debugging information as android.service.SensorServiceProto protobuf message using
552 * ProtoOutputStream.
553 *
554 * See proto definition and some notes about ProtoOutputStream in
555 * frameworks/base/core/proto/android/service/sensor_service.proto
556 */
557status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
558 using namespace service::SensorServiceProto;
559 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800560 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
561 if (!mSensors.hasAnySensor()) {
562 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
563 }
Mike Ma24743862020-01-29 00:36:55 -0800564 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
565
566 timespec curTime;
567 clock_gettime(CLOCK_REALTIME, &curTime);
568 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
569
570 // Write SensorDeviceProto
571 uint64_t token = proto.start(SENSOR_DEVICE);
572 SensorDevice::getInstance().dump(&proto);
573 proto.end(token);
574
575 // Write SensorListProto
576 token = proto.start(SENSORS);
577 mSensors.dump(&proto);
578 proto.end(token);
579
580 // Write SensorFusionProto
581 token = proto.start(FUSION_STATE);
582 SensorFusion::getInstance().dump(&proto);
583 proto.end(token);
584
585 // Write SensorEventsProto
586 token = proto.start(SENSOR_EVENTS);
587 for (auto&& i : mRecentEvent) {
588 sp<SensorInterface> s = mSensors.getInterface(i.first);
589 if (!i.second->isEmpty()) {
590 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
591 "normal" : "mask_data");
592 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
593 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
594 std::string(s->getSensor().getName().string()));
595 i.second->dump(&proto);
596 proto.end(mToken);
597 }
598 }
599 proto.end(token);
600
601 // Write ActiveSensorProto
602 SensorDevice& dev = SensorDevice::getInstance();
603 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
604 int handle = mActiveSensors.keyAt(i);
605 if (dev.isSensorActive(handle)) {
606 token = proto.start(ACTIVE_SENSORS);
607 proto.write(service::ActiveSensorProto::NAME,
608 std::string(getSensorName(handle).string()));
609 proto.write(service::ActiveSensorProto::HANDLE, handle);
610 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
611 int(mActiveSensors.valueAt(i)->getNumConnections()));
612 proto.end(token);
613 }
614 }
615
616 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
617 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
618 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
619
620 switch(mCurrentOperatingMode) {
621 case NORMAL:
622 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
623 break;
624 case RESTRICTED:
625 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
626 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
627 break;
628 case DATA_INJECTION:
629 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
630 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
631 break;
632 default:
633 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
634 }
635 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
636
637 // Write repeated SensorEventConnectionProto
638 const auto& activeConnections = connLock->getActiveConnections();
639 for (size_t i = 0; i < activeConnections.size(); i++) {
640 token = proto.start(ACTIVE_CONNECTIONS);
641 activeConnections[i]->dump(&proto);
642 proto.end(token);
643 }
644
645 // Write repeated SensorDirectConnectionProto
646 const auto& directConnections = connLock->getDirectConnections();
647 for (size_t i = 0 ; i < directConnections.size() ; i++) {
648 token = proto.start(DIRECT_CONNECTIONS);
649 directConnections[i]->dump(&proto);
650 proto.end(token);
651 }
652
653 // Write repeated SensorRegistrationInfoProto
654 const int startIndex = mNextSensorRegIndex;
655 int curr = startIndex;
656 do {
657 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
658 if (SensorRegistrationInfo::isSentinel(reg_info)) {
659 // Ignore sentinel, proceed to next item.
660 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
661 continue;
662 }
663 token = proto.start(PREVIOUS_REGISTRATIONS);
664 reg_info.dump(&proto);
665 proto.end(token);
666 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
667 } while (startIndex != curr);
668
669 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
670}
671
Michael Groover5e1f60b2018-12-04 22:34:29 -0800672void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700673 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
674 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800675}
676
Brian Duddie967ce172019-06-10 11:08:27 -0700677void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800678 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700679 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
680 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
681 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800682 }
Andrew Lehmer3a602572021-03-25 15:19:56 -0700683 mSensors.forEachEntry([](const SensorServiceUtil::SensorList::Entry& e) {
684 e.si->willDisableAllSensors();
685 return true;
686 });
Michael Groover5e1f60b2018-12-04 22:34:29 -0800687 dev.disableAllSensors();
688 // Clear all pending flush connections for all active sensors. If one of the active
689 // connections has called flush() and the underlying sensor has been disabled before a
690 // flush complete event is returned, we need to remove the connection from this queue.
691 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
692 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
693 }
694}
695
696void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700697 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
698 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800699}
700
Brian Duddie967ce172019-06-10 11:08:27 -0700701void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800702 // sensors should only be enabled if the operating state is not restricted and sensor
703 // privacy is not enabled.
704 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
705 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
706 mCurrentOperatingMode,
707 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
708 return;
709 }
710 SensorDevice& dev(SensorDevice::getInstance());
711 dev.enableAllSensors();
Andrew Lehmer3a602572021-03-25 15:19:56 -0700712 mSensors.forEachEntry([](const SensorServiceUtil::SensorList::Entry& e) {
713 e.si->didEnableAllSensors();
714 return true;
715 });
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700716 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
717 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
718 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800719 }
720}
721
Anh Pham5198c992021-02-10 14:15:30 +0100722void SensorService::capRates(userid_t userId) {
723 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
724 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
725 if (conn->getUserId() == userId) {
726 conn->onMicSensorAccessChanged(true);
727 }
728 }
729
730 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
731 if (conn->getUserId() == userId) {
732 conn->onMicSensorAccessChanged(true);
733 }
734 }
735}
736
737void SensorService::uncapRates(userid_t userId) {
738 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
739 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
740 if (conn->getUserId() == userId) {
741 conn->onMicSensorAccessChanged(false);
742 }
743 }
744
745 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
746 if (conn->getUserId() == userId) {
747 conn->onMicSensorAccessChanged(false);
748 }
749 }
750}
Brian Duddie967ce172019-06-10 11:08:27 -0700751
Svet Ganove752a5c2018-01-15 17:14:20 -0800752// NOTE: This is a remote API - make sure all args are validated
753status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
754 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
755 return PERMISSION_DENIED;
756 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700757 if (args.size() == 0) {
758 return BAD_INDEX;
759 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800760 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
761 return BAD_VALUE;
762 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700763 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800764 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700765 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800766 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700767 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800768 return handleGetUidState(args, out, err);
769 } else if (args.size() == 1 && args[0] == String16("help")) {
770 printHelp(out);
771 return NO_ERROR;
772 }
773 printHelp(err);
774 return BAD_VALUE;
775}
776
Tanmay Patild33a1822019-04-11 18:38:55 -0700777static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800778 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700779 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800780 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700781 ALOGE("Unknown package: '%s'", String8(packageName).string());
782 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800783 return BAD_VALUE;
784 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700785
786 if (userId < 0) {
787 ALOGE("Invalid user: %d", userId);
788 dprintf(err, "Invalid user: %d\n", userId);
789 return BAD_VALUE;
790 }
791
792 uid = multiuser_get_uid(userId, uid);
793 return NO_ERROR;
794}
795
796status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
797 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
798 if (!(args.size() == 3 || args.size() == 5)) {
799 printHelp(err);
800 return BAD_VALUE;
801 }
802
Svet Ganove752a5c2018-01-15 17:14:20 -0800803 bool active = false;
804 if (args[2] == String16("active")) {
805 active = true;
806 } else if ((args[2] != String16("idle"))) {
807 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
808 return BAD_VALUE;
809 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700810
811 int userId = 0;
812 if (args.size() == 5 && args[3] == String16("--user")) {
813 userId = atoi(String8(args[4]));
814 }
815
816 uid_t uid;
817 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
818 return BAD_VALUE;
819 }
820
Svet Ganove752a5c2018-01-15 17:14:20 -0800821 mUidPolicy->addOverrideUid(uid, active);
822 return NO_ERROR;
823}
824
825status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700826 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
827 if (!(args.size() == 2 || args.size() == 4)) {
828 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800829 return BAD_VALUE;
830 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700831
832 int userId = 0;
833 if (args.size() == 4 && args[2] == String16("--user")) {
834 userId = atoi(String8(args[3]));
835 }
836
837 uid_t uid;
838 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
839 return BAD_VALUE;
840 }
841
Svet Ganove752a5c2018-01-15 17:14:20 -0800842 mUidPolicy->removeOverrideUid(uid);
843 return NO_ERROR;
844}
845
846status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700847 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
848 if (!(args.size() == 2 || args.size() == 4)) {
849 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800850 return BAD_VALUE;
851 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700852
853 int userId = 0;
854 if (args.size() == 4 && args[2] == String16("--user")) {
855 userId = atoi(String8(args[3]));
856 }
857
858 uid_t uid;
859 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
860 return BAD_VALUE;
861 }
862
Svet Ganove752a5c2018-01-15 17:14:20 -0800863 if (mUidPolicy->isUidActive(uid)) {
864 return dprintf(out, "active\n");
865 } else {
866 return dprintf(out, "idle\n");
867 }
868}
869
870status_t SensorService::printHelp(int out) {
871 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700872 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
873 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
874 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800875 " help print this message\n");
876}
877
Peng Xu0cc8f802016-04-05 23:46:03 -0700878//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800879void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700880 sensors_event_t const* buffer, const int count) {
881 for (int i=0 ; i<count ; i++) {
882 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700883 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
884 handle = buffer[i].meta_data.sensor;
885 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700886 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700887 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700888 // If this buffer has an event from a one_shot sensor and this connection is registered
889 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700890 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700891 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
892 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800893 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700894 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700895
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700896 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700897 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700898}
899
Peng Xu47e96012016-03-28 17:55:56 -0700900bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000901 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700902
Peng Xueb4d6282015-12-10 18:02:41 -0800903 // each virtual sensor could generate an event per "real" event, that's why we need to size
904 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
905 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700906 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700907 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700908 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700909
Mathias Agopianf001c922010-11-11 17:58:51 -0800910 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700911
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700912 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700913 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700914 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
915 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700916 if(count == DEAD_OBJECT && device.isReconnecting()) {
917 device.reconnect();
918 continue;
919 } else {
920 ALOGE("sensor poll failed (%s)", strerror(-count));
921 break;
922 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700923 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700924
925 // Reset sensors_event_t.flags to zero for all events in the buffer.
926 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700927 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700928 }
Brian Duddie967ce172019-06-10 11:08:27 -0700929 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700930
Aravind Akella9a844cf2014-02-11 18:58:52 -0800931 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
932 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
933 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
934 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
935 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700936 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700937 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700938 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700939 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700940 }
941 }
942
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700943 if (wakeEvents > 0) {
944 if (!mWakeLockAcquired) {
945 setWakeLockAcquiredLocked(true);
946 }
947 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800948 }
Aravind Akella8493b792014-09-08 15:45:47 -0700949 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800950
Mathias Agopianf001c922010-11-11 17:58:51 -0800951 // handle virtual sensors
952 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700953 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700954 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800955 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700956 SensorFusion& fusion(SensorFusion::getInstance());
957 if (fusion.isEnabled()) {
958 for (size_t i=0 ; i<size_t(count) ; i++) {
959 fusion.process(event[i]);
960 }
961 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700962 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700963 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700964 if (count + k >= minBufferSize) {
965 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700966 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700967 count, k, minBufferSize);
968 break;
969 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800970 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700971 sp<SensorInterface> si = mSensors.getInterface(handle);
972 if (si == nullptr) {
973 ALOGE("handle %d is not an valid virtual sensor", handle);
974 continue;
975 }
976
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700977 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700978 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800979 k++;
980 }
981 }
982 }
983 if (k) {
984 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700985 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800986 count += k;
987 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700988 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700989 }
990 }
991 }
992
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700993 // handle backward compatibility for RotationVector sensor
994 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
995 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700996 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700997 // All the 4 components of the quaternion should be available
998 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700999 mSensorEventBuffer[i].data[4] = -1;
1000 }
1001 }
1002 }
1003
Brian Duddie967ce172019-06-10 11:08:27 -07001004 // Cache the list of active connections, since we use it in multiple places below but won't
1005 // modify it here
1006 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
1007
Aravind Akella8493b792014-09-08 15:45:47 -07001008 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -07001009 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
1010 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
1011 // SensorEventConnection mapped to the corresponding flush_complete_event in
1012 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -07001013 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -07001014 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
1015 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
1016 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001017 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -07001018 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
1019 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001020 }
1021 }
Peng Xu2576cb62016-01-20 00:22:09 -08001022
1023 // handle dynamic sensor meta events, process registration and unregistration of dynamic
1024 // sensor based on content of event.
1025 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
1026 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
1027 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1028 const sensor_t& dynamicSensor =
1029 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
1030 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
1031 handle, dynamicSensor.type, dynamicSensor.name);
1032
Peng Xu0cc8f802016-04-05 23:46:03 -07001033 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -08001034 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -07001035 sensor_t s = dynamicSensor;
1036 // make sure the dynamic sensor flag is set
1037 s.flags |= DYNAMIC_SENSOR_MASK;
1038 // force the handle to be consistent
1039 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -08001040
1041 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -08001042
Peng Xu0cc8f802016-04-05 23:46:03 -07001043 // This will release hold on dynamic sensor meta, so it should be called
1044 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -07001045 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001046 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -07001047 } else {
1048 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
1049 }
Peng Xu2576cb62016-01-20 00:22:09 -08001050 } else {
1051 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1052 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1053
1054 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001055 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -08001056 ALOGE("Dynamic sensor release error.");
1057 }
1058
Brian Duddie967ce172019-06-10 11:08:27 -07001059 for (const sp<SensorEventConnection>& connection : activeConnections) {
1060 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001061 }
1062 }
1063 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001064 }
1065
Aravind Akella9a844cf2014-02-11 18:58:52 -08001066 // Send our events to clients. Check the state of wake lock for each client and release the
1067 // lock if none of the clients need it.
1068 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001069 for (const sp<SensorEventConnection>& connection : activeConnections) {
1070 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1071 mMapFlushEventsToConnections);
1072 needsWakeLock |= connection->needsWakeLock();
1073 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1074 // Early check for one-shot sensors.
1075 if (connection->hasOneShotSensors()) {
1076 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001077 }
1078 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001079
Aravind Akella9a844cf2014-02-11 18:58:52 -08001080 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001081 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001082 }
Aravind Akella8493b792014-09-08 15:45:47 -07001083 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001084
Steve Block3c20fbe2012-01-05 23:22:43 +00001085 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001086 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001087 return false;
1088}
1089
Aravind Akella56ae4262014-07-10 16:01:10 -07001090sp<Looper> SensorService::getLooper() const {
1091 return mLooper;
1092}
1093
Aravind Akellab4373ac2014-10-29 17:55:20 -07001094void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001095 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1096 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1097 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001098 }
Brian Duddie967ce172019-06-10 11:08:27 -07001099 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001100}
1101
1102void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1103 if (acquire) {
1104 if (!mWakeLockAcquired) {
1105 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1106 mWakeLockAcquired = true;
1107 }
1108 mLooper->wake();
1109 } else {
1110 if (mWakeLockAcquired) {
1111 release_wake_lock(WAKE_LOCK_NAME);
1112 mWakeLockAcquired = false;
1113 }
1114 }
1115}
1116
Aravind Akellab4373ac2014-10-29 17:55:20 -07001117bool SensorService::isWakeLockAcquired() {
1118 Mutex::Autolock _l(mLock);
1119 return mWakeLockAcquired;
1120}
1121
Aravind Akella56ae4262014-07-10 16:01:10 -07001122bool SensorService::SensorEventAckReceiver::threadLoop() {
1123 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001124 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001125 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001126 bool wakeLockAcquired = mService->isWakeLockAcquired();
1127 int timeout = -1;
1128 if (wakeLockAcquired) timeout = 5000;
1129 int ret = looper->pollOnce(timeout);
1130 if (ret == ALOOPER_POLL_TIMEOUT) {
1131 mService->resetAllWakeLockRefCounts();
1132 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001133 } while(!Thread::exitPending());
1134 return false;
1135}
1136
Aravind Akella9a844cf2014-02-11 18:58:52 -08001137void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001138 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001139 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001140 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1141 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001142 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001143 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001144 }
Peng Xu2576cb62016-01-20 00:22:09 -08001145
Peng Xu6a2d3a02015-12-21 12:00:23 -08001146 auto logger = mRecentEvent.find(buffer[i].sensor);
1147 if (logger != mRecentEvent.end()) {
1148 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001149 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001150 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001151}
1152
Peng Xu47e96012016-03-28 17:55:56 -07001153void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001154 struct compar {
1155 static int cmp(void const* lhs, void const* rhs) {
1156 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1157 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001158 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001159 }
1160 };
1161 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1162}
1163
Mathias Agopian5d270722010-07-19 15:20:39 -07001164String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001165 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001166}
1167
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001168String8 SensorService::getSensorStringType(int handle) const {
1169 return mSensors.getStringType(handle);
1170}
1171
Aravind Akellab4099e72013-10-15 15:43:10 -07001172bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001173 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1174 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001175}
1176
Aravind Akella9a844cf2014-02-11 18:58:52 -08001177bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001178 int handle = event.sensor;
1179 if (event.type == SENSOR_TYPE_META_DATA) {
1180 handle = event.meta_data.sensor;
1181 }
Peng Xu755c4512016-04-07 23:15:14 -07001182 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1183 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001184}
1185
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001186int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1187 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1188 // UUID is not supported for this device.
1189 return 0;
1190 }
1191 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1192 // This sensor can be uniquely identified in the system by
1193 // the combination of its type and name.
1194 return -1;
1195 }
1196
1197 // We have a dynamic sensor.
1198
1199 if (!sHmacGlobalKeyIsValid) {
1200 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1201 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1202 return 0;
1203 }
1204
1205 // We want each app author/publisher to get a different ID, so that the
1206 // same dynamic sensor cannot be tracked across apps by multiple
1207 // authors/publishers. So we use both our UUID and our User ID.
1208 // Note potential confusion:
1209 // UUID => Universally Unique Identifier.
1210 // UID => User Identifier.
1211 // We refrain from using "uid" except as needed by API to try to
1212 // keep this distinction clear.
1213
1214 auto appUserId = IPCThreadState::self()->getCallingUid();
1215 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1216 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1217 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1218
1219 // Now we use our key on our UUID/app combo to get the hash.
1220 uint8_t hash[EVP_MAX_MD_SIZE];
1221 unsigned int hashLen;
1222 if (HMAC(EVP_sha256(),
1223 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1224 uuidAndApp, sizeof(uuidAndApp),
1225 hash, &hashLen) == nullptr) {
1226 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1227 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1228 return 0;
1229 }
1230
1231 int32_t id = 0;
1232 if (hashLen < sizeof(id)) {
1233 // We never expect this case, but out of paranoia, we handle it.
1234 // Our 'id' length is already quite small, we don't want the
1235 // effective length of it to be even smaller.
1236 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1237 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1238 return 0;
1239 }
1240
1241 // This is almost certainly less than all of 'hash', but it's as secure
1242 // as we can be with our current 'id' length.
1243 memcpy(&id, hash, sizeof(id));
1244
1245 // Note at the beginning of the function that we return the values of
1246 // 0 and -1 to represent special cases. As a result, we can't return
1247 // those as dynamic sensor IDs. If we happened to hash to one of those
1248 // values, we change 'id' so we report as a dynamic sensor, and not as
1249 // one of those special cases.
1250 if (id == -1) {
1251 id = -2;
1252 } else if (id == 0) {
1253 id = 1;
1254 }
1255 return id;
1256}
1257
1258void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1259 for (auto &sensor : sensorList) {
1260 int32_t id = getIdFromUuid(sensor.getUuid());
1261 sensor.setId(id);
1262 }
1263}
1264
Anh Pham4e291332021-02-10 14:17:56 +01001265Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -07001266 char value[PROPERTY_VALUE_MAX];
1267 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001268 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001269 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001270 Vector<Sensor> accessibleSensorList;
Anh Pham4e291332021-02-10 14:17:56 +01001271
1272 bool isCapped = isRateCappedBasedOnPermission(opPackageName);
Aravind Akella70018042014-04-07 22:52:37 +00001273 for (size_t i = 0; i < initialSensorList.size(); i++) {
1274 Sensor sensor = initialSensorList[i];
Anh Pham4e291332021-02-10 14:17:56 +01001275 if (isCapped && isSensorInCappedSet(sensor.getType())) {
1276 sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
1277 sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
1278 }
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001279 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001280 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001281 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001282 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001283}
1284
Peng Xu47e96012016-03-28 17:55:56 -07001285Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001286 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001287 mSensors.forEachSensor(
1288 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001289 if (sensor.isDynamicSensor()) {
1290 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1291 accessibleSensorList.add(sensor);
1292 } else {
1293 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1294 sensor.getName().string(),
1295 sensor.getRequiredPermission().string(),
1296 sensor.getRequiredAppOp());
1297 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001298 }
1299 return true;
1300 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001301 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001302 return accessibleSensorList;
1303}
1304
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001305sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001306 int requestedMode, const String16& opPackageName, const String16& attributionTag) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001307 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1308 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001309 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001310 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001311
1312 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001313 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1314 // operating in DI mode.
1315 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001316 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1317 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001318 }
1319
Mathias Agopian5307d172012-09-18 17:02:43 -07001320 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001321 pid_t pid = IPCThreadState::self()->getCallingPid();
1322
1323 String8 connPackageName =
1324 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1325 String16 connOpPackageName =
1326 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1327 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001328 requestedMode == DATA_INJECTION, connOpPackageName, attributionTag));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001329 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001330 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001331 // Add the associated file descriptor to the Looper for polling whenever there is data to
1332 // be injected.
1333 result->updateLooperRegistration(mLooper);
1334 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001335 return result;
1336}
1337
Aravind Akella841a5922015-06-29 12:37:48 -07001338int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001339 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001340 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001341}
1342
Peng Xue36e3472016-11-03 11:57:10 -07001343sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1344 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1345 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001346 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001347
Michael Groover5e1f60b2018-12-04 22:34:29 -08001348 // No new direct connections are allowed when sensor privacy is enabled
1349 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1350 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1351 return nullptr;
1352 }
1353
Peng Xue36e3472016-11-03 11:57:10 -07001354 struct sensors_direct_mem_t mem = {
1355 .type = type,
1356 .format = format,
1357 .size = size,
1358 .handle = resource,
1359 };
1360 uid_t uid = IPCThreadState::self()->getCallingUid();
1361
1362 if (mem.handle == nullptr) {
1363 ALOGE("Failed to clone resource handle");
1364 return nullptr;
1365 }
1366
1367 // check format
1368 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1369 ALOGE("Direct channel format %d is unsupported!", format);
1370 return nullptr;
1371 }
1372
1373 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001374 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1375 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001376 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001377 return nullptr;
1378 }
1379 }
1380
1381 // check specific to memory type
1382 switch(type) {
1383 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001384 if (resource->numFds < 1) {
1385 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1386 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1387 return nullptr;
1388 }
Peng Xue36e3472016-11-03 11:57:10 -07001389 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001390 if (!ashmem_valid(fd)) {
1391 ALOGE("Supplied Ashmem memory region is invalid");
1392 return nullptr;
1393 }
1394
Peng Xue36e3472016-11-03 11:57:10 -07001395 int size2 = ashmem_get_size_region(fd);
1396 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001397 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001398 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1399 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001400 return nullptr;
1401 }
1402 break;
1403 }
1404 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001405 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001406 break;
1407 default:
1408 ALOGE("Unknown direct connection memory type %d", type);
1409 return nullptr;
1410 }
1411
1412 native_handle_t *clone = native_handle_clone(resource);
1413 if (!clone) {
1414 return nullptr;
1415 }
1416
Brian Duddie967ce172019-06-10 11:08:27 -07001417 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001418 SensorDevice& dev(SensorDevice::getInstance());
1419 int channelHandle = dev.registerDirectChannel(&mem);
1420
1421 if (channelHandle <= 0) {
1422 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1423 } else {
1424 mem.handle = clone;
1425 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1426 }
1427
1428 if (conn == nullptr) {
1429 native_handle_close(clone);
1430 native_handle_delete(clone);
1431 } else {
1432 // add to list of direct connections
1433 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001434 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001435 }
1436 return conn;
1437}
1438
Peng Xudd5c5cb2017-03-16 17:39:43 -07001439int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001440 int32_t handle, int32_t type,
1441 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001442 Mutex::Autolock _l(mLock);
1443
Alexey Polyudov88711e82017-05-23 19:54:04 -07001444 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001445 return PERMISSION_DENIED;
1446 }
1447
1448 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001449 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001450 size_t expectSize = INT32_MAX;
1451 switch (type) {
1452 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1453 isFloat = true;
1454 expectSize = 3;
1455 break;
1456 case AINFO_LOCAL_GRAVITY:
1457 isFloat = true;
1458 expectSize = 1;
1459 break;
1460 case AINFO_DOCK_STATE:
1461 case AINFO_HIGH_PERFORMANCE_MODE:
1462 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1463 isFloat = false;
1464 expectSize = 1;
1465 break;
1466 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001467 // CUSTOM events must only contain float data; it may have variable size
1468 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1469 ints.size() ||
1470 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1471 handle < 0) {
1472 return BAD_VALUE;
1473 }
1474 isFloat = true;
1475 isCustom = true;
1476 expectSize = floats.size();
1477 break;
1478 }
1479
1480 if (!isCustom && handle != -1) {
1481 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001482 }
1483
1484 // three events: first one is begin tag, last one is end tag, the one in the middle
1485 // is the payload.
1486 sensors_event_t event[3];
1487 int64_t timestamp = elapsedRealtimeNano();
1488 for (sensors_event_t* i = event; i < event + 3; i++) {
1489 *i = (sensors_event_t) {
1490 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001491 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001492 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1493 .timestamp = timestamp++,
1494 .additional_info = (additional_info_event_t) {
1495 .serial = 0
1496 }
1497 };
1498 }
1499
1500 event[0].additional_info.type = AINFO_BEGIN;
1501 event[1].additional_info.type = type;
1502 event[2].additional_info.type = AINFO_END;
1503
1504 if (isFloat) {
1505 if (floats.size() != expectSize) {
1506 return BAD_VALUE;
1507 }
1508 for (size_t i = 0; i < expectSize; ++i) {
1509 event[1].additional_info.data_float[i] = floats[i];
1510 }
1511 } else {
1512 if (ints.size() != expectSize) {
1513 return BAD_VALUE;
1514 }
1515 for (size_t i = 0; i < expectSize; ++i) {
1516 event[1].additional_info.data_int32[i] = ints[i];
1517 }
1518 }
1519
1520 SensorDevice& dev(SensorDevice::getInstance());
1521 for (sensors_event_t* i = event; i < event + 3; i++) {
1522 int ret = dev.injectSensorData(i);
1523 if (ret != NO_ERROR) {
1524 return ret;
1525 }
1526 }
1527 return NO_ERROR;
1528}
1529
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001530status_t SensorService::resetToNormalMode() {
1531 Mutex::Autolock _l(mLock);
1532 return resetToNormalModeLocked();
1533}
1534
1535status_t SensorService::resetToNormalModeLocked() {
1536 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001537 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301538 if (err == NO_ERROR) {
1539 mCurrentOperatingMode = NORMAL;
1540 dev.enableAllSensors();
Andrew Lehmer3a602572021-03-25 15:19:56 -07001541 mSensors.forEachEntry([](const SensorServiceUtil::SensorList::Entry& e) {
1542 e.si->didEnableAllSensors();
1543 return true;
1544 });
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301545 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001546 return err;
1547}
1548
Peng Xu47e96012016-03-28 17:55:56 -07001549void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001550 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001551 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001552 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001553 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001554 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001555 int handle = mActiveSensors.keyAt(i);
1556 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001557 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001558 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1559 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001560 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001561 } else {
1562 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001563 }
Aravind Akella8a969552014-09-28 17:52:41 -07001564 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001565 }
1566 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001567 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001568 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001569 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001570 c, i, handle);
1571
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001572 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001573 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001574 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001575 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001576 delete rec;
1577 size--;
1578 } else {
1579 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001580 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001581 }
Aravind Akella8a969552014-09-28 17:52:41 -07001582 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001583 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001584 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001585 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001586 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001587 }
Peng Xu4f707f82016-09-26 11:28:32 -07001588
Brian Stack793f4642019-04-18 17:21:34 -07001589 {
1590 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1591 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1592 if (iter != sPackageTargetVersion.end()) {
1593 sPackageTargetVersion.erase(iter);
1594 }
1595 }
1596
Peng Xu4f707f82016-09-26 11:28:32 -07001597 SensorDevice& dev(SensorDevice::getInstance());
1598 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001599}
1600
Peng Xue36e3472016-11-03 11:57:10 -07001601void SensorService::cleanupConnection(SensorDirectConnection* c) {
1602 Mutex::Autolock _l(mLock);
1603
1604 SensorDevice& dev(SensorDevice::getInstance());
1605 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001606 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001607}
1608
Andrew Lehmer3a602572021-03-25 15:19:56 -07001609void SensorService::onProximityActiveLocked(bool isActive) {
1610 int prevCount = mProximityActiveCount;
1611 bool activeStateChanged = false;
1612 if (isActive) {
1613 mProximityActiveCount++;
1614 activeStateChanged = prevCount == 0;
1615 } else {
1616 mProximityActiveCount--;
1617 if (mProximityActiveCount < 0) {
1618 ALOGE("Proximity active count is negative (%d)!", mProximityActiveCount);
1619 }
1620 activeStateChanged = prevCount > 0 && mProximityActiveCount <= 0;
1621 }
1622
1623 if (activeStateChanged) {
1624 notifyProximityStateLocked(mProximityActiveListeners);
1625 }
1626}
1627
1628void SensorService::notifyProximityStateLocked(
1629 const std::vector<sp<ProximityActiveListener>>& listnrs) {
1630 std::async(
1631 std::launch::async,
1632 [](uint64_t mySeq, bool isActive, std::vector<sp<ProximityActiveListener>> listeners) {
1633 while (completedCallbackSeq.load() != mySeq - 1)
1634 std::this_thread::sleep_for(1ms);
1635 for (auto& listener : listeners)
1636 listener->onProximityActive(isActive);
1637 completedCallbackSeq++;
1638 },
1639 ++curProxCallbackSeq, mProximityActiveCount > 0,
1640 listnrs /* (this is meant to be a copy) */
1641 );
1642}
1643
1644status_t SensorService::addProximityActiveListener(const sp<ProximityActiveListener>& callback) {
1645 if (callback == nullptr) {
1646 return BAD_VALUE;
1647 }
1648
1649 Mutex::Autolock _l(mLock);
1650
1651 // Check if the callback was already added.
1652 for (const auto& cb : mProximityActiveListeners) {
1653 if (cb == callback) {
1654 return ALREADY_EXISTS;
1655 }
1656 }
1657
1658 mProximityActiveListeners.push_back(callback);
1659 std::vector<sp<ProximityActiveListener>> listener(1, callback);
1660 notifyProximityStateLocked(listener);
1661 return OK;
1662}
1663
1664status_t SensorService::removeProximityActiveListener(
1665 const sp<ProximityActiveListener>& callback) {
1666 if (callback == nullptr) {
1667 return BAD_VALUE;
1668 }
1669
1670 Mutex::Autolock _l(mLock);
1671
1672 for (auto iter = mProximityActiveListeners.begin();
1673 iter != mProximityActiveListeners.end();
1674 ++iter) {
1675 if (*iter == callback) {
1676 mProximityActiveListeners.erase(iter);
1677 return OK;
1678 }
1679 }
1680 return NAME_NOT_FOUND;
1681}
1682
Peng Xu755c4512016-04-07 23:15:14 -07001683sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001684 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001685}
1686
Mathias Agopianfc328812010-07-14 23:41:37 -07001687status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001688 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001689 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001690 if (mInitCheck != NO_ERROR)
1691 return mInitCheck;
1692
Peng Xu755c4512016-04-07 23:15:14 -07001693 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1694 if (sensor == nullptr ||
1695 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001696 return BAD_VALUE;
1697 }
1698
Brian Duddie967ce172019-06-10 11:08:27 -07001699 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001700 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001701 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001702 return INVALID_OPERATION;
1703 }
1704
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001705 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001706 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001707 rec = new SensorRecord(connection);
1708 mActiveSensors.add(handle, rec);
1709 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001710 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001711 }
Brian Stack26029ee2019-04-22 17:25:49 -07001712
1713 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1714 // the recent event as stale to ensure that the previous event is not sent to a client. This
1715 // ensures on-change events that were generated during a previous sensor activation are not
1716 // erroneously sent to newly connected clients, especially if a second client registers for
1717 // an on-change sensor before the first client receives the updated event. Once an updated
1718 // event is received, the recent events will be marked as current, and any new clients will
1719 // immediately receive the most recent event.
1720 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1721 auto logger = mRecentEvent.find(handle);
1722 if (logger != mRecentEvent.end()) {
1723 logger->second->setLastEventStale();
1724 }
1725 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001726 } else {
1727 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001728 // this sensor is already activated, but we are adding a connection that uses it.
1729 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001730 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001731 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001732 // NOTE: The wake_up flag of this event may get set to
1733 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001734
1735 auto logger = mRecentEvent.find(handle);
1736 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001737 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001738 // Verify that the last sensor event was generated from the current activation
1739 // of the sensor. If not, it is possible for an on-change sensor to receive a
1740 // sensor event that is stale if two clients re-activate the sensor
1741 // simultaneously.
1742 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001743 event.sensor = handle;
1744 if (event.version == sizeof(sensors_event_t)) {
1745 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1746 setWakeLockAcquiredLocked(true);
1747 }
Yi Kong8f313e32018-07-17 14:13:29 -07001748 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001749 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001750 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001751 }
1752 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001753 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001754 }
1755 }
1756 }
1757 }
1758
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001759 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001760 BatteryService::enableSensor(connection->getUid(), handle);
1761 // the sensor was added (which means it wasn't already there)
1762 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001763 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001764 } else {
1765 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1766 handle, connection.get());
1767 }
1768
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301769 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001770 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301771 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1772 samplingPeriodNs = maxDelayNs;
1773 }
1774
Aravind Akella724d91d2013-06-27 12:04:23 -07001775 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1776 if (samplingPeriodNs < minDelayNs) {
1777 samplingPeriodNs = minDelayNs;
1778 }
1779
Aravind Akella6c2664a2014-08-13 12:24:50 -07001780 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1781 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001782 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1783
Aravind Akella4949c502015-02-11 15:54:35 -08001784 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001785 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001786
Peng Xu20483c42015-10-26 15:14:43 -07001787 // Call flush() before calling activate() on the sensor. Wait for a first
1788 // flush complete event before sending events on this connection. Ignore
1789 // one-shot sensors which don't support flush(). Ignore on-change sensors
1790 // to maintain the on-change logic (any on-change events except the initial
1791 // one should be trigger by a change in value). Also if this sensor isn't
1792 // already active, don't call flush().
1793 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001794 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001795 rec->getNumConnections() > 1) {
1796 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001797 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001798 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001799 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001800 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001801 } else {
1802 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001803 }
1804 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001805
1806 if (err == NO_ERROR) {
1807 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1808 err = sensor->activate(connection.get(), true);
1809 }
1810
Aravind Akella8a969552014-09-28 17:52:41 -07001811 if (err == NO_ERROR) {
1812 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001813
Brian Stack240d1d62019-05-17 09:49:39 -07001814 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1815 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001816 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1817 }
1818
Peng Xu51224682017-03-10 16:57:27 -08001819 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1820 SensorRegistrationInfo(handle, connection->getPackageName(),
1821 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001822 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001823 }
1824
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001825 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001826 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001827 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001828 }
1829 return err;
1830}
1831
Peng Xu47e96012016-03-28 17:55:56 -07001832status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001833 if (mInitCheck != NO_ERROR)
1834 return mInitCheck;
1835
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001836 Mutex::Autolock _l(mLock);
1837 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001838 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001839 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1840 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001841
1842 }
1843 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001844 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1845 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001846 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001847 }
1848 return err;
1849}
1850
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001851status_t SensorService::cleanupWithoutDisable(
1852 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001853 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001854 return cleanupWithoutDisableLocked(connection, handle);
1855}
1856
1857status_t SensorService::cleanupWithoutDisableLocked(
1858 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001859 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001860 if (rec) {
1861 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001862 if (connection->removeSensor(handle)) {
1863 BatteryService::disableSensor(connection->getUid(), handle);
1864 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001865 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001866 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001867 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001868 }
1869 // see if this sensor becomes inactive
1870 if (rec->removeConnection(connection)) {
1871 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001872 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001873 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001874 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001875 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001876 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001877 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001878}
1879
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001880status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001881 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001882 if (mInitCheck != NO_ERROR)
1883 return mInitCheck;
1884
Peng Xu755c4512016-04-07 23:15:14 -07001885 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1886 if (sensor == nullptr ||
1887 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001888 return BAD_VALUE;
1889 }
1890
Mathias Agopian1cd70002010-07-21 15:59:50 -07001891 if (ns < 0)
1892 return BAD_VALUE;
1893
Mathias Agopian62569ec2011-11-07 21:21:47 -08001894 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1895 if (ns < minDelayNs) {
1896 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001897 }
1898
Mathias Agopianf001c922010-11-11 17:58:51 -08001899 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001900}
1901
Svetoslavb412f6e2015-04-29 16:50:41 -07001902status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1903 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001904 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001905 SensorDevice& dev(SensorDevice::getInstance());
1906 const int halVersion = dev.getHalDeviceVersion();
1907 status_t err(NO_ERROR);
1908 Mutex::Autolock _l(mLock);
1909 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07001910 for (int handle : connection->getActiveSensorHandles()) {
Peng Xu755c4512016-04-07 23:15:14 -07001911 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1912 if (sensor == nullptr) {
1913 continue;
1914 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001915 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1916 ALOGE("flush called on a one-shot sensor");
1917 err = INVALID_OPERATION;
1918 continue;
1919 }
Aravind Akella8493b792014-09-08 15:45:47 -07001920 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001921 // For older devices just increment pending flush count which will send a trivial
1922 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07001923 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
1924 ALOGE("flush called on an inaccessible sensor");
1925 err = INVALID_OPERATION;
1926 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001927 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001928 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1929 err = INVALID_OPERATION;
1930 continue;
1931 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001932 status_t err_flush = sensor->flush(connection.get(), handle);
1933 if (err_flush == NO_ERROR) {
1934 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001935 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001936 }
1937 err = (err_flush != NO_ERROR) ? err_flush : err;
1938 }
Aravind Akella70018042014-04-07 22:52:37 +00001939 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07001940 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001941}
Aravind Akella70018042014-04-07 22:52:37 +00001942
Svetoslavb412f6e2015-04-29 16:50:41 -07001943bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1944 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001945 // Check if a permission is required for this sensor
1946 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001947 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001948 }
1949
Brian Stack793f4642019-04-18 17:21:34 -07001950 const int32_t opCode = sensor.getRequiredAppOp();
Brian Duddie457e6392020-06-19 11:38:29 -07001951 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07001952
Brian Stack793f4642019-04-18 17:21:34 -07001953 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07001954 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
1955 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1956 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
1957 // Allow access to step sensors if the application targets pre-Q, which is before the
1958 // requirement to hold the AR permission to access Step Counter and Step Detector events
1959 // was introduced.
1960 canAccess = true;
1961 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07001962 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001963 if (opCode >= 0) {
1964 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1965 IPCThreadState::self()->getCallingUid(), opPackageName);
1966 canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
1967 } else {
Brian Stack793f4642019-04-18 17:21:34 -07001968 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001969 }
Brian Stack793f4642019-04-18 17:21:34 -07001970 }
1971
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001972 if (!canAccess) {
Brian Duddie457e6392020-06-19 11:38:29 -07001973 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
1974 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07001975 }
1976
1977 return canAccess;
1978}
1979
1980bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001981 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001982 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001983
1984 // Runtime permissions can't use the cache as they may change.
1985 if (sensor.isRequiredPermissionRuntime()) {
1986 hasPermission = checkPermission(String16(requiredPermission),
1987 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001988 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001989 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1990 }
Brian Stack793f4642019-04-18 17:21:34 -07001991 return hasPermission;
1992}
Svetoslavb412f6e2015-04-29 16:50:41 -07001993
Brian Stack793f4642019-04-18 17:21:34 -07001994int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Anthony Stange07eb4212020-08-28 14:50:28 -04001995 // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
1996 // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
1997 // give it elevated privileges.
1998 if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
1999 return -1;
2000 }
2001
Brian Stack793f4642019-04-18 17:21:34 -07002002 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2003 int targetSdkVersion = -1;
2004 auto entry = sPackageTargetVersion.find(opPackageName);
2005 if (entry != sPackageTargetVersion.end()) {
2006 targetSdkVersion = entry->second;
2007 } else {
2008 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2009 if (binder != nullptr) {
2010 sp<content::pm::IPackageManagerNative> packageManager =
2011 interface_cast<content::pm::IPackageManagerNative>(binder);
2012 if (packageManager != nullptr) {
2013 binder::Status status = packageManager->getTargetSdkVersionForPackage(
2014 opPackageName, &targetSdkVersion);
2015 if (!status.isOk()) {
2016 targetSdkVersion = -1;
2017 }
2018 }
Svetoslavb412f6e2015-04-29 16:50:41 -07002019 }
Brian Stack793f4642019-04-18 17:21:34 -07002020 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07002021 }
Brian Stack793f4642019-04-18 17:21:34 -07002022 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00002023}
2024
Aravind Akella9a844cf2014-02-11 18:58:52 -08002025void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07002026 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2027 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08002028}
2029
Brian Duddie967ce172019-06-10 11:08:27 -07002030void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002031 if (!mWakeLockAcquired) {
2032 return;
2033 }
2034 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07002035 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
2036 if (connection->needsWakeLock()) {
2037 releaseLock = false;
2038 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08002039 }
2040 }
2041 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07002042 setWakeLockAcquiredLocked(false);
2043 }
2044}
2045
2046void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
2047 Mutex::Autolock _l(mLock);
2048 connection->writeToSocketFromCache();
2049 if (connection->needsWakeLock()) {
2050 setWakeLockAcquiredLocked(true);
2051 }
2052}
2053
Aravind Akella4949c502015-02-11 15:54:35 -08002054bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07002055 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08002056}
2057
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002058bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08002059 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07002060 String8 package(opPackageName);
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002061 return !isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07002062 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002063 return false;
Peng Xue36e3472016-11-03 11:57:10 -07002064}
2065
Svet Ganove752a5c2018-01-15 17:14:20 -08002066void SensorService::UidPolicy::registerSelf() {
2067 ActivityManager am;
2068 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
2069 | ActivityManager::UID_OBSERVER_IDLE
2070 | ActivityManager::UID_OBSERVER_ACTIVE,
2071 ActivityManager::PROCESS_STATE_UNKNOWN,
2072 String16("android"));
2073}
2074
2075void SensorService::UidPolicy::unregisterSelf() {
2076 ActivityManager am;
2077 am.unregisterUidObserver(this);
2078}
2079
2080void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
2081 onUidIdle(uid, disabled);
2082}
2083
2084void SensorService::UidPolicy::onUidActive(uid_t uid) {
2085 {
2086 Mutex::Autolock _l(mUidLock);
2087 mActiveUids.insert(uid);
2088 }
2089 sp<SensorService> service = mService.promote();
2090 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002091 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002092 }
2093}
2094
2095void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
2096 bool deleted = false;
2097 {
2098 Mutex::Autolock _l(mUidLock);
2099 if (mActiveUids.erase(uid) > 0) {
2100 deleted = true;
2101 }
2102 }
2103 if (deleted) {
2104 sp<SensorService> service = mService.promote();
2105 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002106 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002107 }
2108 }
2109}
2110
2111void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
2112 updateOverrideUid(uid, active, true);
2113}
2114
2115void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
2116 updateOverrideUid(uid, false, false);
2117}
2118
2119void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
2120 bool wasActive = false;
2121 bool isActive = false;
2122 {
2123 Mutex::Autolock _l(mUidLock);
2124 wasActive = isUidActiveLocked(uid);
2125 mOverrideUids.erase(uid);
2126 if (insert) {
2127 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2128 }
2129 isActive = isUidActiveLocked(uid);
2130 }
2131 if (wasActive != isActive) {
2132 sp<SensorService> service = mService.promote();
2133 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002134 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002135 }
2136 }
2137}
2138
2139bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2140 // Non-app UIDs are considered always active
2141 if (uid < FIRST_APPLICATION_UID) {
2142 return true;
2143 }
2144 Mutex::Autolock _l(mUidLock);
2145 return isUidActiveLocked(uid);
2146}
2147
2148bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2149 // Non-app UIDs are considered always active
2150 if (uid < FIRST_APPLICATION_UID) {
2151 return true;
2152 }
2153 auto it = mOverrideUids.find(uid);
2154 if (it != mOverrideUids.end()) {
2155 return it->second;
2156 }
2157 return mActiveUids.find(uid) != mActiveUids.end();
2158}
2159
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002160bool SensorService::isUidActive(uid_t uid) {
2161 return mUidPolicy->isUidActive(uid);
2162}
2163
Anh Phamaf91a912021-02-10 14:10:53 +01002164bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2165 int targetSdk = getTargetSdkVersion(opPackageName);
2166 bool hasSamplingRatePermission = PermissionCache::checkCallingPermission(
2167 sAccessHighSensorSamplingRatePermission);
2168 if (targetSdk < __ANDROID_API_S__ ||
2169 (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2170 return false;
2171 }
2172 return true;
2173}
2174
Anh Pham3dae77f2021-06-11 16:24:37 +02002175/**
2176 * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS
2177 * permission.
2178 *
2179 * This needs to be kept in sync with the list defined on the Java side
2180 * in frameworks/base/core/java/android/hardware/SystemSensorManager.java
2181 */
Anh Phamaf91a912021-02-10 14:10:53 +01002182bool SensorService::isSensorInCappedSet(int sensorType) {
2183 return (sensorType == SENSOR_TYPE_ACCELEROMETER
2184 || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2185 || sensorType == SENSOR_TYPE_GYROSCOPE
2186 || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2187 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2188 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2189}
2190
2191status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2192 const String16& opPackageName) {
Anh Pham5198c992021-02-10 14:15:30 +01002193 uid_t uid = IPCThreadState::self()->getCallingUid();
Anh Phamaf91a912021-02-10 14:10:53 +01002194 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
2195 if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2196 return OK;
2197 }
2198 if (shouldCapBasedOnPermission) {
2199 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2200 if (isPackageDebuggable(opPackageName)) {
2201 return PERMISSION_DENIED;
2202 }
2203 return OK;
2204 }
Anh Pham5198c992021-02-10 14:15:30 +01002205 if (isMicSensorPrivacyEnabledForUid(uid)) {
2206 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2207 return OK;
2208 }
Anh Phamaf91a912021-02-10 14:10:53 +01002209 return OK;
2210}
2211
2212status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2213 const String16& opPackageName) {
2214 uid_t uid = IPCThreadState::self()->getCallingUid();
2215 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
2216
2217 if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2218 return OK;
2219 }
2220 if (shouldCapBasedOnPermission) {
2221 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2222 if (isPackageDebuggable(opPackageName)) {
2223 return PERMISSION_DENIED;
2224 }
2225 return OK;
2226 }
Anh Pham5198c992021-02-10 14:15:30 +01002227 if (isMicSensorPrivacyEnabledForUid(uid)) {
2228 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2229 return OK;
2230 }
Anh Phamaf91a912021-02-10 14:10:53 +01002231 return OK;
2232}
2233
Michael Groover5e1f60b2018-12-04 22:34:29 -08002234void SensorService::SensorPrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002235 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002236 SensorPrivacyManager spm;
2237 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2238 spm.addSensorPrivacyListener(this);
2239}
2240
2241void SensorService::SensorPrivacyPolicy::unregisterSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002242 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002243 SensorPrivacyManager spm;
Evan Severson7bfa35e2021-05-19 16:10:29 -07002244 if (mIsIndividualMic) {
2245 spm.removeIndividualSensorPrivacyListener(
2246 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE, this);
2247 } else {
2248 spm.removeSensorPrivacyListener(this);
2249 }
Michael Groover5e1f60b2018-12-04 22:34:29 -08002250}
2251
2252bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2253 return mSensorPrivacyEnabled;
2254}
2255
2256binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2257 mSensorPrivacyEnabled = enabled;
2258 sp<SensorService> service = mService.promote();
Anh Pham5198c992021-02-10 14:15:30 +01002259
Michael Groover5e1f60b2018-12-04 22:34:29 -08002260 if (service != nullptr) {
Anh Pham5198c992021-02-10 14:15:30 +01002261 if (mIsIndividualMic) {
2262 if (enabled) {
2263 service->capRates(mUserId);
2264 } else {
2265 service->uncapRates(mUserId);
2266 }
Michael Groover5e1f60b2018-12-04 22:34:29 -08002267 } else {
Anh Pham5198c992021-02-10 14:15:30 +01002268 if (enabled) {
2269 service->disableAllSensors();
2270 } else {
2271 service->enableAllSensors();
2272 }
Michael Groover5e1f60b2018-12-04 22:34:29 -08002273 }
2274 }
2275 return binder::Status::ok();
2276}
Brian Duddie967ce172019-06-10 11:08:27 -07002277
Anh Pham5198c992021-02-10 14:15:30 +01002278status_t SensorService::SensorPrivacyPolicy::registerSelfForIndividual(int userId) {
2279 Mutex::Autolock _l(mSensorPrivacyLock);
Anh Phamb04658b2021-03-22 18:17:17 +01002280 AutoCallerClear acc;
Anh Pham5198c992021-02-10 14:15:30 +01002281 SensorPrivacyManager spm;
2282 status_t err = spm.addIndividualSensorPrivacyListener(userId,
2283 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE, this);
2284
2285 if (err != OK) {
2286 ALOGE("Cannot register a mic listener.");
2287 return err;
2288 }
2289 mSensorPrivacyEnabled = spm.isIndividualSensorPrivacyEnabled(userId,
2290 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE);
2291
2292 mIsIndividualMic = true;
2293 mUserId = userId;
2294 return OK;
2295}
2296
2297bool SensorService::isMicSensorPrivacyEnabledForUid(uid_t uid) {
2298 userid_t userId = multiuser_get_user_id(uid);
2299 if (mMicSensorPrivacyPolicies.find(userId) == mMicSensorPrivacyPolicies.end()) {
2300 sp<SensorPrivacyPolicy> userPolicy = new SensorPrivacyPolicy(this);
2301 if (userPolicy->registerSelfForIndividual(userId) != OK) {
2302 return false;
2303 }
2304 mMicSensorPrivacyPolicies[userId] = userPolicy;
2305 }
2306 return mMicSensorPrivacyPolicies[userId]->isSensorPrivacyEnabled();
2307}
2308
Brian Duddie967ce172019-06-10 11:08:27 -07002309SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2310 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2311 : mConnectionHolder(holder), mAutolock(mutex) {}
2312
2313template<typename ConnectionType>
2314const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2315 const SortedVector<wp<ConnectionType>>& connectionList,
2316 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2317 referenceHolder->emplace_back();
2318 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2319 for (const wp<ConnectionType>& weakConnection : connectionList){
2320 sp<ConnectionType> connection = weakConnection.promote();
2321 if (connection != nullptr) {
2322 connections.push_back(std::move(connection));
2323 }
2324 }
2325 return connections;
2326}
2327
2328const std::vector<sp<SensorService::SensorEventConnection>>&
2329 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2330 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2331 &mReferencedActiveConnections);
2332}
2333
2334const std::vector<sp<SensorService::SensorDirectConnection>>&
2335 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2336 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2337 &mReferencedDirectConnections);
2338}
2339
2340void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2341 const sp<SensorService::SensorEventConnection>& connection) {
2342 if (mActiveConnections.indexOf(connection) < 0) {
2343 mActiveConnections.add(connection);
2344 }
2345}
2346
2347void SensorService::SensorConnectionHolder::removeEventConnection(
2348 const wp<SensorService::SensorEventConnection>& connection) {
2349 mActiveConnections.remove(connection);
2350}
2351
2352void SensorService::SensorConnectionHolder::addDirectConnection(
2353 const sp<SensorService::SensorDirectConnection>& connection) {
2354 mDirectConnections.add(connection);
2355}
2356
2357void SensorService::SensorConnectionHolder::removeDirectConnection(
2358 const wp<SensorService::SensorDirectConnection>& connection) {
2359 mDirectConnections.remove(connection);
2360}
2361
2362SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2363 return ConnectionSafeAutolock(*this, mutex);
2364}
2365
Anh Phamaf91a912021-02-10 14:10:53 +01002366bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2367 bool debugMode = false;
2368 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2369 if (binder != nullptr) {
2370 sp<content::pm::IPackageManagerNative> packageManager =
2371 interface_cast<content::pm::IPackageManagerNative>(binder);
2372 if (packageManager != nullptr) {
2373 binder::Status status = packageManager->isPackageDebuggable(
2374 opPackageName, &debugMode);
2375 }
2376 }
2377 return debugMode;
2378}
Brian Duddie967ce172019-06-10 11:08:27 -07002379} // namespace android