blob: e0a4f034cba30d640e631f7fa8df5e39914b2f91 [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"
Tyler Trephanc7b92632021-07-21 10:39:38 -070041#include "LimitedAxesImuSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080042#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070043#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080044#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070045#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070046#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080047
Mathias Agopian984826c2011-05-17 22:54:42 -070048#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070049#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080050#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080051#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080052#include "SensorRecord.h"
53#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080054
55#include <inttypes.h>
56#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070057#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080058#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080059#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070060#include <sys/stat.h>
61#include <sys/types.h>
62#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070063
Andrew Lehmer3a602572021-03-25 15:19:56 -070064#include <ctime>
65#include <future>
66
Svet Ganove752a5c2018-01-15 17:14:20 -080067#include <private/android_filesystem_config.h>
68
Andrew Lehmer3a602572021-03-25 15:19:56 -070069using namespace std::chrono_literals;
70
Mathias Agopianfc328812010-07-14 23:41:37 -070071namespace android {
72// ---------------------------------------------------------------------------
73
Mathias Agopian33015422011-05-27 18:18:13 -070074/*
75 * Notes:
76 *
77 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070078 * - run mag sensor from time to time to force calibration
79 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
80 *
81 */
82
Aravind Akella8ef3c892015-07-10 11:24:28 -070083const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070084uint8_t SensorService::sHmacGlobalKey[128] = {};
85bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070086std::map<String16, int> SensorService::sPackageTargetVersion;
87Mutex SensorService::sPackageTargetVersionLock;
Anthony Stange07eb4212020-08-28 14:50:28 -040088String16 SensorService::sSensorInterfaceDescriptorPrefix =
89 String16("android.frameworks.sensorservice@");
Brian Stack793f4642019-04-18 17:21:34 -070090AppOpsManager SensorService::sAppOpsManager;
Andrew Lehmer3a602572021-03-25 15:19:56 -070091std::atomic_uint64_t SensorService::curProxCallbackSeq(0);
92std::atomic_uint64_t SensorService::completedCallbackSeq(0);
Greg Kaiser53ca2e02016-06-21 16:11:14 -070093
94#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
95#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070096#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070097
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070098// Permissions.
Anh Phamaf91a912021-02-10 14:10:53 +010099static const String16 sAccessHighSensorSamplingRatePermission(
100 "android.permission.HIGH_SAMPLING_RATE_SENSORS");
Peng Xudd5c5cb2017-03-16 17:39:43 -0700101static const String16 sDumpPermission("android.permission.DUMP");
102static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -0800103static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700104
Tyler Trephanc7b92632021-07-21 10:39:38 -0700105static bool isAutomotive() {
106 sp<IServiceManager> serviceManager = defaultServiceManager();
107 if (serviceManager.get() == nullptr) {
108 ALOGE("%s: unable to access native ServiceManager", __func__);
109 return false;
110 }
111
112 sp<content::pm::IPackageManagerNative> packageManager;
113 sp<IBinder> binder = serviceManager->waitForService(String16("package_native"));
114 packageManager = interface_cast<content::pm::IPackageManagerNative>(binder);
115 if (packageManager == nullptr) {
116 ALOGE("%s: unable to access native PackageManager", __func__);
117 return false;
118 }
119
120 bool isAutomotive = false;
121 binder::Status status =
122 packageManager->hasSystemFeature(String16("android.hardware.type.automotive"), 0,
123 &isAutomotive);
124 if (!status.isOk()) {
125 ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str());
126 return false;
127 }
128
129 return isAutomotive;
130}
131
Mathias Agopianfc328812010-07-14 23:41:37 -0700132SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -0700133 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700134 mWakeLockAcquired(false), mLastReportedProxIsActive(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +0900135 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800136 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Evan Severson4c197852022-01-27 10:44:27 -0800137 mMicSensorPrivacyPolicy = new MicrophonePrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700138}
139
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700140bool SensorService::initializeHmacKey() {
141 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
142 if (fd != -1) {
143 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
144 close(fd);
145 if (result == sizeof(sHmacGlobalKey)) {
146 return true;
147 }
148 ALOGW("Unable to read HMAC key; generating new one.");
149 }
150
151 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
152 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
153 return false;
154 }
155
156 // We need to make sure this is only readable to us.
157 bool wroteKey = false;
158 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
159 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
160 S_IRUSR|S_IWUSR);
161 if (fd != -1) {
162 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
163 close(fd);
164 wroteKey = (result == sizeof(sHmacGlobalKey));
165 }
166 if (wroteKey) {
167 ALOGI("Generated new HMAC key.");
168 } else {
169 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
170 "after reboot.");
171 }
172 // Even if we failed to write the key we return true, because we did
173 // initialize the HMAC key.
174 return true;
175}
176
Peng Xu98d30f62016-08-01 18:12:11 -0700177// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
178void SensorService::enableSchedFifoMode() {
179 struct sched_param param = {0};
180 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
181 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
182 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
183 }
184}
185
Peng Xu47e96012016-03-28 17:55:56 -0700186void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000187 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800188 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700189
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700190 sHmacGlobalKeyIsValid = initializeHmacKey();
191
Mathias Agopianf001c922010-11-11 17:58:51 -0800192 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800193 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700194 ssize_t count = dev.getSensorList(&list);
195 if (count > 0) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700196 bool hasGyro = false, hasAccel = false, hasMag = false;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700197 bool hasGyroUncalibrated = false;
198 bool hasAccelUncalibrated = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700199 uint32_t virtualSensorsNeeds =
200 (1<<SENSOR_TYPE_GRAVITY) |
201 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700202 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
203 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
204 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700205
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700206 for (ssize_t i=0 ; i<count ; i++) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700207 bool useThisSensor = true;
Peng Xuf66684a2015-07-23 11:41:53 -0700208
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700209 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700210 case SENSOR_TYPE_ACCELEROMETER:
211 hasAccel = true;
212 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700213 case SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED:
214 hasAccelUncalibrated = true;
215 break;
Aravind Akellaf5047892015-07-20 17:29:33 -0700216 case SENSOR_TYPE_MAGNETIC_FIELD:
217 hasMag = true;
218 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700219 case SENSOR_TYPE_GYROSCOPE:
220 hasGyro = true;
221 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700222 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
223 hasGyroUncalibrated = true;
224 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700225 case SENSOR_TYPE_GRAVITY:
226 case SENSOR_TYPE_LINEAR_ACCELERATION:
227 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700228 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
229 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
230 if (IGNORE_HARDWARE_FUSION) {
231 useThisSensor = false;
232 } else {
233 virtualSensorsNeeds &= ~(1<<list[i].type);
234 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700235 break;
Arthur Ishiguro2fd90a72021-11-12 17:24:41 +0000236 default:
237 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700238 }
Peng Xuf66684a2015-07-23 11:41:53 -0700239 if (useThisSensor) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700240 if (list[i].type == SENSOR_TYPE_PROXIMITY) {
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700241 SensorInterface* s = new ProximitySensor(list[i], *this);
242 registerSensor(s);
243 mProxSensorHandles.push_back(s->getSensor().getHandle());
Andrew Lehmer3a602572021-03-25 15:19:56 -0700244 } else {
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700245 registerSensor(new HardwareSensor(list[i]));
Andrew Lehmer3a602572021-03-25 15:19:56 -0700246 }
Peng Xuf66684a2015-07-23 11:41:53 -0700247 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700248 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700249
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700250 // it's safe to instantiate the SensorFusion object here
251 // (it wants to be instantiated after h/w sensors have been
252 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700253 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700254
Tyler Trephanc7b92632021-07-21 10:39:38 -0700255 if ((hasGyro || hasGyroUncalibrated) && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700256 // Add Android virtual sensors if they're not already
257 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700258 bool needRotationVector =
259 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700260
Peng Xu0cc8f802016-04-05 23:46:03 -0700261 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
262 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700263
Peng Xu0cc8f802016-04-05 23:46:03 -0700264 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700265 registerSensor( new CorrectedGyroSensor(list, count), true, true);
266 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700267 }
268
Tyler Trephanc7b92632021-07-21 10:39:38 -0700269 if (hasAccel && (hasGyro || hasGyroUncalibrated)) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700270 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
271 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700272
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800273 bool needLinearAcceleration =
274 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
275 registerSensor(new LinearAccelerationSensor(list, count),
276 !needLinearAcceleration, true);
277
Peng Xu0cc8f802016-04-05 23:46:03 -0700278 bool needGameRotationVector =
279 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
280 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700281 }
282
283 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700284 bool needGeoMagRotationVector =
285 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
286 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700287 }
288
Tyler Trephanc7b92632021-07-21 10:39:38 -0700289 if (isAutomotive()) {
290 if (hasAccel) {
291 registerSensor(new LimitedAxesImuSensor(list, count, SENSOR_TYPE_ACCELEROMETER),
292 /*isDebug=*/false, /*isVirtual=*/true);
293 }
294
295 if (hasGyro) {
296 registerSensor(new LimitedAxesImuSensor(list, count, SENSOR_TYPE_GYROSCOPE),
297 /*isDebug=*/false, /*isVirtual=*/true);
298 }
299
300 if (hasAccelUncalibrated) {
301 registerSensor(new LimitedAxesImuSensor(list, count,
302 SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED),
303 /*isDebug=*/false, /*isVirtual=*/true);
304 }
305
306 if (hasGyroUncalibrated) {
307 registerSensor(new LimitedAxesImuSensor(list, count,
308 SENSOR_TYPE_GYROSCOPE_UNCALIBRATED),
309 /*isDebug=*/false, /*isVirtual=*/true);
310 }
311 }
312
Aravind Akella5466c3d2014-08-22 16:11:10 -0700313 // Check if the device really supports batching by looking at the FIFO event
314 // counts for each sensor.
315 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700316 mSensors.forEachSensor(
317 [&batchingSupported] (const Sensor& s) -> bool {
318 if (s.getFifoMaxEventCount() > 0) {
319 batchingSupported = true;
320 }
321 return !batchingSupported;
322 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700323
324 if (batchingSupported) {
325 // Increase socket buffer size to a max of 100 KB for batching capabilities.
326 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
327 } else {
328 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
329 }
330
331 // Compare the socketBufferSize value against the system limits and limit
332 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700333 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
334 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700335 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700336 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700337 size_t maxSystemSocketBufferSize;
338 sscanf(line, "%zu", &maxSystemSocketBufferSize);
339 if (mSocketBufferSize > maxSystemSocketBufferSize) {
340 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700341 }
342 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700343 if (fp) {
344 fclose(fp);
345 }
346
Aravind Akella9a844cf2014-02-11 18:58:52 -0800347 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700348 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700349 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
350 mSensorEventBuffer = new sensors_event_t[minBufferSize];
351 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700352 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700353 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700354
Aravind Akella18d6d512015-06-18 14:18:28 -0700355 mNextSensorRegIndex = 0;
356 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
357 mLastNSensorRegistrations.push();
358 }
359
360 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700361 mAckReceiver = new SensorEventAckReceiver(this);
362 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700363 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700364
365 // priority can only be changed after run
366 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800367
368 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800369 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800370
371 // Start watching sensor privacy changes
372 mSensorPrivacyPolicy->registerSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800373
374 // Start watching mic sensor privacy changes
375 mMicSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800376 }
377 }
378}
379
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700380void SensorService::onUidStateChanged(uid_t uid, UidState state) {
381 SensorDevice& dev(SensorDevice::getInstance());
382
Brian Duddie967ce172019-06-10 11:08:27 -0700383 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700384 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700385 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700386 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700387 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700388 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700389
390 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
391 if (conn->getUid() == uid) {
392 // Update sensor subscriptions if needed
393 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
394 conn->onSensorAccessChanged(hasAccess);
395 }
396 }
Chris Kuiper587ef9b2021-10-12 16:36:43 -0700397 checkAndReportProxStateChangeLocked();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700398}
399
400bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
401 Mutex::Autolock _l(mLock);
402 return hasSensorAccessLocked(uid, opPackageName);
403}
404
405bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
406 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
407 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700408}
409
Peng Xu0cc8f802016-04-05 23:46:03 -0700410const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
411 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800412 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700413 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700414 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700415 return s->getSensor();
416 } else {
417 return mSensors.getNonSensor();
418 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800419}
420
Peng Xu6a2d3a02015-12-21 12:00:23 -0800421const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700422 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800423}
424
Peng Xu6a2d3a02015-12-21 12:00:23 -0800425bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700426 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800427
428 const auto i = mRecentEvent.find(handle);
429 if (i != mRecentEvent.end()) {
430 delete i->second;
431 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800432 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700433 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800434}
435
Peng Xu0cc8f802016-04-05 23:46:03 -0700436const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
437 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700438}
439
Peng Xu47e96012016-03-28 17:55:56 -0700440SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800441 for (auto && entry : mRecentEvent) {
442 delete entry.second;
443 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800444 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800445 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800446 mMicSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700447}
448
449status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700450 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700451 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800452 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700453 IPCThreadState::self()->getCallingPid(),
454 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700455 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700456 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700457 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800458 return INVALID_OPERATION;
459 }
Brian Duddie967ce172019-06-10 11:08:27 -0700460 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800461 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700462 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700463 // If already in restricted mode. Ignore.
464 if (mCurrentOperatingMode == RESTRICTED) {
465 return status_t(NO_ERROR);
466 }
467 // If in any mode other than normal, ignore.
468 if (mCurrentOperatingMode != NORMAL) {
469 return INVALID_OPERATION;
470 }
Peng Xue36e3472016-11-03 11:57:10 -0700471
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700472 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800473 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700474 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700475 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700476 return status_t(NO_ERROR);
477 } else if (args.size() == 1 && args[0] == String16("enable")) {
478 // If currently in restricted mode, reset back to NORMAL mode else ignore.
479 if (mCurrentOperatingMode == RESTRICTED) {
480 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800481 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700482 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700483 }
Aravind Akella841a5922015-06-29 12:37:48 -0700484 if (mCurrentOperatingMode == DATA_INJECTION) {
485 resetToNormalModeLocked();
486 }
487 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700488 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700489 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
490 if (mCurrentOperatingMode == NORMAL) {
491 dev.disableAllSensors();
492 status_t err = dev.setMode(DATA_INJECTION);
493 if (err == NO_ERROR) {
494 mCurrentOperatingMode = DATA_INJECTION;
495 } else {
496 // Re-enable sensors.
497 dev.enableAllSensors();
498 }
499 mWhiteListedPackage.setTo(String8(args[1]));
500 return NO_ERROR;
501 } else if (mCurrentOperatingMode == DATA_INJECTION) {
502 // Already in DATA_INJECTION mode. Treat this as a no_op.
503 return NO_ERROR;
504 } else {
505 // Transition to data injection mode supported only from NORMAL mode.
506 return INVALID_OPERATION;
507 }
Mike Ma24743862020-01-29 00:36:55 -0800508 } else if (args.size() == 1 && args[0] == String16("--proto")) {
509 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700510 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700511 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700512 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700513 } else {
514 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700515 //
Brian Stack51498e62018-10-03 10:52:21 -0700516 timespec curTime;
517 clock_gettime(CLOCK_REALTIME, &curTime);
518 struct tm* timeinfo = localtime(&(curTime.tv_sec));
519 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
520 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800521 result.append("Sensor Device:\n");
522 result.append(SensorDevice::getInstance().dump().c_str());
523
524 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700525 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700526
Peng Xu6a2d3a02015-12-21 12:00:23 -0800527 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700528 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700529
Peng Xu0cc8f802016-04-05 23:46:03 -0700530 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800531 for (auto&& i : mRecentEvent) {
532 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700533 if (!i.second->isEmpty()) {
534 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
535 i.second->setFormat("normal");
536 } else {
537 i.second->setFormat("mask_data");
538 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800539 // if there is events and sensor does not need special permission.
540 result.appendFormat("%s: ", s->getSensor().getName().string());
541 result.append(i.second->dump().c_str());
542 }
543 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700544
Aravind Akella444f2672015-05-07 12:40:52 -0700545 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700546 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700547 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
548 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700549 if (dev.isSensorActive(handle)) {
550 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
551 getSensorName(handle).string(),
552 handle,
553 mActiveSensors.valueAt(i)->getNumConnections());
554 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700555 }
556
Andreas Gamped4036b62015-07-28 13:49:04 -0700557 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700558 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700559 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
560 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700561 result.appendFormat("Mode :");
562 switch(mCurrentOperatingMode) {
563 case NORMAL:
564 result.appendFormat(" NORMAL\n");
565 break;
566 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700567 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700568 break;
569 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700570 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700571 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800572 result.appendFormat("Sensor Privacy: %s\n",
573 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700574
Brian Duddie967ce172019-06-10 11:08:27 -0700575 const auto& activeConnections = connLock.getActiveConnections();
576 result.appendFormat("%zd active connections\n", activeConnections.size());
577 for (size_t i=0 ; i < activeConnections.size() ; i++) {
578 result.appendFormat("Connection Number: %zu \n", i);
579 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700580 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700581
Brian Duddie967ce172019-06-10 11:08:27 -0700582 const auto& directConnections = connLock.getDirectConnections();
583 result.appendFormat("%zd direct connections\n", directConnections.size());
584 for (size_t i = 0 ; i < directConnections.size() ; i++) {
585 result.appendFormat("Direct connection %zu:\n", i);
586 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700587 }
588
Aravind Akella18d6d512015-06-18 14:18:28 -0700589 result.appendFormat("Previous Registrations:\n");
590 // Log in the reverse chronological order.
591 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
592 SENSOR_REGISTRATIONS_BUF_SIZE;
593 const int startIndex = currentIndex;
594 do {
595 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
596 if (SensorRegistrationInfo::isSentinel(reg_info)) {
597 // Ignore sentinel, proceed to next item.
598 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
599 SENSOR_REGISTRATIONS_BUF_SIZE;
600 continue;
601 }
Peng Xu51224682017-03-10 16:57:27 -0800602 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700603 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
604 SENSOR_REGISTRATIONS_BUF_SIZE;
605 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700606 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700607 }
608 write(fd, result.string(), result.size());
609 return NO_ERROR;
610}
611
Mike Ma24743862020-01-29 00:36:55 -0800612/**
613 * Dump debugging information as android.service.SensorServiceProto protobuf message using
614 * ProtoOutputStream.
615 *
616 * See proto definition and some notes about ProtoOutputStream in
617 * frameworks/base/core/proto/android/service/sensor_service.proto
618 */
619status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
620 using namespace service::SensorServiceProto;
621 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800622 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
623 if (!mSensors.hasAnySensor()) {
624 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
625 }
Mike Ma24743862020-01-29 00:36:55 -0800626 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
627
628 timespec curTime;
629 clock_gettime(CLOCK_REALTIME, &curTime);
630 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
631
632 // Write SensorDeviceProto
633 uint64_t token = proto.start(SENSOR_DEVICE);
634 SensorDevice::getInstance().dump(&proto);
635 proto.end(token);
636
637 // Write SensorListProto
638 token = proto.start(SENSORS);
639 mSensors.dump(&proto);
640 proto.end(token);
641
642 // Write SensorFusionProto
643 token = proto.start(FUSION_STATE);
644 SensorFusion::getInstance().dump(&proto);
645 proto.end(token);
646
647 // Write SensorEventsProto
648 token = proto.start(SENSOR_EVENTS);
649 for (auto&& i : mRecentEvent) {
650 sp<SensorInterface> s = mSensors.getInterface(i.first);
651 if (!i.second->isEmpty()) {
652 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
653 "normal" : "mask_data");
654 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
655 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
656 std::string(s->getSensor().getName().string()));
657 i.second->dump(&proto);
658 proto.end(mToken);
659 }
660 }
661 proto.end(token);
662
663 // Write ActiveSensorProto
664 SensorDevice& dev = SensorDevice::getInstance();
665 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
666 int handle = mActiveSensors.keyAt(i);
667 if (dev.isSensorActive(handle)) {
668 token = proto.start(ACTIVE_SENSORS);
669 proto.write(service::ActiveSensorProto::NAME,
670 std::string(getSensorName(handle).string()));
671 proto.write(service::ActiveSensorProto::HANDLE, handle);
672 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
673 int(mActiveSensors.valueAt(i)->getNumConnections()));
674 proto.end(token);
675 }
676 }
677
678 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
679 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
680 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
681
682 switch(mCurrentOperatingMode) {
683 case NORMAL:
684 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
685 break;
686 case RESTRICTED:
687 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
688 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
689 break;
690 case DATA_INJECTION:
691 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
692 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
693 break;
694 default:
695 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
696 }
697 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
698
699 // Write repeated SensorEventConnectionProto
700 const auto& activeConnections = connLock->getActiveConnections();
701 for (size_t i = 0; i < activeConnections.size(); i++) {
702 token = proto.start(ACTIVE_CONNECTIONS);
703 activeConnections[i]->dump(&proto);
704 proto.end(token);
705 }
706
707 // Write repeated SensorDirectConnectionProto
708 const auto& directConnections = connLock->getDirectConnections();
709 for (size_t i = 0 ; i < directConnections.size() ; i++) {
710 token = proto.start(DIRECT_CONNECTIONS);
711 directConnections[i]->dump(&proto);
712 proto.end(token);
713 }
714
715 // Write repeated SensorRegistrationInfoProto
716 const int startIndex = mNextSensorRegIndex;
717 int curr = startIndex;
718 do {
719 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
720 if (SensorRegistrationInfo::isSentinel(reg_info)) {
721 // Ignore sentinel, proceed to next item.
722 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
723 continue;
724 }
725 token = proto.start(PREVIOUS_REGISTRATIONS);
726 reg_info.dump(&proto);
727 proto.end(token);
728 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
729 } while (startIndex != curr);
730
731 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
732}
733
Michael Groover5e1f60b2018-12-04 22:34:29 -0800734void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700735 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
736 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800737}
738
Brian Duddie967ce172019-06-10 11:08:27 -0700739void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800740 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700741 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
742 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
743 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800744 }
745 dev.disableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700746 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800747 // Clear all pending flush connections for all active sensors. If one of the active
748 // connections has called flush() and the underlying sensor has been disabled before a
749 // flush complete event is returned, we need to remove the connection from this queue.
750 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
751 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
752 }
753}
754
755void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700756 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
757 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800758}
759
Brian Duddie967ce172019-06-10 11:08:27 -0700760void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800761 // sensors should only be enabled if the operating state is not restricted and sensor
762 // privacy is not enabled.
763 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
764 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
765 mCurrentOperatingMode,
766 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
767 return;
768 }
769 SensorDevice& dev(SensorDevice::getInstance());
770 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700771 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
772 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
773 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800774 }
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700775 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800776}
777
Evan Severson4c197852022-01-27 10:44:27 -0800778void SensorService::capRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100779 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
780 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800781 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100782 }
783
784 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800785 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100786 }
787}
788
Evan Severson4c197852022-01-27 10:44:27 -0800789void SensorService::uncapRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100790 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
791 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800792 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100793 }
794
795 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800796 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100797 }
798}
Brian Duddie967ce172019-06-10 11:08:27 -0700799
Svet Ganove752a5c2018-01-15 17:14:20 -0800800// NOTE: This is a remote API - make sure all args are validated
801status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
802 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
803 return PERMISSION_DENIED;
804 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700805 if (args.size() == 0) {
806 return BAD_INDEX;
807 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800808 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
809 return BAD_VALUE;
810 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700811 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800812 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700813 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800814 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700815 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800816 return handleGetUidState(args, out, err);
Brian Duddie4a4d0462022-05-09 16:49:49 -0700817 } else if (args[0] == String16("unrestrict-ht")) {
818 mHtRestricted = false;
819 return NO_ERROR;
820 } else if (args[0] == String16("restrict-ht")) {
821 mHtRestricted = true;
822 return NO_ERROR;
Svet Ganove752a5c2018-01-15 17:14:20 -0800823 } else if (args.size() == 1 && args[0] == String16("help")) {
824 printHelp(out);
825 return NO_ERROR;
826 }
827 printHelp(err);
828 return BAD_VALUE;
829}
830
Tanmay Patild33a1822019-04-11 18:38:55 -0700831static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800832 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700833 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800834 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700835 ALOGE("Unknown package: '%s'", String8(packageName).string());
836 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800837 return BAD_VALUE;
838 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700839
840 if (userId < 0) {
841 ALOGE("Invalid user: %d", userId);
842 dprintf(err, "Invalid user: %d\n", userId);
843 return BAD_VALUE;
844 }
845
846 uid = multiuser_get_uid(userId, uid);
847 return NO_ERROR;
848}
849
850status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
851 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
852 if (!(args.size() == 3 || args.size() == 5)) {
853 printHelp(err);
854 return BAD_VALUE;
855 }
856
Svet Ganove752a5c2018-01-15 17:14:20 -0800857 bool active = false;
858 if (args[2] == String16("active")) {
859 active = true;
860 } else if ((args[2] != String16("idle"))) {
861 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
862 return BAD_VALUE;
863 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700864
865 int userId = 0;
866 if (args.size() == 5 && args[3] == String16("--user")) {
867 userId = atoi(String8(args[4]));
868 }
869
870 uid_t uid;
871 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
872 return BAD_VALUE;
873 }
874
Svet Ganove752a5c2018-01-15 17:14:20 -0800875 mUidPolicy->addOverrideUid(uid, active);
876 return NO_ERROR;
877}
878
879status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700880 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
881 if (!(args.size() == 2 || args.size() == 4)) {
882 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800883 return BAD_VALUE;
884 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700885
886 int userId = 0;
887 if (args.size() == 4 && args[2] == String16("--user")) {
888 userId = atoi(String8(args[3]));
889 }
890
891 uid_t uid;
892 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
893 return BAD_VALUE;
894 }
895
Svet Ganove752a5c2018-01-15 17:14:20 -0800896 mUidPolicy->removeOverrideUid(uid);
897 return NO_ERROR;
898}
899
900status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700901 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
902 if (!(args.size() == 2 || args.size() == 4)) {
903 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800904 return BAD_VALUE;
905 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700906
907 int userId = 0;
908 if (args.size() == 4 && args[2] == String16("--user")) {
909 userId = atoi(String8(args[3]));
910 }
911
912 uid_t uid;
913 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
914 return BAD_VALUE;
915 }
916
Svet Ganove752a5c2018-01-15 17:14:20 -0800917 if (mUidPolicy->isUidActive(uid)) {
918 return dprintf(out, "active\n");
919 } else {
920 return dprintf(out, "idle\n");
921 }
922}
923
924status_t SensorService::printHelp(int out) {
925 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700926 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
927 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
928 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800929 " help print this message\n");
930}
931
Peng Xu0cc8f802016-04-05 23:46:03 -0700932//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800933void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700934 sensors_event_t const* buffer, const int count) {
935 for (int i=0 ; i<count ; i++) {
936 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700937 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
938 handle = buffer[i].meta_data.sensor;
939 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700940 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700941 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700942 // If this buffer has an event from a one_shot sensor and this connection is registered
943 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700944 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700945 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
946 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800947 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700948 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700949
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700950 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700951 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700952}
953
Peng Xu47e96012016-03-28 17:55:56 -0700954bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000955 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700956
Peng Xueb4d6282015-12-10 18:02:41 -0800957 // each virtual sensor could generate an event per "real" event, that's why we need to size
958 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
959 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700960 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700961 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700962 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700963
Mathias Agopianf001c922010-11-11 17:58:51 -0800964 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700965
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700966 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700967 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700968 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
969 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700970 if(count == DEAD_OBJECT && device.isReconnecting()) {
971 device.reconnect();
972 continue;
973 } else {
974 ALOGE("sensor poll failed (%s)", strerror(-count));
975 break;
976 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700977 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700978
979 // Reset sensors_event_t.flags to zero for all events in the buffer.
980 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700981 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700982 }
Brian Duddie967ce172019-06-10 11:08:27 -0700983 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700984
Aravind Akella9a844cf2014-02-11 18:58:52 -0800985 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
986 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
987 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
988 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
989 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700990 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700991 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700992 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700993 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700994 }
995 }
996
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700997 if (wakeEvents > 0) {
998 if (!mWakeLockAcquired) {
999 setWakeLockAcquiredLocked(true);
1000 }
1001 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001002 }
Aravind Akella8493b792014-09-08 15:45:47 -07001003 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -08001004
Mathias Agopianf001c922010-11-11 17:58:51 -08001005 // handle virtual sensors
1006 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -07001007 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -07001008 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001009 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -07001010 SensorFusion& fusion(SensorFusion::getInstance());
1011 if (fusion.isEnabled()) {
1012 for (size_t i=0 ; i<size_t(count) ; i++) {
1013 fusion.process(event[i]);
1014 }
1015 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001016 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -07001017 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001018 if (count + k >= minBufferSize) {
1019 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -07001020 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001021 count, k, minBufferSize);
1022 break;
1023 }
Mathias Agopianf001c922010-11-11 17:58:51 -08001024 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -07001025 sp<SensorInterface> si = mSensors.getInterface(handle);
1026 if (si == nullptr) {
1027 ALOGE("handle %d is not an valid virtual sensor", handle);
1028 continue;
1029 }
1030
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001031 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -07001032 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -08001033 k++;
1034 }
1035 }
1036 }
1037 if (k) {
1038 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -07001039 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -08001040 count += k;
1041 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -07001042 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -07001043 }
1044 }
1045 }
1046
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001047 // handle backward compatibility for RotationVector sensor
1048 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
1049 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001050 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001051 // All the 4 components of the quaternion should be available
1052 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -07001053 mSensorEventBuffer[i].data[4] = -1;
1054 }
1055 }
1056 }
1057
Brian Duddie967ce172019-06-10 11:08:27 -07001058 // Cache the list of active connections, since we use it in multiple places below but won't
1059 // modify it here
1060 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
1061
Aravind Akella8493b792014-09-08 15:45:47 -07001062 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -07001063 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
1064 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
1065 // SensorEventConnection mapped to the corresponding flush_complete_event in
1066 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -07001067 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -07001068 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
1069 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
1070 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001071 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -07001072 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
1073 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001074 }
1075 }
Peng Xu2576cb62016-01-20 00:22:09 -08001076
1077 // handle dynamic sensor meta events, process registration and unregistration of dynamic
1078 // sensor based on content of event.
1079 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
1080 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
1081 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1082 const sensor_t& dynamicSensor =
1083 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
1084 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
1085 handle, dynamicSensor.type, dynamicSensor.name);
1086
Peng Xu0cc8f802016-04-05 23:46:03 -07001087 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -08001088 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -07001089 sensor_t s = dynamicSensor;
1090 // make sure the dynamic sensor flag is set
1091 s.flags |= DYNAMIC_SENSOR_MASK;
1092 // force the handle to be consistent
1093 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -08001094
1095 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -08001096
Peng Xu0cc8f802016-04-05 23:46:03 -07001097 // This will release hold on dynamic sensor meta, so it should be called
1098 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -07001099 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001100 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -07001101 } else {
1102 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
1103 }
Peng Xu2576cb62016-01-20 00:22:09 -08001104 } else {
1105 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1106 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1107
1108 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001109 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -08001110 ALOGE("Dynamic sensor release error.");
1111 }
1112
Brian Duddie967ce172019-06-10 11:08:27 -07001113 for (const sp<SensorEventConnection>& connection : activeConnections) {
1114 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001115 }
1116 }
1117 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001118 }
1119
Aravind Akella9a844cf2014-02-11 18:58:52 -08001120 // Send our events to clients. Check the state of wake lock for each client and release the
1121 // lock if none of the clients need it.
1122 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001123 for (const sp<SensorEventConnection>& connection : activeConnections) {
1124 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1125 mMapFlushEventsToConnections);
1126 needsWakeLock |= connection->needsWakeLock();
1127 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1128 // Early check for one-shot sensors.
1129 if (connection->hasOneShotSensors()) {
1130 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001131 }
1132 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001133
Aravind Akella9a844cf2014-02-11 18:58:52 -08001134 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001135 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001136 }
Aravind Akella8493b792014-09-08 15:45:47 -07001137 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001138
Steve Block3c20fbe2012-01-05 23:22:43 +00001139 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001140 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001141 return false;
1142}
1143
Aravind Akella56ae4262014-07-10 16:01:10 -07001144sp<Looper> SensorService::getLooper() const {
1145 return mLooper;
1146}
1147
Aravind Akellab4373ac2014-10-29 17:55:20 -07001148void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001149 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1150 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1151 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001152 }
Brian Duddie967ce172019-06-10 11:08:27 -07001153 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001154}
1155
1156void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1157 if (acquire) {
1158 if (!mWakeLockAcquired) {
1159 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1160 mWakeLockAcquired = true;
1161 }
1162 mLooper->wake();
1163 } else {
1164 if (mWakeLockAcquired) {
1165 release_wake_lock(WAKE_LOCK_NAME);
1166 mWakeLockAcquired = false;
1167 }
1168 }
1169}
1170
Aravind Akellab4373ac2014-10-29 17:55:20 -07001171bool SensorService::isWakeLockAcquired() {
1172 Mutex::Autolock _l(mLock);
1173 return mWakeLockAcquired;
1174}
1175
Aravind Akella56ae4262014-07-10 16:01:10 -07001176bool SensorService::SensorEventAckReceiver::threadLoop() {
1177 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001178 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001179 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001180 bool wakeLockAcquired = mService->isWakeLockAcquired();
1181 int timeout = -1;
1182 if (wakeLockAcquired) timeout = 5000;
1183 int ret = looper->pollOnce(timeout);
1184 if (ret == ALOOPER_POLL_TIMEOUT) {
1185 mService->resetAllWakeLockRefCounts();
1186 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001187 } while(!Thread::exitPending());
1188 return false;
1189}
1190
Aravind Akella9a844cf2014-02-11 18:58:52 -08001191void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001192 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001193 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001194 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1195 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001196 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001197 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001198 }
Peng Xu2576cb62016-01-20 00:22:09 -08001199
Peng Xu6a2d3a02015-12-21 12:00:23 -08001200 auto logger = mRecentEvent.find(buffer[i].sensor);
1201 if (logger != mRecentEvent.end()) {
1202 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001203 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001204 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001205}
1206
Peng Xu47e96012016-03-28 17:55:56 -07001207void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001208 struct compar {
1209 static int cmp(void const* lhs, void const* rhs) {
1210 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1211 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001212 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001213 }
1214 };
1215 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1216}
1217
Mathias Agopian5d270722010-07-19 15:20:39 -07001218String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001219 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001220}
1221
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001222String8 SensorService::getSensorStringType(int handle) const {
1223 return mSensors.getStringType(handle);
1224}
1225
Aravind Akellab4099e72013-10-15 15:43:10 -07001226bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001227 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1228 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001229}
1230
Aravind Akella9a844cf2014-02-11 18:58:52 -08001231bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001232 int handle = event.sensor;
1233 if (event.type == SENSOR_TYPE_META_DATA) {
1234 handle = event.meta_data.sensor;
1235 }
Peng Xu755c4512016-04-07 23:15:14 -07001236 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1237 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001238}
1239
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001240int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1241 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1242 // UUID is not supported for this device.
1243 return 0;
1244 }
1245 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1246 // This sensor can be uniquely identified in the system by
1247 // the combination of its type and name.
1248 return -1;
1249 }
1250
1251 // We have a dynamic sensor.
1252
1253 if (!sHmacGlobalKeyIsValid) {
lifr3ab0a1b2021-08-06 00:14:26 +08001254 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001255 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1256 return 0;
1257 }
1258
1259 // We want each app author/publisher to get a different ID, so that the
1260 // same dynamic sensor cannot be tracked across apps by multiple
1261 // authors/publishers. So we use both our UUID and our User ID.
1262 // Note potential confusion:
1263 // UUID => Universally Unique Identifier.
1264 // UID => User Identifier.
1265 // We refrain from using "uid" except as needed by API to try to
1266 // keep this distinction clear.
1267
1268 auto appUserId = IPCThreadState::self()->getCallingUid();
1269 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1270 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1271 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1272
1273 // Now we use our key on our UUID/app combo to get the hash.
1274 uint8_t hash[EVP_MAX_MD_SIZE];
1275 unsigned int hashLen;
1276 if (HMAC(EVP_sha256(),
1277 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1278 uuidAndApp, sizeof(uuidAndApp),
1279 hash, &hashLen) == nullptr) {
lifr3ab0a1b2021-08-06 00:14:26 +08001280 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001281 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1282 return 0;
1283 }
1284
1285 int32_t id = 0;
1286 if (hashLen < sizeof(id)) {
1287 // We never expect this case, but out of paranoia, we handle it.
1288 // Our 'id' length is already quite small, we don't want the
1289 // effective length of it to be even smaller.
1290 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1291 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1292 return 0;
1293 }
1294
1295 // This is almost certainly less than all of 'hash', but it's as secure
1296 // as we can be with our current 'id' length.
1297 memcpy(&id, hash, sizeof(id));
1298
1299 // Note at the beginning of the function that we return the values of
1300 // 0 and -1 to represent special cases. As a result, we can't return
1301 // those as dynamic sensor IDs. If we happened to hash to one of those
1302 // values, we change 'id' so we report as a dynamic sensor, and not as
1303 // one of those special cases.
1304 if (id == -1) {
1305 id = -2;
1306 } else if (id == 0) {
1307 id = 1;
1308 }
1309 return id;
1310}
1311
1312void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1313 for (auto &sensor : sensorList) {
1314 int32_t id = getIdFromUuid(sensor.getUuid());
1315 sensor.setId(id);
Eric Laurente3f27df2022-01-05 19:20:32 +01001316 // The sensor UUID must always be anonymized here for non privileged clients.
1317 // There is no other checks after this point before returning to client process.
1318 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1319 sensor.anonymizeUuid();
1320 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001321 }
1322}
1323
Anh Pham4e291332021-02-10 14:17:56 +01001324Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -07001325 char value[PROPERTY_VALUE_MAX];
1326 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001327 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001328 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001329 Vector<Sensor> accessibleSensorList;
Anh Pham4e291332021-02-10 14:17:56 +01001330
Brian Duddie0d4ac562022-05-23 17:47:50 -07001331 resetTargetSdkVersionCache(opPackageName);
Anh Pham4e291332021-02-10 14:17:56 +01001332 bool isCapped = isRateCappedBasedOnPermission(opPackageName);
Aravind Akella70018042014-04-07 22:52:37 +00001333 for (size_t i = 0; i < initialSensorList.size(); i++) {
1334 Sensor sensor = initialSensorList[i];
Anh Pham4e291332021-02-10 14:17:56 +01001335 if (isCapped && isSensorInCappedSet(sensor.getType())) {
1336 sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
1337 sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
1338 }
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001339 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001340 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001341 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001342 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001343}
1344
Peng Xu47e96012016-03-28 17:55:56 -07001345Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001346 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001347 mSensors.forEachSensor(
Brian Duddie4a4d0462022-05-09 16:49:49 -07001348 [this, &opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001349 if (sensor.isDynamicSensor()) {
Brian Duddie4a4d0462022-05-09 16:49:49 -07001350 if (canAccessSensor(sensor, "can't see", opPackageName)) {
Peng Xu755c4512016-04-07 23:15:14 -07001351 accessibleSensorList.add(sensor);
Brian Duddie4a4d0462022-05-09 16:49:49 -07001352 } else if (sensor.getType() != SENSOR_TYPE_HEAD_TRACKER) {
Peng Xu755c4512016-04-07 23:15:14 -07001353 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1354 sensor.getName().string(),
1355 sensor.getRequiredPermission().string(),
1356 sensor.getRequiredAppOp());
1357 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001358 }
1359 return true;
1360 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001361 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001362 return accessibleSensorList;
1363}
1364
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001365sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001366 int requestedMode, const String16& opPackageName, const String16& attributionTag) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001367 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1368 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001369 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001370 }
Brian Duddie0d4ac562022-05-23 17:47:50 -07001371 resetTargetSdkVersionCache(opPackageName);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001372
1373 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001374 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1375 // operating in DI mode.
1376 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001377 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1378 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001379 }
1380
Mathias Agopian5307d172012-09-18 17:02:43 -07001381 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001382 pid_t pid = IPCThreadState::self()->getCallingPid();
1383
1384 String8 connPackageName =
1385 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1386 String16 connOpPackageName =
1387 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1388 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001389 requestedMode == DATA_INJECTION, connOpPackageName, attributionTag));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001390 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001391 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001392 // Add the associated file descriptor to the Looper for polling whenever there is data to
1393 // be injected.
1394 result->updateLooperRegistration(mLooper);
1395 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001396 return result;
1397}
1398
Aravind Akella841a5922015-06-29 12:37:48 -07001399int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001400 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001401 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001402}
1403
Peng Xue36e3472016-11-03 11:57:10 -07001404sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1405 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1406 const native_handle *resource) {
Brian Duddie0d4ac562022-05-23 17:47:50 -07001407 resetTargetSdkVersionCache(opPackageName);
Brian Duddie967ce172019-06-10 11:08:27 -07001408 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001409
Michael Groover5e1f60b2018-12-04 22:34:29 -08001410 // No new direct connections are allowed when sensor privacy is enabled
1411 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1412 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1413 return nullptr;
1414 }
1415
Peng Xue36e3472016-11-03 11:57:10 -07001416 struct sensors_direct_mem_t mem = {
1417 .type = type,
1418 .format = format,
1419 .size = size,
1420 .handle = resource,
1421 };
1422 uid_t uid = IPCThreadState::self()->getCallingUid();
1423
1424 if (mem.handle == nullptr) {
1425 ALOGE("Failed to clone resource handle");
1426 return nullptr;
1427 }
1428
1429 // check format
1430 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1431 ALOGE("Direct channel format %d is unsupported!", format);
1432 return nullptr;
1433 }
1434
1435 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001436 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1437 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001438 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001439 return nullptr;
1440 }
1441 }
1442
1443 // check specific to memory type
1444 switch(type) {
1445 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001446 if (resource->numFds < 1) {
1447 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1448 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1449 return nullptr;
1450 }
Peng Xue36e3472016-11-03 11:57:10 -07001451 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001452 if (!ashmem_valid(fd)) {
1453 ALOGE("Supplied Ashmem memory region is invalid");
1454 return nullptr;
1455 }
1456
Peng Xue36e3472016-11-03 11:57:10 -07001457 int size2 = ashmem_get_size_region(fd);
1458 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001459 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001460 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1461 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001462 return nullptr;
1463 }
1464 break;
1465 }
1466 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001467 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001468 break;
1469 default:
1470 ALOGE("Unknown direct connection memory type %d", type);
1471 return nullptr;
1472 }
1473
1474 native_handle_t *clone = native_handle_clone(resource);
1475 if (!clone) {
1476 return nullptr;
1477 }
1478
Brian Duddie967ce172019-06-10 11:08:27 -07001479 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001480 SensorDevice& dev(SensorDevice::getInstance());
1481 int channelHandle = dev.registerDirectChannel(&mem);
1482
1483 if (channelHandle <= 0) {
1484 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1485 } else {
1486 mem.handle = clone;
1487 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1488 }
1489
1490 if (conn == nullptr) {
1491 native_handle_close(clone);
1492 native_handle_delete(clone);
1493 } else {
1494 // add to list of direct connections
1495 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001496 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001497 }
1498 return conn;
1499}
1500
Peng Xudd5c5cb2017-03-16 17:39:43 -07001501int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001502 int32_t handle, int32_t type,
1503 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001504 Mutex::Autolock _l(mLock);
1505
Alexey Polyudov88711e82017-05-23 19:54:04 -07001506 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001507 return PERMISSION_DENIED;
1508 }
1509
1510 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001511 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001512 size_t expectSize = INT32_MAX;
1513 switch (type) {
1514 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1515 isFloat = true;
1516 expectSize = 3;
1517 break;
1518 case AINFO_LOCAL_GRAVITY:
1519 isFloat = true;
1520 expectSize = 1;
1521 break;
1522 case AINFO_DOCK_STATE:
1523 case AINFO_HIGH_PERFORMANCE_MODE:
1524 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1525 isFloat = false;
1526 expectSize = 1;
1527 break;
1528 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001529 // CUSTOM events must only contain float data; it may have variable size
1530 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1531 ints.size() ||
1532 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1533 handle < 0) {
1534 return BAD_VALUE;
1535 }
1536 isFloat = true;
1537 isCustom = true;
1538 expectSize = floats.size();
1539 break;
1540 }
1541
1542 if (!isCustom && handle != -1) {
1543 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001544 }
1545
1546 // three events: first one is begin tag, last one is end tag, the one in the middle
1547 // is the payload.
1548 sensors_event_t event[3];
1549 int64_t timestamp = elapsedRealtimeNano();
1550 for (sensors_event_t* i = event; i < event + 3; i++) {
1551 *i = (sensors_event_t) {
1552 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001553 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001554 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1555 .timestamp = timestamp++,
1556 .additional_info = (additional_info_event_t) {
1557 .serial = 0
1558 }
1559 };
1560 }
1561
1562 event[0].additional_info.type = AINFO_BEGIN;
1563 event[1].additional_info.type = type;
1564 event[2].additional_info.type = AINFO_END;
1565
1566 if (isFloat) {
1567 if (floats.size() != expectSize) {
1568 return BAD_VALUE;
1569 }
1570 for (size_t i = 0; i < expectSize; ++i) {
1571 event[1].additional_info.data_float[i] = floats[i];
1572 }
1573 } else {
1574 if (ints.size() != expectSize) {
1575 return BAD_VALUE;
1576 }
1577 for (size_t i = 0; i < expectSize; ++i) {
1578 event[1].additional_info.data_int32[i] = ints[i];
1579 }
1580 }
1581
1582 SensorDevice& dev(SensorDevice::getInstance());
1583 for (sensors_event_t* i = event; i < event + 3; i++) {
1584 int ret = dev.injectSensorData(i);
1585 if (ret != NO_ERROR) {
1586 return ret;
1587 }
1588 }
1589 return NO_ERROR;
1590}
1591
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001592status_t SensorService::resetToNormalMode() {
1593 Mutex::Autolock _l(mLock);
1594 return resetToNormalModeLocked();
1595}
1596
1597status_t SensorService::resetToNormalModeLocked() {
1598 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001599 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301600 if (err == NO_ERROR) {
1601 mCurrentOperatingMode = NORMAL;
1602 dev.enableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001603 checkAndReportProxStateChangeLocked();
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301604 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001605 return err;
1606}
1607
Peng Xu47e96012016-03-28 17:55:56 -07001608void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001609 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001610 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001611 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001612 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001613 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001614 int handle = mActiveSensors.keyAt(i);
1615 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001616 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001617 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1618 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001619 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001620 } else {
1621 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001622 }
Brian Duddie7be85572021-12-21 10:44:55 -08001623 if (c->removeSensor(handle)) {
1624 BatteryService::disableSensor(c->getUid(), handle);
1625 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001626 }
1627 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001628 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001629 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001630 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001631 c, i, handle);
1632
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001633 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001634 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001635 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001636 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001637 delete rec;
1638 size--;
1639 } else {
1640 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001641 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001642 }
Aravind Akella8a969552014-09-28 17:52:41 -07001643 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001644 mConnectionHolder.removeEventConnection(connection);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001645 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001646 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001647 }
Peng Xu4f707f82016-09-26 11:28:32 -07001648
1649 SensorDevice& dev(SensorDevice::getInstance());
1650 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001651}
1652
Peng Xue36e3472016-11-03 11:57:10 -07001653void SensorService::cleanupConnection(SensorDirectConnection* c) {
1654 Mutex::Autolock _l(mLock);
1655
1656 SensorDevice& dev(SensorDevice::getInstance());
1657 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001658 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001659}
1660
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001661void SensorService::checkAndReportProxStateChangeLocked() {
1662 if (mProxSensorHandles.empty()) return;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001663
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001664 SensorDevice& dev(SensorDevice::getInstance());
1665 bool isActive = false;
1666 for (auto& sensor : mProxSensorHandles) {
1667 if (dev.isSensorActive(sensor)) {
1668 isActive = true;
1669 break;
1670 }
1671 }
1672 if (isActive != mLastReportedProxIsActive) {
1673 notifyProximityStateLocked(isActive, mProximityActiveListeners);
1674 mLastReportedProxIsActive = isActive;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001675 }
1676}
1677
1678void SensorService::notifyProximityStateLocked(
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001679 const bool isActive,
Santos Cordon7ea287a2021-06-14 13:45:29 +01001680 const std::vector<sp<ProximityActiveListener>>& listeners) {
Santos Cordon7ea287a2021-06-14 13:45:29 +01001681 const uint64_t mySeq = ++curProxCallbackSeq;
1682 std::thread t([isActive, mySeq, listenersCopy = listeners]() {
1683 while (completedCallbackSeq.load() != mySeq - 1)
1684 std::this_thread::sleep_for(1ms);
1685 for (auto& listener : listenersCopy)
1686 listener->onProximityActive(isActive);
1687 completedCallbackSeq++;
1688 });
1689 t.detach();
Andrew Lehmer3a602572021-03-25 15:19:56 -07001690}
1691
1692status_t SensorService::addProximityActiveListener(const sp<ProximityActiveListener>& callback) {
1693 if (callback == nullptr) {
1694 return BAD_VALUE;
1695 }
1696
1697 Mutex::Autolock _l(mLock);
1698
1699 // Check if the callback was already added.
1700 for (const auto& cb : mProximityActiveListeners) {
1701 if (cb == callback) {
1702 return ALREADY_EXISTS;
1703 }
1704 }
1705
1706 mProximityActiveListeners.push_back(callback);
1707 std::vector<sp<ProximityActiveListener>> listener(1, callback);
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001708 notifyProximityStateLocked(mLastReportedProxIsActive, listener);
Andrew Lehmer3a602572021-03-25 15:19:56 -07001709 return OK;
1710}
1711
1712status_t SensorService::removeProximityActiveListener(
1713 const sp<ProximityActiveListener>& callback) {
1714 if (callback == nullptr) {
1715 return BAD_VALUE;
1716 }
1717
1718 Mutex::Autolock _l(mLock);
1719
1720 for (auto iter = mProximityActiveListeners.begin();
1721 iter != mProximityActiveListeners.end();
1722 ++iter) {
1723 if (*iter == callback) {
1724 mProximityActiveListeners.erase(iter);
1725 return OK;
1726 }
1727 }
1728 return NAME_NOT_FOUND;
1729}
1730
Peng Xu755c4512016-04-07 23:15:14 -07001731sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001732 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001733}
1734
Mathias Agopianfc328812010-07-14 23:41:37 -07001735status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001736 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001737 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001738 if (mInitCheck != NO_ERROR)
1739 return mInitCheck;
1740
Peng Xu755c4512016-04-07 23:15:14 -07001741 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1742 if (sensor == nullptr ||
1743 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001744 return BAD_VALUE;
1745 }
1746
Brian Duddie967ce172019-06-10 11:08:27 -07001747 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001748 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001749 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001750 return INVALID_OPERATION;
1751 }
1752
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001753 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001754 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001755 rec = new SensorRecord(connection);
1756 mActiveSensors.add(handle, rec);
1757 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001758 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001759 }
Brian Stack26029ee2019-04-22 17:25:49 -07001760
1761 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1762 // the recent event as stale to ensure that the previous event is not sent to a client. This
1763 // ensures on-change events that were generated during a previous sensor activation are not
1764 // erroneously sent to newly connected clients, especially if a second client registers for
1765 // an on-change sensor before the first client receives the updated event. Once an updated
1766 // event is received, the recent events will be marked as current, and any new clients will
1767 // immediately receive the most recent event.
1768 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1769 auto logger = mRecentEvent.find(handle);
1770 if (logger != mRecentEvent.end()) {
1771 logger->second->setLastEventStale();
1772 }
1773 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001774 } else {
1775 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001776 // this sensor is already activated, but we are adding a connection that uses it.
1777 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001778 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001779 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001780 // NOTE: The wake_up flag of this event may get set to
1781 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001782
1783 auto logger = mRecentEvent.find(handle);
1784 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001785 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001786 // Verify that the last sensor event was generated from the current activation
1787 // of the sensor. If not, it is possible for an on-change sensor to receive a
1788 // sensor event that is stale if two clients re-activate the sensor
1789 // simultaneously.
1790 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001791 event.sensor = handle;
1792 if (event.version == sizeof(sensors_event_t)) {
1793 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1794 setWakeLockAcquiredLocked(true);
1795 }
Yi Kong8f313e32018-07-17 14:13:29 -07001796 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001797 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001798 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001799 }
1800 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001801 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001802 }
1803 }
1804 }
1805 }
1806
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001807 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001808 BatteryService::enableSensor(connection->getUid(), handle);
1809 // the sensor was added (which means it wasn't already there)
1810 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001811 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001812 } else {
1813 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1814 handle, connection.get());
1815 }
1816
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301817 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001818 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301819 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1820 samplingPeriodNs = maxDelayNs;
1821 }
1822
Aravind Akella724d91d2013-06-27 12:04:23 -07001823 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1824 if (samplingPeriodNs < minDelayNs) {
1825 samplingPeriodNs = minDelayNs;
1826 }
1827
Aravind Akella6c2664a2014-08-13 12:24:50 -07001828 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1829 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001830 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1831
Aravind Akella4949c502015-02-11 15:54:35 -08001832 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001833 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001834
Peng Xu20483c42015-10-26 15:14:43 -07001835 // Call flush() before calling activate() on the sensor. Wait for a first
1836 // flush complete event before sending events on this connection. Ignore
1837 // one-shot sensors which don't support flush(). Ignore on-change sensors
1838 // to maintain the on-change logic (any on-change events except the initial
1839 // one should be trigger by a change in value). Also if this sensor isn't
1840 // already active, don't call flush().
1841 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001842 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001843 rec->getNumConnections() > 1) {
1844 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001845 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001846 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001847 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001848 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001849 } else {
1850 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001851 }
1852 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001853
1854 if (err == NO_ERROR) {
1855 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1856 err = sensor->activate(connection.get(), true);
1857 }
1858
Aravind Akella8a969552014-09-28 17:52:41 -07001859 if (err == NO_ERROR) {
1860 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001861
Brian Stack240d1d62019-05-17 09:49:39 -07001862 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1863 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001864 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1865 }
1866
Peng Xu51224682017-03-10 16:57:27 -08001867 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1868 SensorRegistrationInfo(handle, connection->getPackageName(),
1869 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001870 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001871 }
1872
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001873 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001874 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001875 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001876 }
1877 return err;
1878}
1879
Peng Xu47e96012016-03-28 17:55:56 -07001880status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001881 if (mInitCheck != NO_ERROR)
1882 return mInitCheck;
1883
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001884 Mutex::Autolock _l(mLock);
1885 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001886 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001887 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1888 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001889
1890 }
1891 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001892 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1893 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001894 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001895 }
1896 return err;
1897}
1898
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001899status_t SensorService::cleanupWithoutDisable(
1900 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001901 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001902 return cleanupWithoutDisableLocked(connection, handle);
1903}
1904
1905status_t SensorService::cleanupWithoutDisableLocked(
1906 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001907 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001908 if (rec) {
1909 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001910 if (connection->removeSensor(handle)) {
1911 BatteryService::disableSensor(connection->getUid(), handle);
1912 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001913 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001914 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001915 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001916 }
1917 // see if this sensor becomes inactive
1918 if (rec->removeConnection(connection)) {
1919 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001920 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001921 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001922 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001923 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001924 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001925 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001926}
1927
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001928status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001929 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001930 if (mInitCheck != NO_ERROR)
1931 return mInitCheck;
1932
Peng Xu755c4512016-04-07 23:15:14 -07001933 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1934 if (sensor == nullptr ||
1935 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001936 return BAD_VALUE;
1937 }
1938
Mathias Agopian1cd70002010-07-21 15:59:50 -07001939 if (ns < 0)
1940 return BAD_VALUE;
1941
Mathias Agopian62569ec2011-11-07 21:21:47 -08001942 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1943 if (ns < minDelayNs) {
1944 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001945 }
1946
Mathias Agopianf001c922010-11-11 17:58:51 -08001947 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001948}
1949
Svetoslavb412f6e2015-04-29 16:50:41 -07001950status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1951 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001952 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001953 SensorDevice& dev(SensorDevice::getInstance());
1954 const int halVersion = dev.getHalDeviceVersion();
1955 status_t err(NO_ERROR);
1956 Mutex::Autolock _l(mLock);
1957 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07001958 for (int handle : connection->getActiveSensorHandles()) {
Peng Xu755c4512016-04-07 23:15:14 -07001959 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1960 if (sensor == nullptr) {
1961 continue;
1962 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001963 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1964 ALOGE("flush called on a one-shot sensor");
1965 err = INVALID_OPERATION;
1966 continue;
1967 }
Aravind Akella8493b792014-09-08 15:45:47 -07001968 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001969 // For older devices just increment pending flush count which will send a trivial
1970 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07001971 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
1972 ALOGE("flush called on an inaccessible sensor");
1973 err = INVALID_OPERATION;
1974 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001975 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001976 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1977 err = INVALID_OPERATION;
1978 continue;
1979 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001980 status_t err_flush = sensor->flush(connection.get(), handle);
1981 if (err_flush == NO_ERROR) {
1982 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001983 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001984 }
1985 err = (err_flush != NO_ERROR) ? err_flush : err;
1986 }
Aravind Akella70018042014-04-07 22:52:37 +00001987 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07001988 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001989}
Aravind Akella70018042014-04-07 22:52:37 +00001990
Svetoslavb412f6e2015-04-29 16:50:41 -07001991bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1992 const String16& opPackageName) {
Brian Duddie4a4d0462022-05-09 16:49:49 -07001993 // Special case for Head Tracker sensor type: currently restricted to system usage only, unless
1994 // the restriction is specially lifted for testing
1995 if (sensor.getType() == SENSOR_TYPE_HEAD_TRACKER &&
1996 !isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1997 if (!mHtRestricted) {
1998 ALOGI("Permitting access to HT sensor type outside system (%s)",
1999 String8(opPackageName).string());
2000 } else {
2001 ALOGW("%s %s a sensor (%s) as a non-system client", String8(opPackageName).string(),
2002 operation, sensor.getName().string());
2003 return false;
2004 }
2005 }
2006
Brian Stack793f4642019-04-18 17:21:34 -07002007 // Check if a permission is required for this sensor
2008 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00002009 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07002010 }
2011
Brian Stack793f4642019-04-18 17:21:34 -07002012 const int32_t opCode = sensor.getRequiredAppOp();
Brian Duddie457e6392020-06-19 11:38:29 -07002013 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07002014
Brian Stack793f4642019-04-18 17:21:34 -07002015 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07002016 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
2017 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
2018 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
2019 // Allow access to step sensors if the application targets pre-Q, which is before the
2020 // requirement to hold the AR permission to access Step Counter and Step Detector events
2021 // was introduced.
2022 canAccess = true;
2023 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07002024 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002025 if (opCode >= 0) {
2026 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
2027 IPCThreadState::self()->getCallingUid(), opPackageName);
2028 canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
2029 } else {
Brian Stack793f4642019-04-18 17:21:34 -07002030 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07002031 }
Brian Stack793f4642019-04-18 17:21:34 -07002032 }
2033
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002034 if (!canAccess) {
Brian Duddie457e6392020-06-19 11:38:29 -07002035 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
2036 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07002037 }
2038
2039 return canAccess;
2040}
2041
2042bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07002043 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07002044 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07002045
2046 // Runtime permissions can't use the cache as they may change.
2047 if (sensor.isRequiredPermissionRuntime()) {
2048 hasPermission = checkPermission(String16(requiredPermission),
matthuang65794462022-03-24 16:02:57 +08002049 IPCThreadState::self()->getCallingPid(),
2050 IPCThreadState::self()->getCallingUid(),
2051 /*logPermissionFailure=*/ false);
Aravind Akella70018042014-04-07 22:52:37 +00002052 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002053 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
2054 }
Brian Stack793f4642019-04-18 17:21:34 -07002055 return hasPermission;
2056}
Svetoslavb412f6e2015-04-29 16:50:41 -07002057
Brian Stack793f4642019-04-18 17:21:34 -07002058int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Anthony Stange07eb4212020-08-28 14:50:28 -04002059 // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
2060 // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
2061 // give it elevated privileges.
2062 if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
2063 return -1;
2064 }
2065
Brian Stack793f4642019-04-18 17:21:34 -07002066 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2067 int targetSdkVersion = -1;
2068 auto entry = sPackageTargetVersion.find(opPackageName);
2069 if (entry != sPackageTargetVersion.end()) {
2070 targetSdkVersion = entry->second;
2071 } else {
2072 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2073 if (binder != nullptr) {
2074 sp<content::pm::IPackageManagerNative> packageManager =
2075 interface_cast<content::pm::IPackageManagerNative>(binder);
2076 if (packageManager != nullptr) {
2077 binder::Status status = packageManager->getTargetSdkVersionForPackage(
2078 opPackageName, &targetSdkVersion);
2079 if (!status.isOk()) {
2080 targetSdkVersion = -1;
2081 }
2082 }
Svetoslavb412f6e2015-04-29 16:50:41 -07002083 }
Brian Stack793f4642019-04-18 17:21:34 -07002084 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07002085 }
Brian Stack793f4642019-04-18 17:21:34 -07002086 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00002087}
2088
Brian Duddie0d4ac562022-05-23 17:47:50 -07002089void SensorService::resetTargetSdkVersionCache(const String16& opPackageName) {
2090 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2091 auto iter = sPackageTargetVersion.find(opPackageName);
2092 if (iter != sPackageTargetVersion.end()) {
2093 sPackageTargetVersion.erase(iter);
2094 }
2095}
2096
Aravind Akella9a844cf2014-02-11 18:58:52 -08002097void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07002098 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2099 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08002100}
2101
Brian Duddie967ce172019-06-10 11:08:27 -07002102void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002103 if (!mWakeLockAcquired) {
2104 return;
2105 }
2106 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07002107 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
2108 if (connection->needsWakeLock()) {
2109 releaseLock = false;
2110 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08002111 }
2112 }
2113 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07002114 setWakeLockAcquiredLocked(false);
2115 }
2116}
2117
2118void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
2119 Mutex::Autolock _l(mLock);
2120 connection->writeToSocketFromCache();
2121 if (connection->needsWakeLock()) {
2122 setWakeLockAcquiredLocked(true);
2123 }
2124}
2125
Aravind Akella4949c502015-02-11 15:54:35 -08002126bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07002127 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08002128}
2129
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002130bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08002131 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07002132 String8 package(opPackageName);
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002133 return !isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07002134 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002135 return false;
Peng Xue36e3472016-11-03 11:57:10 -07002136}
2137
Svet Ganove752a5c2018-01-15 17:14:20 -08002138void SensorService::UidPolicy::registerSelf() {
2139 ActivityManager am;
2140 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
2141 | ActivityManager::UID_OBSERVER_IDLE
2142 | ActivityManager::UID_OBSERVER_ACTIVE,
2143 ActivityManager::PROCESS_STATE_UNKNOWN,
2144 String16("android"));
2145}
2146
2147void SensorService::UidPolicy::unregisterSelf() {
2148 ActivityManager am;
2149 am.unregisterUidObserver(this);
2150}
2151
2152void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
2153 onUidIdle(uid, disabled);
2154}
2155
2156void SensorService::UidPolicy::onUidActive(uid_t uid) {
2157 {
2158 Mutex::Autolock _l(mUidLock);
2159 mActiveUids.insert(uid);
2160 }
2161 sp<SensorService> service = mService.promote();
2162 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002163 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002164 }
2165}
2166
2167void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
2168 bool deleted = false;
2169 {
2170 Mutex::Autolock _l(mUidLock);
2171 if (mActiveUids.erase(uid) > 0) {
2172 deleted = true;
2173 }
2174 }
2175 if (deleted) {
2176 sp<SensorService> service = mService.promote();
2177 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002178 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002179 }
2180 }
2181}
2182
2183void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
2184 updateOverrideUid(uid, active, true);
2185}
2186
2187void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
2188 updateOverrideUid(uid, false, false);
2189}
2190
2191void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
2192 bool wasActive = false;
2193 bool isActive = false;
2194 {
2195 Mutex::Autolock _l(mUidLock);
2196 wasActive = isUidActiveLocked(uid);
2197 mOverrideUids.erase(uid);
2198 if (insert) {
2199 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2200 }
2201 isActive = isUidActiveLocked(uid);
2202 }
2203 if (wasActive != isActive) {
2204 sp<SensorService> service = mService.promote();
2205 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002206 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002207 }
2208 }
2209}
2210
2211bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2212 // Non-app UIDs are considered always active
2213 if (uid < FIRST_APPLICATION_UID) {
2214 return true;
2215 }
2216 Mutex::Autolock _l(mUidLock);
2217 return isUidActiveLocked(uid);
2218}
2219
2220bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2221 // Non-app UIDs are considered always active
2222 if (uid < FIRST_APPLICATION_UID) {
2223 return true;
2224 }
2225 auto it = mOverrideUids.find(uid);
2226 if (it != mOverrideUids.end()) {
2227 return it->second;
2228 }
2229 return mActiveUids.find(uid) != mActiveUids.end();
2230}
2231
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002232bool SensorService::isUidActive(uid_t uid) {
2233 return mUidPolicy->isUidActive(uid);
2234}
2235
Anh Phamaf91a912021-02-10 14:10:53 +01002236bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2237 int targetSdk = getTargetSdkVersion(opPackageName);
Anh Phama5538232021-06-23 08:41:11 +02002238 bool hasSamplingRatePermission = checkPermission(sAccessHighSensorSamplingRatePermission,
2239 IPCThreadState::self()->getCallingPid(),
matthuang65794462022-03-24 16:02:57 +08002240 IPCThreadState::self()->getCallingUid(),
2241 /*logPermissionFailure=*/ false);
Anh Phamaf91a912021-02-10 14:10:53 +01002242 if (targetSdk < __ANDROID_API_S__ ||
2243 (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2244 return false;
2245 }
2246 return true;
2247}
2248
Anh Pham3dae77f2021-06-11 16:24:37 +02002249/**
2250 * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS
2251 * permission.
2252 *
2253 * This needs to be kept in sync with the list defined on the Java side
2254 * in frameworks/base/core/java/android/hardware/SystemSensorManager.java
2255 */
Anh Phamaf91a912021-02-10 14:10:53 +01002256bool SensorService::isSensorInCappedSet(int sensorType) {
2257 return (sensorType == SENSOR_TYPE_ACCELEROMETER
2258 || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2259 || sensorType == SENSOR_TYPE_GYROSCOPE
2260 || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2261 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2262 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2263}
2264
2265status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2266 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002267 if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2268 return OK;
2269 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002270 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002271 if (shouldCapBasedOnPermission) {
2272 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2273 if (isPackageDebuggable(opPackageName)) {
2274 return PERMISSION_DENIED;
2275 }
2276 return OK;
2277 }
Evan Severson4c197852022-01-27 10:44:27 -08002278 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002279 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2280 return OK;
2281 }
Anh Phamaf91a912021-02-10 14:10:53 +01002282 return OK;
2283}
2284
2285status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2286 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002287 if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2288 return OK;
2289 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002290 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002291 if (shouldCapBasedOnPermission) {
2292 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2293 if (isPackageDebuggable(opPackageName)) {
2294 return PERMISSION_DENIED;
2295 }
2296 return OK;
2297 }
Evan Severson4c197852022-01-27 10:44:27 -08002298 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002299 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2300 return OK;
2301 }
Anh Phamaf91a912021-02-10 14:10:53 +01002302 return OK;
2303}
2304
Michael Groover5e1f60b2018-12-04 22:34:29 -08002305void SensorService::SensorPrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002306 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002307 SensorPrivacyManager spm;
2308 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2309 spm.addSensorPrivacyListener(this);
2310}
2311
2312void SensorService::SensorPrivacyPolicy::unregisterSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002313 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002314 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002315 spm.removeSensorPrivacyListener(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -08002316}
2317
2318bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2319 return mSensorPrivacyEnabled;
2320}
2321
Evan Severson4c197852022-01-27 10:44:27 -08002322binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2323 int sensor __unused, bool enabled) {
Michael Groover5e1f60b2018-12-04 22:34:29 -08002324 mSensorPrivacyEnabled = enabled;
2325 sp<SensorService> service = mService.promote();
Anh Pham5198c992021-02-10 14:15:30 +01002326
Michael Groover5e1f60b2018-12-04 22:34:29 -08002327 if (service != nullptr) {
Evan Severson4c197852022-01-27 10:44:27 -08002328 if (enabled) {
2329 service->disableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002330 } else {
Evan Severson4c197852022-01-27 10:44:27 -08002331 service->enableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002332 }
2333 }
2334 return binder::Status::ok();
2335}
Brian Duddie967ce172019-06-10 11:08:27 -07002336
Evan Severson4c197852022-01-27 10:44:27 -08002337void SensorService::MicrophonePrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002338 AutoCallerClear acc;
Anh Pham5198c992021-02-10 14:15:30 +01002339 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002340 mSensorPrivacyEnabled =
2341 spm.isToggleSensorPrivacyEnabled(
2342 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
2343 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE)
2344 || spm.isToggleSensorPrivacyEnabled(
2345 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE,
2346 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE);
2347 spm.addToggleSensorPrivacyListener(this);
Anh Pham5198c992021-02-10 14:15:30 +01002348}
2349
Evan Severson4c197852022-01-27 10:44:27 -08002350void SensorService::MicrophonePrivacyPolicy::unregisterSelf() {
2351 AutoCallerClear acc;
2352 SensorPrivacyManager spm;
2353 spm.removeToggleSensorPrivacyListener(this);
2354}
2355
2356binder::Status SensorService::MicrophonePrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2357 int sensor, bool enabled) {
2358 if (sensor != SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE) {
2359 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002360 }
Evan Severson4c197852022-01-27 10:44:27 -08002361 mSensorPrivacyEnabled = enabled;
2362 sp<SensorService> service = mService.promote();
2363
2364 if (service != nullptr) {
2365 if (enabled) {
2366 service->capRates();
2367 } else {
2368 service->uncapRates();
2369 }
2370 }
2371 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002372}
2373
Brian Duddie967ce172019-06-10 11:08:27 -07002374SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2375 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2376 : mConnectionHolder(holder), mAutolock(mutex) {}
2377
2378template<typename ConnectionType>
2379const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2380 const SortedVector<wp<ConnectionType>>& connectionList,
2381 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2382 referenceHolder->emplace_back();
2383 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2384 for (const wp<ConnectionType>& weakConnection : connectionList){
2385 sp<ConnectionType> connection = weakConnection.promote();
2386 if (connection != nullptr) {
2387 connections.push_back(std::move(connection));
2388 }
2389 }
2390 return connections;
2391}
2392
2393const std::vector<sp<SensorService::SensorEventConnection>>&
2394 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2395 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2396 &mReferencedActiveConnections);
2397}
2398
2399const std::vector<sp<SensorService::SensorDirectConnection>>&
2400 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2401 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2402 &mReferencedDirectConnections);
2403}
2404
2405void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2406 const sp<SensorService::SensorEventConnection>& connection) {
2407 if (mActiveConnections.indexOf(connection) < 0) {
2408 mActiveConnections.add(connection);
2409 }
2410}
2411
2412void SensorService::SensorConnectionHolder::removeEventConnection(
2413 const wp<SensorService::SensorEventConnection>& connection) {
2414 mActiveConnections.remove(connection);
2415}
2416
2417void SensorService::SensorConnectionHolder::addDirectConnection(
2418 const sp<SensorService::SensorDirectConnection>& connection) {
2419 mDirectConnections.add(connection);
2420}
2421
2422void SensorService::SensorConnectionHolder::removeDirectConnection(
2423 const wp<SensorService::SensorDirectConnection>& connection) {
2424 mDirectConnections.remove(connection);
2425}
2426
2427SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2428 return ConnectionSafeAutolock(*this, mutex);
2429}
2430
Anh Phamaf91a912021-02-10 14:10:53 +01002431bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2432 bool debugMode = false;
2433 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2434 if (binder != nullptr) {
2435 sp<content::pm::IPackageManagerNative> packageManager =
2436 interface_cast<content::pm::IPackageManagerNative>(binder);
2437 if (packageManager != nullptr) {
2438 binder::Status status = packageManager->isPackageDebuggable(
2439 opPackageName, &debugMode);
2440 }
2441 }
2442 return debugMode;
2443}
Brian Duddie967ce172019-06-10 11:08:27 -07002444} // namespace android