blob: 0fb3cadc6304f5ec7f64146f7ae35c2122203f43 [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 */
Vladimir Komsiyski29d2afd2022-12-06 13:24:10 +010016#include <aidl/android/hardware/sensors/ISensors.h>
Anh Phamaf91a912021-02-10 14:10:53 +010017#include <android-base/strings.h>
Brian Stack793f4642019-04-18 17:21:34 -070018#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080019#include <android/util/ProtoOutputStream.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>
Brian Duddie0a4cebb2022-08-25 19:20:18 +000028#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070029#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070030#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080031#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070032#include <openssl/digest.h>
33#include <openssl/hmac.h>
34#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070035#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080036#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070037#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070038
Mathias Agopian787ac1b2012-09-18 18:49:18 -070039#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070040#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080041#include "GravitySensor.h"
Tyler Trephanc7b92632021-07-21 10:39:38 -070042#include "LimitedAxesImuSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080043#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070044#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080045#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070047#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048
Mathias Agopian984826c2011-05-17 22:54:42 -070049#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070050#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080051#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080052#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080053#include "SensorRecord.h"
54#include "SensorRegistrationInfo.h"
Anthony Stange9bb16702023-01-03 22:42:31 +000055#include "SensorServiceUtils.h"
Peng Xueb4d6282015-12-10 18:02:41 -080056
57#include <inttypes.h>
58#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070059#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080060#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080061#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070062#include <sys/stat.h>
63#include <sys/types.h>
64#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070065
Andrew Lehmer3a602572021-03-25 15:19:56 -070066#include <ctime>
67#include <future>
Anthony Stangec1608152023-01-06 21:14:46 +000068#include <string>
Andrew Lehmer3a602572021-03-25 15:19:56 -070069
Svet Ganove752a5c2018-01-15 17:14:20 -080070#include <private/android_filesystem_config.h>
71
Andrew Lehmer3a602572021-03-25 15:19:56 -070072using namespace std::chrono_literals;
73
Mathias Agopianfc328812010-07-14 23:41:37 -070074namespace android {
75// ---------------------------------------------------------------------------
76
Mathias Agopian33015422011-05-27 18:18:13 -070077/*
78 * Notes:
79 *
80 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070081 * - run mag sensor from time to time to force calibration
82 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
83 *
84 */
85
Aravind Akella8ef3c892015-07-10 11:24:28 -070086const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070087uint8_t SensorService::sHmacGlobalKey[128] = {};
88bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070089std::map<String16, int> SensorService::sPackageTargetVersion;
90Mutex SensorService::sPackageTargetVersionLock;
Anthony Stange07eb4212020-08-28 14:50:28 -040091String16 SensorService::sSensorInterfaceDescriptorPrefix =
92 String16("android.frameworks.sensorservice@");
Brian Stack793f4642019-04-18 17:21:34 -070093AppOpsManager SensorService::sAppOpsManager;
Andrew Lehmer3a602572021-03-25 15:19:56 -070094std::atomic_uint64_t SensorService::curProxCallbackSeq(0);
95std::atomic_uint64_t SensorService::completedCallbackSeq(0);
Greg Kaiser53ca2e02016-06-21 16:11:14 -070096
97#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
98#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070099#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700100
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700101// Permissions.
Anh Phamaf91a912021-02-10 14:10:53 +0100102static const String16 sAccessHighSensorSamplingRatePermission(
103 "android.permission.HIGH_SAMPLING_RATE_SENSORS");
Peng Xudd5c5cb2017-03-16 17:39:43 -0700104static const String16 sDumpPermission("android.permission.DUMP");
105static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -0800106static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700107
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200108namespace {
109
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200110int32_t nextRuntimeSensorHandle() {
Vladimir Komsiyski29d2afd2022-12-06 13:24:10 +0100111 using ::aidl::android::hardware::sensors::ISensors;
112 static int32_t nextHandle = ISensors::RUNTIME_SENSORS_HANDLE_BASE;
113 if (nextHandle == ISensors::RUNTIME_SENSORS_HANDLE_END) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200114 return -1;
115 }
116 return nextHandle++;
117}
118
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100119class RuntimeSensorCallbackProxy : public RuntimeSensor::SensorCallback {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200120 public:
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100121 RuntimeSensorCallbackProxy(sp<SensorService::RuntimeSensorCallback> callback)
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200122 : mCallback(std::move(callback)) {}
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100123 status_t onConfigurationChanged(int handle, bool enabled, int64_t samplingPeriodNs,
124 int64_t batchReportLatencyNs) override {
125 return mCallback->onConfigurationChanged(handle, enabled, samplingPeriodNs,
126 batchReportLatencyNs);
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200127 }
128 private:
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100129 sp<SensorService::RuntimeSensorCallback> mCallback;
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200130};
131
132} // namespace
133
Tyler Trephanc7b92632021-07-21 10:39:38 -0700134static bool isAutomotive() {
135 sp<IServiceManager> serviceManager = defaultServiceManager();
136 if (serviceManager.get() == nullptr) {
137 ALOGE("%s: unable to access native ServiceManager", __func__);
138 return false;
139 }
140
141 sp<content::pm::IPackageManagerNative> packageManager;
142 sp<IBinder> binder = serviceManager->waitForService(String16("package_native"));
143 packageManager = interface_cast<content::pm::IPackageManagerNative>(binder);
144 if (packageManager == nullptr) {
145 ALOGE("%s: unable to access native PackageManager", __func__);
146 return false;
147 }
148
149 bool isAutomotive = false;
150 binder::Status status =
151 packageManager->hasSystemFeature(String16("android.hardware.type.automotive"), 0,
152 &isAutomotive);
153 if (!status.isOk()) {
154 ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str());
155 return false;
156 }
157
158 return isAutomotive;
159}
160
Mathias Agopianfc328812010-07-14 23:41:37 -0700161SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -0700162 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700163 mWakeLockAcquired(false), mLastReportedProxIsActive(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +0900164 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800165 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Evan Severson4c197852022-01-27 10:44:27 -0800166 mMicSensorPrivacyPolicy = new MicrophonePrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700167}
168
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200169int SensorService::registerRuntimeSensor(
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100170 const sensor_t& sensor, int deviceId, sp<RuntimeSensorCallback> callback) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200171 int handle = 0;
172 while (handle == 0 || !mSensors.isNewHandle(handle)) {
173 handle = nextRuntimeSensorHandle();
174 if (handle < 0) {
175 // Ran out of the dedicated range for runtime sensors.
176 return handle;
177 }
178 }
179
180 ALOGI("Registering runtime sensor handle 0x%x, type %d, name %s",
181 handle, sensor.type, sensor.name);
182
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100183 sp<RuntimeSensor::SensorCallback> runtimeSensorCallback(
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100184 new RuntimeSensorCallbackProxy(callback));
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200185 sensor_t runtimeSensor = sensor;
186 // force the handle to be consistent
187 runtimeSensor.handle = handle;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100188 auto si = std::make_shared<RuntimeSensor>(runtimeSensor, std::move(runtimeSensorCallback));
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200189
190 Mutex::Autolock _l(mLock);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100191 if (!registerSensor(std::move(si), /* isDebug= */ false, /* isVirtual= */ false, deviceId)) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200192 // The registration was unsuccessful.
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100193 return mSensors.getNonSensor().getHandle();
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200194 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100195
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100196 if (mRuntimeSensorCallbacks.find(deviceId) == mRuntimeSensorCallbacks.end()) {
197 mRuntimeSensorCallbacks.emplace(deviceId, callback);
198 }
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200199 return handle;
200}
201
202status_t SensorService::unregisterRuntimeSensor(int handle) {
203 ALOGI("Unregistering runtime sensor handle 0x%x disconnected", handle);
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100204 int deviceId = getDeviceIdFromHandle(handle);
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200205 {
206 Mutex::Autolock _l(mLock);
207 if (!unregisterDynamicSensorLocked(handle)) {
208 ALOGE("Runtime sensor release error.");
209 return UNKNOWN_ERROR;
210 }
211 }
212
213 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
214 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
215 connection->removeSensor(handle);
216 }
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100217
218 // If this was the last sensor for this device, remove its callback.
219 bool deviceHasSensors = false;
220 mSensors.forEachEntry(
221 [&deviceId, &deviceHasSensors] (const SensorServiceUtil::SensorList::Entry& e) -> bool {
222 if (e.deviceId == deviceId) {
223 deviceHasSensors = true;
224 return false; // stop iterating
225 }
226 return true;
227 });
228 if (!deviceHasSensors) {
229 mRuntimeSensorCallbacks.erase(deviceId);
230 }
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200231 return OK;
232}
233
234status_t SensorService::sendRuntimeSensorEvent(const sensors_event_t& event) {
235 Mutex::Autolock _l(mLock);
236 mRuntimeSensorEventQueue.push(event);
237 return OK;
238}
239
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700240bool SensorService::initializeHmacKey() {
241 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
242 if (fd != -1) {
243 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
244 close(fd);
245 if (result == sizeof(sHmacGlobalKey)) {
246 return true;
247 }
248 ALOGW("Unable to read HMAC key; generating new one.");
249 }
250
251 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
252 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
253 return false;
254 }
255
256 // We need to make sure this is only readable to us.
257 bool wroteKey = false;
258 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
259 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
260 S_IRUSR|S_IWUSR);
261 if (fd != -1) {
262 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
263 close(fd);
264 wroteKey = (result == sizeof(sHmacGlobalKey));
265 }
266 if (wroteKey) {
267 ALOGI("Generated new HMAC key.");
268 } else {
269 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
270 "after reboot.");
271 }
272 // Even if we failed to write the key we return true, because we did
273 // initialize the HMAC key.
274 return true;
275}
276
Peng Xu98d30f62016-08-01 18:12:11 -0700277// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
278void SensorService::enableSchedFifoMode() {
279 struct sched_param param = {0};
280 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
281 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
282 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
283 }
284}
285
Peng Xu47e96012016-03-28 17:55:56 -0700286void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000287 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800288 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700289
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700290 sHmacGlobalKeyIsValid = initializeHmacKey();
291
Mathias Agopianf001c922010-11-11 17:58:51 -0800292 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800293 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700294 ssize_t count = dev.getSensorList(&list);
295 if (count > 0) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700296 bool hasGyro = false, hasAccel = false, hasMag = false;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700297 bool hasGyroUncalibrated = false;
298 bool hasAccelUncalibrated = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700299 uint32_t virtualSensorsNeeds =
300 (1<<SENSOR_TYPE_GRAVITY) |
301 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700302 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
303 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
304 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700305
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700306 for (ssize_t i=0 ; i<count ; i++) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700307 bool useThisSensor = true;
Peng Xuf66684a2015-07-23 11:41:53 -0700308
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700309 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700310 case SENSOR_TYPE_ACCELEROMETER:
311 hasAccel = true;
312 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700313 case SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED:
314 hasAccelUncalibrated = true;
315 break;
Aravind Akellaf5047892015-07-20 17:29:33 -0700316 case SENSOR_TYPE_MAGNETIC_FIELD:
317 hasMag = true;
318 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700319 case SENSOR_TYPE_GYROSCOPE:
320 hasGyro = true;
321 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700322 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
323 hasGyroUncalibrated = true;
324 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700325 case SENSOR_TYPE_GRAVITY:
326 case SENSOR_TYPE_LINEAR_ACCELERATION:
327 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700328 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
329 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
330 if (IGNORE_HARDWARE_FUSION) {
331 useThisSensor = false;
332 } else {
333 virtualSensorsNeeds &= ~(1<<list[i].type);
334 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700335 break;
Arthur Ishiguro2fd90a72021-11-12 17:24:41 +0000336 default:
337 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700338 }
Peng Xuf66684a2015-07-23 11:41:53 -0700339 if (useThisSensor) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700340 if (list[i].type == SENSOR_TYPE_PROXIMITY) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100341 auto s = std::make_shared<ProximitySensor>(list[i], *this);
342 const int handle = s->getSensor().getHandle();
343 if (registerSensor(std::move(s))) {
344 mProxSensorHandles.push_back(handle);
345 }
Andrew Lehmer3a602572021-03-25 15:19:56 -0700346 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100347 registerSensor(std::make_shared<HardwareSensor>(list[i]));
Andrew Lehmer3a602572021-03-25 15:19:56 -0700348 }
Peng Xuf66684a2015-07-23 11:41:53 -0700349 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700350 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700351
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700352 // it's safe to instantiate the SensorFusion object here
353 // (it wants to be instantiated after h/w sensors have been
354 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700355 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700356
Tyler Trephanc7b92632021-07-21 10:39:38 -0700357 if ((hasGyro || hasGyroUncalibrated) && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700358 // Add Android virtual sensors if they're not already
359 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700360 bool needRotationVector =
361 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100362 registerVirtualSensor(std::make_shared<RotationVectorSensor>(),
363 /* isDebug= */ !needRotationVector);
364 registerVirtualSensor(std::make_shared<OrientationSensor>(),
365 /* isDebug= */ !needRotationVector);
Mathias Agopian03193062013-05-10 19:32:39 -0700366
Peng Xu0cc8f802016-04-05 23:46:03 -0700367 // virtual debugging sensors are not for user
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100368 registerVirtualSensor(std::make_shared<CorrectedGyroSensor>(list, count),
369 /* isDebug= */ true);
370 registerVirtualSensor(std::make_shared<GyroDriftSensor>(), /* isDebug= */ true);
Mathias Agopian33264862012-06-28 19:46:54 -0700371 }
372
Tyler Trephanc7b92632021-07-21 10:39:38 -0700373 if (hasAccel && (hasGyro || hasGyroUncalibrated)) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700374 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100375 registerVirtualSensor(std::make_shared<GravitySensor>(list, count),
376 /* isDebug= */ !needGravitySensor);
Peng Xuf66684a2015-07-23 11:41:53 -0700377
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800378 bool needLinearAcceleration =
379 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100380 registerVirtualSensor(std::make_shared<LinearAccelerationSensor>(list, count),
381 /* isDebug= */ !needLinearAcceleration);
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800382
Peng Xu0cc8f802016-04-05 23:46:03 -0700383 bool needGameRotationVector =
384 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100385 registerVirtualSensor(std::make_shared<GameRotationVectorSensor>(),
386 /* isDebug= */ !needGameRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700387 }
388
389 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700390 bool needGeoMagRotationVector =
391 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100392 registerVirtualSensor(std::make_shared<GeoMagRotationVectorSensor>(),
393 /* isDebug= */ !needGeoMagRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700394 }
395
Tyler Trephanc7b92632021-07-21 10:39:38 -0700396 if (isAutomotive()) {
397 if (hasAccel) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100398 registerVirtualSensor(
399 std::make_shared<LimitedAxesImuSensor>(
400 list, count, SENSOR_TYPE_ACCELEROMETER));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700401 }
402
403 if (hasGyro) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100404 registerVirtualSensor(
405 std::make_shared<LimitedAxesImuSensor>(
406 list, count, SENSOR_TYPE_GYROSCOPE));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700407 }
408
409 if (hasAccelUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100410 registerVirtualSensor(
411 std::make_shared<LimitedAxesImuSensor>(
412 list, count, SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700413 }
414
415 if (hasGyroUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100416 registerVirtualSensor(
417 std::make_shared<LimitedAxesImuSensor>(
418 list, count, SENSOR_TYPE_GYROSCOPE_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700419 }
420 }
421
Aravind Akella5466c3d2014-08-22 16:11:10 -0700422 // Check if the device really supports batching by looking at the FIFO event
423 // counts for each sensor.
424 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700425 mSensors.forEachSensor(
426 [&batchingSupported] (const Sensor& s) -> bool {
427 if (s.getFifoMaxEventCount() > 0) {
428 batchingSupported = true;
429 }
430 return !batchingSupported;
431 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700432
433 if (batchingSupported) {
434 // Increase socket buffer size to a max of 100 KB for batching capabilities.
435 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
436 } else {
437 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
438 }
439
440 // Compare the socketBufferSize value against the system limits and limit
441 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700442 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
443 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700444 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700445 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700446 size_t maxSystemSocketBufferSize;
447 sscanf(line, "%zu", &maxSystemSocketBufferSize);
448 if (mSocketBufferSize > maxSystemSocketBufferSize) {
449 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700450 }
451 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700452 if (fp) {
453 fclose(fp);
454 }
455
Aravind Akella9a844cf2014-02-11 18:58:52 -0800456 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700457 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700458 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
459 mSensorEventBuffer = new sensors_event_t[minBufferSize];
460 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700461 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700462 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700463
Aravind Akella18d6d512015-06-18 14:18:28 -0700464 mNextSensorRegIndex = 0;
465 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
466 mLastNSensorRegistrations.push();
467 }
468
469 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700470 mAckReceiver = new SensorEventAckReceiver(this);
471 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700472 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700473
474 // priority can only be changed after run
475 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800476
477 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800478 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800479
480 // Start watching sensor privacy changes
481 mSensorPrivacyPolicy->registerSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800482
483 // Start watching mic sensor privacy changes
484 mMicSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800485 }
486 }
487}
488
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700489void SensorService::onUidStateChanged(uid_t uid, UidState state) {
490 SensorDevice& dev(SensorDevice::getInstance());
491
Brian Duddie967ce172019-06-10 11:08:27 -0700492 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700493 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700494 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700495 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700496 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700497 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700498
499 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
500 if (conn->getUid() == uid) {
501 // Update sensor subscriptions if needed
502 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
503 conn->onSensorAccessChanged(hasAccess);
504 }
505 }
Chris Kuiper587ef9b2021-10-12 16:36:43 -0700506 checkAndReportProxStateChangeLocked();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700507}
508
509bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
510 Mutex::Autolock _l(mLock);
511 return hasSensorAccessLocked(uid, opPackageName);
512}
513
514bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
515 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
516 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700517}
518
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100519bool SensorService::registerSensor(std::shared_ptr<SensorInterface> s, bool isDebug, bool isVirtual,
520 int deviceId) {
521 const int handle = s->getSensor().getHandle();
522 const int type = s->getSensor().getType();
523 if (mSensors.add(handle, std::move(s), isDebug, isVirtual, deviceId)) {
Brian Stack4baa5be2018-09-18 14:03:13 -0700524 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100525 return true;
Peng Xu0cc8f802016-04-05 23:46:03 -0700526 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100527 LOG_FATAL("Failed to register sensor with handle %d", handle);
528 return false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700529 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800530}
531
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100532bool SensorService::registerDynamicSensorLocked(std::shared_ptr<SensorInterface> s, bool isDebug) {
533 return registerSensor(std::move(s), isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800534}
535
Peng Xu6a2d3a02015-12-21 12:00:23 -0800536bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700537 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800538
539 const auto i = mRecentEvent.find(handle);
540 if (i != mRecentEvent.end()) {
541 delete i->second;
542 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800543 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700544 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800545}
546
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100547bool SensorService::registerVirtualSensor(std::shared_ptr<SensorInterface> s, bool isDebug) {
548 return registerSensor(std::move(s), isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700549}
550
Peng Xu47e96012016-03-28 17:55:56 -0700551SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800552 for (auto && entry : mRecentEvent) {
553 delete entry.second;
554 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800555 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800556 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800557 mMicSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700558}
559
560status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700561 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700562 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800563 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700564 IPCThreadState::self()->getCallingPid(),
565 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700566 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700567 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700568 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800569 return INVALID_OPERATION;
570 }
Anthony Stangec1608152023-01-06 21:14:46 +0000571 if (args.size() > 0) {
572 Mode targetOperatingMode = NORMAL;
573 std::string inputStringMode = String8(args[0]).string();
574 if (getTargetOperatingMode(inputStringMode, &targetOperatingMode)) {
575 status_t error = changeOperatingMode(args, targetOperatingMode);
576 // Dump the latest state only if no error was encountered.
577 if (error != NO_ERROR) {
578 return error;
579 }
Aravind Akella444f2672015-05-07 12:40:52 -0700580 }
Anthony Stangec1608152023-01-06 21:14:46 +0000581 }
Peng Xue36e3472016-11-03 11:57:10 -0700582
Anthony Stangec1608152023-01-06 21:14:46 +0000583 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
584 // Run the following logic if a transition isn't requested above based on the input
585 // argument parsing.
586 if (args.size() == 1 && args[0] == String16("--proto")) {
Mike Ma24743862020-01-29 00:36:55 -0800587 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700588 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700589 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700590 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700591 } else {
592 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700593 //
Brian Stack51498e62018-10-03 10:52:21 -0700594 timespec curTime;
595 clock_gettime(CLOCK_REALTIME, &curTime);
596 struct tm* timeinfo = localtime(&(curTime.tv_sec));
597 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
598 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800599 result.append("Sensor Device:\n");
600 result.append(SensorDevice::getInstance().dump().c_str());
601
602 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700603 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700604
Peng Xu6a2d3a02015-12-21 12:00:23 -0800605 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700606 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700607
Peng Xu0cc8f802016-04-05 23:46:03 -0700608 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800609 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100610 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
611 if (!i.second->isEmpty() && s != nullptr) {
Peng Xufba3c112016-09-08 12:36:59 -0700612 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
613 i.second->setFormat("normal");
614 } else {
615 i.second->setFormat("mask_data");
616 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800617 // if there is events and sensor does not need special permission.
618 result.appendFormat("%s: ", s->getSensor().getName().string());
619 result.append(i.second->dump().c_str());
620 }
621 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700622
Aravind Akella444f2672015-05-07 12:40:52 -0700623 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700624 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700625 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
626 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700627 if (dev.isSensorActive(handle)) {
628 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
629 getSensorName(handle).string(),
630 handle,
631 mActiveSensors.valueAt(i)->getNumConnections());
632 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700633 }
634
Andreas Gamped4036b62015-07-28 13:49:04 -0700635 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700636 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700637 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
638 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700639 result.appendFormat("Mode :");
640 switch(mCurrentOperatingMode) {
641 case NORMAL:
642 result.appendFormat(" NORMAL\n");
643 break;
644 case RESTRICTED:
Anthony Stangecd01ec12023-01-06 18:35:13 +0000645 result.appendFormat(" RESTRICTED : %s\n", mAllowListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700646 break;
647 case DATA_INJECTION:
Anthony Stangecd01ec12023-01-06 18:35:13 +0000648 result.appendFormat(" DATA_INJECTION : %s\n", mAllowListedPackage.string());
Anthony Stange9bb16702023-01-03 22:42:31 +0000649 break;
650 case REPLAY_DATA_INJECTION:
651 result.appendFormat(" REPLAY_DATA_INJECTION : %s\n",
Anthony Stangecd01ec12023-01-06 18:35:13 +0000652 mAllowListedPackage.string());
Anthony Stange9bb16702023-01-03 22:42:31 +0000653 break;
654 default:
655 result.appendFormat(" UNKNOWN\n");
656 break;
Mathias Agopianba02cd22013-07-03 16:20:57 -0700657 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800658 result.appendFormat("Sensor Privacy: %s\n",
659 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700660
Brian Duddie967ce172019-06-10 11:08:27 -0700661 const auto& activeConnections = connLock.getActiveConnections();
662 result.appendFormat("%zd active connections\n", activeConnections.size());
663 for (size_t i=0 ; i < activeConnections.size() ; i++) {
664 result.appendFormat("Connection Number: %zu \n", i);
665 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700666 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700667
Brian Duddie967ce172019-06-10 11:08:27 -0700668 const auto& directConnections = connLock.getDirectConnections();
669 result.appendFormat("%zd direct connections\n", directConnections.size());
670 for (size_t i = 0 ; i < directConnections.size() ; i++) {
671 result.appendFormat("Direct connection %zu:\n", i);
672 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700673 }
674
Aravind Akella18d6d512015-06-18 14:18:28 -0700675 result.appendFormat("Previous Registrations:\n");
676 // Log in the reverse chronological order.
677 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
678 SENSOR_REGISTRATIONS_BUF_SIZE;
679 const int startIndex = currentIndex;
680 do {
681 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
682 if (SensorRegistrationInfo::isSentinel(reg_info)) {
683 // Ignore sentinel, proceed to next item.
684 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
685 SENSOR_REGISTRATIONS_BUF_SIZE;
686 continue;
687 }
Peng Xu51224682017-03-10 16:57:27 -0800688 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700689 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
690 SENSOR_REGISTRATIONS_BUF_SIZE;
691 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700692 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700693 }
694 write(fd, result.string(), result.size());
695 return NO_ERROR;
696}
697
Mike Ma24743862020-01-29 00:36:55 -0800698/**
699 * Dump debugging information as android.service.SensorServiceProto protobuf message using
700 * ProtoOutputStream.
701 *
702 * See proto definition and some notes about ProtoOutputStream in
703 * frameworks/base/core/proto/android/service/sensor_service.proto
704 */
705status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
706 using namespace service::SensorServiceProto;
707 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800708 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
709 if (!mSensors.hasAnySensor()) {
710 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
711 }
Mike Ma24743862020-01-29 00:36:55 -0800712 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
713
714 timespec curTime;
715 clock_gettime(CLOCK_REALTIME, &curTime);
716 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
717
718 // Write SensorDeviceProto
719 uint64_t token = proto.start(SENSOR_DEVICE);
720 SensorDevice::getInstance().dump(&proto);
721 proto.end(token);
722
723 // Write SensorListProto
724 token = proto.start(SENSORS);
725 mSensors.dump(&proto);
726 proto.end(token);
727
728 // Write SensorFusionProto
729 token = proto.start(FUSION_STATE);
730 SensorFusion::getInstance().dump(&proto);
731 proto.end(token);
732
733 // Write SensorEventsProto
734 token = proto.start(SENSOR_EVENTS);
735 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100736 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
737 if (!i.second->isEmpty() && s != nullptr) {
Mike Ma24743862020-01-29 00:36:55 -0800738 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
739 "normal" : "mask_data");
740 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
741 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
742 std::string(s->getSensor().getName().string()));
743 i.second->dump(&proto);
744 proto.end(mToken);
745 }
746 }
747 proto.end(token);
748
749 // Write ActiveSensorProto
750 SensorDevice& dev = SensorDevice::getInstance();
751 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
752 int handle = mActiveSensors.keyAt(i);
753 if (dev.isSensorActive(handle)) {
754 token = proto.start(ACTIVE_SENSORS);
755 proto.write(service::ActiveSensorProto::NAME,
756 std::string(getSensorName(handle).string()));
757 proto.write(service::ActiveSensorProto::HANDLE, handle);
758 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
759 int(mActiveSensors.valueAt(i)->getNumConnections()));
760 proto.end(token);
761 }
762 }
763
764 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
765 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
766 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
767
768 switch(mCurrentOperatingMode) {
769 case NORMAL:
770 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
771 break;
772 case RESTRICTED:
773 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
Anthony Stangecd01ec12023-01-06 18:35:13 +0000774 proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.string()));
Mike Ma24743862020-01-29 00:36:55 -0800775 break;
776 case DATA_INJECTION:
777 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
Anthony Stangecd01ec12023-01-06 18:35:13 +0000778 proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.string()));
Mike Ma24743862020-01-29 00:36:55 -0800779 break;
780 default:
781 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
782 }
783 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
784
785 // Write repeated SensorEventConnectionProto
786 const auto& activeConnections = connLock->getActiveConnections();
787 for (size_t i = 0; i < activeConnections.size(); i++) {
788 token = proto.start(ACTIVE_CONNECTIONS);
789 activeConnections[i]->dump(&proto);
790 proto.end(token);
791 }
792
793 // Write repeated SensorDirectConnectionProto
794 const auto& directConnections = connLock->getDirectConnections();
795 for (size_t i = 0 ; i < directConnections.size() ; i++) {
796 token = proto.start(DIRECT_CONNECTIONS);
797 directConnections[i]->dump(&proto);
798 proto.end(token);
799 }
800
801 // Write repeated SensorRegistrationInfoProto
802 const int startIndex = mNextSensorRegIndex;
803 int curr = startIndex;
804 do {
805 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
806 if (SensorRegistrationInfo::isSentinel(reg_info)) {
807 // Ignore sentinel, proceed to next item.
808 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
809 continue;
810 }
811 token = proto.start(PREVIOUS_REGISTRATIONS);
812 reg_info.dump(&proto);
813 proto.end(token);
814 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
815 } while (startIndex != curr);
816
817 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
818}
819
Michael Groover5e1f60b2018-12-04 22:34:29 -0800820void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700821 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
822 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800823}
824
Brian Duddie967ce172019-06-10 11:08:27 -0700825void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800826 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700827 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
828 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
829 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800830 }
831 dev.disableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700832 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800833 // Clear all pending flush connections for all active sensors. If one of the active
834 // connections has called flush() and the underlying sensor has been disabled before a
835 // flush complete event is returned, we need to remove the connection from this queue.
836 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
837 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
838 }
839}
840
841void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700842 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
843 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800844}
845
Brian Duddie967ce172019-06-10 11:08:27 -0700846void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800847 // sensors should only be enabled if the operating state is not restricted and sensor
848 // privacy is not enabled.
849 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
850 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
851 mCurrentOperatingMode,
852 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
853 return;
854 }
855 SensorDevice& dev(SensorDevice::getInstance());
856 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700857 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
858 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
859 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800860 }
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700861 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800862}
863
Evan Severson4c197852022-01-27 10:44:27 -0800864void SensorService::capRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100865 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
866 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800867 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100868 }
869
870 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800871 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100872 }
873}
874
Evan Severson4c197852022-01-27 10:44:27 -0800875void SensorService::uncapRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100876 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
877 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800878 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100879 }
880
881 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800882 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100883 }
884}
Brian Duddie967ce172019-06-10 11:08:27 -0700885
Svet Ganove752a5c2018-01-15 17:14:20 -0800886// NOTE: This is a remote API - make sure all args are validated
887status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
888 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
889 return PERMISSION_DENIED;
890 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700891 if (args.size() == 0) {
892 return BAD_INDEX;
893 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800894 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
895 return BAD_VALUE;
896 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700897 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800898 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700899 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800900 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700901 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800902 return handleGetUidState(args, out, err);
Brian Duddie4a4d0462022-05-09 16:49:49 -0700903 } else if (args[0] == String16("unrestrict-ht")) {
904 mHtRestricted = false;
905 return NO_ERROR;
906 } else if (args[0] == String16("restrict-ht")) {
907 mHtRestricted = true;
908 return NO_ERROR;
Svet Ganove752a5c2018-01-15 17:14:20 -0800909 } else if (args.size() == 1 && args[0] == String16("help")) {
910 printHelp(out);
911 return NO_ERROR;
912 }
913 printHelp(err);
914 return BAD_VALUE;
915}
916
Tanmay Patild33a1822019-04-11 18:38:55 -0700917static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800918 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700919 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800920 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700921 ALOGE("Unknown package: '%s'", String8(packageName).string());
922 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800923 return BAD_VALUE;
924 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700925
926 if (userId < 0) {
927 ALOGE("Invalid user: %d", userId);
928 dprintf(err, "Invalid user: %d\n", userId);
929 return BAD_VALUE;
930 }
931
932 uid = multiuser_get_uid(userId, uid);
933 return NO_ERROR;
934}
935
936status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
937 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
938 if (!(args.size() == 3 || args.size() == 5)) {
939 printHelp(err);
940 return BAD_VALUE;
941 }
942
Svet Ganove752a5c2018-01-15 17:14:20 -0800943 bool active = false;
944 if (args[2] == String16("active")) {
945 active = true;
946 } else if ((args[2] != String16("idle"))) {
947 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
948 return BAD_VALUE;
949 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700950
951 int userId = 0;
952 if (args.size() == 5 && args[3] == String16("--user")) {
953 userId = atoi(String8(args[4]));
954 }
955
956 uid_t uid;
957 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
958 return BAD_VALUE;
959 }
960
Svet Ganove752a5c2018-01-15 17:14:20 -0800961 mUidPolicy->addOverrideUid(uid, active);
962 return NO_ERROR;
963}
964
965status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700966 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
967 if (!(args.size() == 2 || args.size() == 4)) {
968 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800969 return BAD_VALUE;
970 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700971
972 int userId = 0;
973 if (args.size() == 4 && args[2] == String16("--user")) {
974 userId = atoi(String8(args[3]));
975 }
976
977 uid_t uid;
978 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
979 return BAD_VALUE;
980 }
981
Svet Ganove752a5c2018-01-15 17:14:20 -0800982 mUidPolicy->removeOverrideUid(uid);
983 return NO_ERROR;
984}
985
986status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700987 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
988 if (!(args.size() == 2 || args.size() == 4)) {
989 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800990 return BAD_VALUE;
991 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700992
993 int userId = 0;
994 if (args.size() == 4 && args[2] == String16("--user")) {
995 userId = atoi(String8(args[3]));
996 }
997
998 uid_t uid;
999 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1000 return BAD_VALUE;
1001 }
1002
Svet Ganove752a5c2018-01-15 17:14:20 -08001003 if (mUidPolicy->isUidActive(uid)) {
1004 return dprintf(out, "active\n");
1005 } else {
1006 return dprintf(out, "idle\n");
1007 }
1008}
1009
1010status_t SensorService::printHelp(int out) {
1011 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -07001012 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1013 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1014 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -08001015 " help print this message\n");
1016}
1017
Peng Xu0cc8f802016-04-05 23:46:03 -07001018//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -08001019void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001020 sensors_event_t const* buffer, const int count) {
1021 for (int i=0 ; i<count ; i++) {
1022 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -07001023 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1024 handle = buffer[i].meta_data.sensor;
1025 }
Aravind Akella0e025c52014-06-03 19:19:57 -07001026 if (connection->hasSensor(handle)) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001027 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -07001028 // If this buffer has an event from a one_shot sensor and this connection is registered
1029 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -07001030 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -07001031 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1032 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001033 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001034 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001035
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001036 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001037 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001038}
1039
Peng Xu47e96012016-03-28 17:55:56 -07001040bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +00001041 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -07001042
Peng Xueb4d6282015-12-10 18:02:41 -08001043 // each virtual sensor could generate an event per "real" event, that's why we need to size
1044 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
1045 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -07001046 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001047 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -07001048 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001049
Mathias Agopianf001c922010-11-11 17:58:51 -08001050 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -07001051
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001052 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -07001053 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001054 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
1055 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -07001056 if(count == DEAD_OBJECT && device.isReconnecting()) {
1057 device.reconnect();
1058 continue;
1059 } else {
1060 ALOGE("sensor poll failed (%s)", strerror(-count));
1061 break;
1062 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001063 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001064
1065 // Reset sensors_event_t.flags to zero for all events in the buffer.
1066 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001067 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001068 }
Brian Duddie967ce172019-06-10 11:08:27 -07001069 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -07001070
Aravind Akella9a844cf2014-02-11 18:58:52 -08001071 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
1072 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
1073 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
1074 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
1075 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001076 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001077 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001078 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001079 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001080 }
1081 }
1082
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001083 if (wakeEvents > 0) {
1084 if (!mWakeLockAcquired) {
1085 setWakeLockAcquiredLocked(true);
1086 }
1087 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001088 }
Aravind Akella8493b792014-09-08 15:45:47 -07001089 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -08001090
Mathias Agopianf001c922010-11-11 17:58:51 -08001091 // handle virtual sensors
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001092 bool bufferNeedsSorting = false;
Mathias Agopianf001c922010-11-11 17:58:51 -08001093 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -07001094 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -07001095 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001096 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -07001097 SensorFusion& fusion(SensorFusion::getInstance());
1098 if (fusion.isEnabled()) {
1099 for (size_t i=0 ; i<size_t(count) ; i++) {
1100 fusion.process(event[i]);
1101 }
1102 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001103 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -07001104 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001105 if (count + k >= minBufferSize) {
1106 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -07001107 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001108 count, k, minBufferSize);
1109 break;
1110 }
Mathias Agopianf001c922010-11-11 17:58:51 -08001111 sensors_event_t out;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001112 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001113 if (si == nullptr) {
1114 ALOGE("handle %d is not an valid virtual sensor", handle);
1115 continue;
1116 }
1117
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001118 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -07001119 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -08001120 k++;
1121 }
1122 }
1123 }
1124 if (k) {
1125 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -07001126 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -08001127 count += k;
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001128 bufferNeedsSorting = true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001129 }
1130 }
1131 }
1132
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001133 // handle runtime sensors
1134 {
1135 size_t k = 0;
1136 while (!mRuntimeSensorEventQueue.empty()) {
1137 if (count + k >= minBufferSize) {
1138 ALOGE("buffer too small to hold all events: count=%zd, k=%zu, size=%zu",
1139 count, k, minBufferSize);
1140 break;
1141 }
1142 mSensorEventBuffer[count + k] = mRuntimeSensorEventQueue.front();
1143 mRuntimeSensorEventQueue.pop();
1144 k++;
1145 }
1146 if (k) {
1147 // record the last synthesized values
1148 recordLastValueLocked(&mSensorEventBuffer[count], k);
1149 count += k;
1150 bufferNeedsSorting = true;
1151 }
1152 }
1153
1154 if (bufferNeedsSorting) {
1155 // sort the buffer by time-stamps
1156 sortEventBuffer(mSensorEventBuffer, count);
1157 }
1158
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001159 // handle backward compatibility for RotationVector sensor
1160 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
1161 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001162 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001163 // All the 4 components of the quaternion should be available
1164 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -07001165 mSensorEventBuffer[i].data[4] = -1;
1166 }
1167 }
1168 }
1169
Brian Duddie967ce172019-06-10 11:08:27 -07001170 // Cache the list of active connections, since we use it in multiple places below but won't
1171 // modify it here
1172 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
1173
Aravind Akella8493b792014-09-08 15:45:47 -07001174 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -07001175 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
1176 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
1177 // SensorEventConnection mapped to the corresponding flush_complete_event in
1178 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -07001179 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -07001180 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
1181 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
1182 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001183 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -07001184 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
1185 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001186 }
1187 }
Peng Xu2576cb62016-01-20 00:22:09 -08001188
1189 // handle dynamic sensor meta events, process registration and unregistration of dynamic
1190 // sensor based on content of event.
1191 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
1192 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
1193 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1194 const sensor_t& dynamicSensor =
1195 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
1196 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
1197 handle, dynamicSensor.type, dynamicSensor.name);
1198
Peng Xu0cc8f802016-04-05 23:46:03 -07001199 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -08001200 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -07001201 sensor_t s = dynamicSensor;
1202 // make sure the dynamic sensor flag is set
1203 s.flags |= DYNAMIC_SENSOR_MASK;
1204 // force the handle to be consistent
1205 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -08001206
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001207 auto si = std::make_shared<HardwareSensor>(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -08001208
Peng Xu0cc8f802016-04-05 23:46:03 -07001209 // This will release hold on dynamic sensor meta, so it should be called
1210 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -07001211 device.handleDynamicSensorConnection(handle, true /*connected*/);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001212 registerDynamicSensorLocked(std::move(si));
Peng Xu47e96012016-03-28 17:55:56 -07001213 } else {
1214 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
1215 }
Peng Xu2576cb62016-01-20 00:22:09 -08001216 } else {
1217 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1218 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1219
1220 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001221 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -08001222 ALOGE("Dynamic sensor release error.");
1223 }
1224
Brian Duddie967ce172019-06-10 11:08:27 -07001225 for (const sp<SensorEventConnection>& connection : activeConnections) {
1226 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001227 }
1228 }
1229 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001230 }
1231
Aravind Akella9a844cf2014-02-11 18:58:52 -08001232 // Send our events to clients. Check the state of wake lock for each client and release the
1233 // lock if none of the clients need it.
1234 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001235 for (const sp<SensorEventConnection>& connection : activeConnections) {
1236 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1237 mMapFlushEventsToConnections);
1238 needsWakeLock |= connection->needsWakeLock();
1239 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1240 // Early check for one-shot sensors.
1241 if (connection->hasOneShotSensors()) {
1242 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001243 }
1244 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001245
Aravind Akella9a844cf2014-02-11 18:58:52 -08001246 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001247 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001248 }
Aravind Akella8493b792014-09-08 15:45:47 -07001249 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001250
Steve Block3c20fbe2012-01-05 23:22:43 +00001251 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001252 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001253 return false;
1254}
1255
Aravind Akella56ae4262014-07-10 16:01:10 -07001256sp<Looper> SensorService::getLooper() const {
1257 return mLooper;
1258}
1259
Aravind Akellab4373ac2014-10-29 17:55:20 -07001260void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001261 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1262 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1263 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001264 }
Brian Duddie967ce172019-06-10 11:08:27 -07001265 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001266}
1267
1268void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1269 if (acquire) {
1270 if (!mWakeLockAcquired) {
1271 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1272 mWakeLockAcquired = true;
1273 }
1274 mLooper->wake();
1275 } else {
1276 if (mWakeLockAcquired) {
1277 release_wake_lock(WAKE_LOCK_NAME);
1278 mWakeLockAcquired = false;
1279 }
1280 }
1281}
1282
Aravind Akellab4373ac2014-10-29 17:55:20 -07001283bool SensorService::isWakeLockAcquired() {
1284 Mutex::Autolock _l(mLock);
1285 return mWakeLockAcquired;
1286}
1287
Aravind Akella56ae4262014-07-10 16:01:10 -07001288bool SensorService::SensorEventAckReceiver::threadLoop() {
1289 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001290 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001291 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001292 bool wakeLockAcquired = mService->isWakeLockAcquired();
1293 int timeout = -1;
1294 if (wakeLockAcquired) timeout = 5000;
1295 int ret = looper->pollOnce(timeout);
1296 if (ret == ALOOPER_POLL_TIMEOUT) {
1297 mService->resetAllWakeLockRefCounts();
1298 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001299 } while(!Thread::exitPending());
1300 return false;
1301}
1302
Aravind Akella9a844cf2014-02-11 18:58:52 -08001303void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001304 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001305 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001306 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1307 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001308 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001309 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001310 }
Peng Xu2576cb62016-01-20 00:22:09 -08001311
Peng Xu6a2d3a02015-12-21 12:00:23 -08001312 auto logger = mRecentEvent.find(buffer[i].sensor);
1313 if (logger != mRecentEvent.end()) {
1314 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001315 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001316 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001317}
1318
Peng Xu47e96012016-03-28 17:55:56 -07001319void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001320 struct compar {
1321 static int cmp(void const* lhs, void const* rhs) {
1322 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1323 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001324 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001325 }
1326 };
1327 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1328}
1329
Mathias Agopian5d270722010-07-19 15:20:39 -07001330String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001331 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001332}
1333
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001334String8 SensorService::getSensorStringType(int handle) const {
1335 return mSensors.getStringType(handle);
1336}
1337
Aravind Akellab4099e72013-10-15 15:43:10 -07001338bool SensorService::isVirtualSensor(int handle) const {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001339 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001340 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001341}
1342
Aravind Akella9a844cf2014-02-11 18:58:52 -08001343bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001344 int handle = event.sensor;
1345 if (event.type == SENSOR_TYPE_META_DATA) {
1346 handle = event.meta_data.sensor;
1347 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001348 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001349 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001350}
1351
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001352int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1353 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1354 // UUID is not supported for this device.
1355 return 0;
1356 }
1357 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1358 // This sensor can be uniquely identified in the system by
1359 // the combination of its type and name.
1360 return -1;
1361 }
1362
1363 // We have a dynamic sensor.
1364
1365 if (!sHmacGlobalKeyIsValid) {
lifr3ab0a1b2021-08-06 00:14:26 +08001366 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001367 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1368 return 0;
1369 }
1370
1371 // We want each app author/publisher to get a different ID, so that the
1372 // same dynamic sensor cannot be tracked across apps by multiple
1373 // authors/publishers. So we use both our UUID and our User ID.
1374 // Note potential confusion:
1375 // UUID => Universally Unique Identifier.
1376 // UID => User Identifier.
1377 // We refrain from using "uid" except as needed by API to try to
1378 // keep this distinction clear.
1379
1380 auto appUserId = IPCThreadState::self()->getCallingUid();
1381 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1382 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1383 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1384
1385 // Now we use our key on our UUID/app combo to get the hash.
1386 uint8_t hash[EVP_MAX_MD_SIZE];
1387 unsigned int hashLen;
1388 if (HMAC(EVP_sha256(),
1389 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1390 uuidAndApp, sizeof(uuidAndApp),
1391 hash, &hashLen) == nullptr) {
lifr3ab0a1b2021-08-06 00:14:26 +08001392 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001393 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1394 return 0;
1395 }
1396
1397 int32_t id = 0;
1398 if (hashLen < sizeof(id)) {
1399 // We never expect this case, but out of paranoia, we handle it.
1400 // Our 'id' length is already quite small, we don't want the
1401 // effective length of it to be even smaller.
1402 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1403 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1404 return 0;
1405 }
1406
1407 // This is almost certainly less than all of 'hash', but it's as secure
1408 // as we can be with our current 'id' length.
1409 memcpy(&id, hash, sizeof(id));
1410
1411 // Note at the beginning of the function that we return the values of
1412 // 0 and -1 to represent special cases. As a result, we can't return
1413 // those as dynamic sensor IDs. If we happened to hash to one of those
1414 // values, we change 'id' so we report as a dynamic sensor, and not as
1415 // one of those special cases.
1416 if (id == -1) {
1417 id = -2;
1418 } else if (id == 0) {
1419 id = 1;
1420 }
1421 return id;
1422}
1423
1424void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1425 for (auto &sensor : sensorList) {
1426 int32_t id = getIdFromUuid(sensor.getUuid());
1427 sensor.setId(id);
Eric Laurente3f27df2022-01-05 19:20:32 +01001428 // The sensor UUID must always be anonymized here for non privileged clients.
1429 // There is no other checks after this point before returning to client process.
1430 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1431 sensor.anonymizeUuid();
1432 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001433 }
1434}
1435
Anh Pham4e291332021-02-10 14:17:56 +01001436Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -07001437 char value[PROPERTY_VALUE_MAX];
1438 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001439 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001440 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001441 Vector<Sensor> accessibleSensorList;
Anh Pham4e291332021-02-10 14:17:56 +01001442
Brian Duddie0d4ac562022-05-23 17:47:50 -07001443 resetTargetSdkVersionCache(opPackageName);
Anh Pham4e291332021-02-10 14:17:56 +01001444 bool isCapped = isRateCappedBasedOnPermission(opPackageName);
Aravind Akella70018042014-04-07 22:52:37 +00001445 for (size_t i = 0; i < initialSensorList.size(); i++) {
1446 Sensor sensor = initialSensorList[i];
Anh Pham4e291332021-02-10 14:17:56 +01001447 if (isCapped && isSensorInCappedSet(sensor.getType())) {
1448 sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
1449 sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
1450 }
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001451 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001452 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001453 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001454 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001455}
1456
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001457void SensorService::addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
1458 Vector<Sensor>& accessibleSensorList) {
1459 if (canAccessSensor(sensor, "can't see", opPackageName)) {
1460 accessibleSensorList.add(sensor);
1461 } else if (sensor.getType() != SENSOR_TYPE_HEAD_TRACKER) {
1462 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1463 sensor.getName().string(), sensor.getRequiredPermission().string(),
1464 sensor.getRequiredAppOp());
1465 }
1466}
1467
Peng Xu47e96012016-03-28 17:55:56 -07001468Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001469 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001470 mSensors.forEachSensor(
Brian Duddie4a4d0462022-05-09 16:49:49 -07001471 [this, &opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001472 if (sensor.isDynamicSensor()) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001473 addSensorIfAccessible(opPackageName, sensor, accessibleSensorList);
1474 }
1475 return true;
1476 });
1477 makeUuidsIntoIdsForSensorList(accessibleSensorList);
1478 return accessibleSensorList;
1479}
1480
1481Vector<Sensor> SensorService::getRuntimeSensorList(const String16& opPackageName, int deviceId) {
1482 Vector<Sensor> accessibleSensorList;
1483 mSensors.forEachEntry(
1484 [this, &opPackageName, deviceId, &accessibleSensorList] (
1485 const SensorServiceUtil::SensorList::Entry& e) -> bool {
1486 if (e.deviceId == deviceId) {
1487 addSensorIfAccessible(opPackageName, e.si->getSensor(), accessibleSensorList);
Peng Xu0cc8f802016-04-05 23:46:03 -07001488 }
1489 return true;
1490 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001491 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001492 return accessibleSensorList;
1493}
1494
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001495sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001496 int requestedMode, const String16& opPackageName, const String16& attributionTag) {
Anthony Stange9bb16702023-01-03 22:42:31 +00001497 // Only 3 modes supported for a SensorEventConnection ... NORMAL, DATA_INJECTION and
1498 // REPLAY_DATA_INJECTION.
1499 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION &&
1500 requestedMode != REPLAY_DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001501 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001502 }
Brian Duddie0d4ac562022-05-23 17:47:50 -07001503 resetTargetSdkVersionCache(opPackageName);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001504
1505 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001506 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1507 // operating in DI mode.
1508 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001509 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
Anthony Stangecd01ec12023-01-06 18:35:13 +00001510 if (!isAllowListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001511 }
1512
Mathias Agopian5307d172012-09-18 17:02:43 -07001513 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001514 pid_t pid = IPCThreadState::self()->getCallingPid();
1515
1516 String8 connPackageName =
1517 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1518 String16 connOpPackageName =
1519 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1520 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Anthony Stange9bb16702023-01-03 22:42:31 +00001521 requestedMode == DATA_INJECTION || requestedMode == REPLAY_DATA_INJECTION,
1522 connOpPackageName, attributionTag));
1523 if (requestedMode == DATA_INJECTION || requestedMode == REPLAY_DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001524 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001525 // Add the associated file descriptor to the Looper for polling whenever there is data to
1526 // be injected.
1527 result->updateLooperRegistration(mLooper);
1528 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001529 return result;
1530}
1531
Aravind Akella841a5922015-06-29 12:37:48 -07001532int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001533 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001534 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001535}
1536
Peng Xue36e3472016-11-03 11:57:10 -07001537sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001538 const String16& opPackageName, int deviceId, uint32_t size, int32_t type, int32_t format,
Peng Xue36e3472016-11-03 11:57:10 -07001539 const native_handle *resource) {
Brian Duddie0d4ac562022-05-23 17:47:50 -07001540 resetTargetSdkVersionCache(opPackageName);
Brian Duddie967ce172019-06-10 11:08:27 -07001541 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001542
Michael Groover5e1f60b2018-12-04 22:34:29 -08001543 // No new direct connections are allowed when sensor privacy is enabled
1544 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1545 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1546 return nullptr;
1547 }
1548
Peng Xue36e3472016-11-03 11:57:10 -07001549 struct sensors_direct_mem_t mem = {
1550 .type = type,
1551 .format = format,
1552 .size = size,
1553 .handle = resource,
1554 };
1555 uid_t uid = IPCThreadState::self()->getCallingUid();
1556
1557 if (mem.handle == nullptr) {
1558 ALOGE("Failed to clone resource handle");
1559 return nullptr;
1560 }
1561
1562 // check format
1563 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1564 ALOGE("Direct channel format %d is unsupported!", format);
1565 return nullptr;
1566 }
1567
1568 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001569 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1570 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001571 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001572 return nullptr;
1573 }
1574 }
1575
1576 // check specific to memory type
1577 switch(type) {
1578 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001579 if (resource->numFds < 1) {
1580 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1581 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1582 return nullptr;
1583 }
Peng Xue36e3472016-11-03 11:57:10 -07001584 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001585 if (!ashmem_valid(fd)) {
1586 ALOGE("Supplied Ashmem memory region is invalid");
1587 return nullptr;
1588 }
1589
Peng Xue36e3472016-11-03 11:57:10 -07001590 int size2 = ashmem_get_size_region(fd);
1591 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001592 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001593 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1594 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001595 return nullptr;
1596 }
1597 break;
1598 }
1599 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001600 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001601 break;
1602 default:
1603 ALOGE("Unknown direct connection memory type %d", type);
1604 return nullptr;
1605 }
1606
1607 native_handle_t *clone = native_handle_clone(resource);
1608 if (!clone) {
1609 return nullptr;
1610 }
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001611 native_handle_set_fdsan_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001612
Brian Duddie967ce172019-06-10 11:08:27 -07001613 sp<SensorDirectConnection> conn;
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001614 int channelHandle = 0;
1615 if (deviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
1616 SensorDevice& dev(SensorDevice::getInstance());
1617 channelHandle = dev.registerDirectChannel(&mem);
1618 } else {
1619 auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1620 if (runtimeSensorCallback == mRuntimeSensorCallbacks.end()) {
1621 ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1622 } else {
1623 int fd = dup(clone->data[0]);
1624 channelHandle = runtimeSensorCallback->second->onDirectChannelCreated(fd);
1625 }
1626 }
Peng Xue36e3472016-11-03 11:57:10 -07001627
1628 if (channelHandle <= 0) {
1629 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1630 } else {
1631 mem.handle = clone;
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001632 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName, deviceId);
Peng Xue36e3472016-11-03 11:57:10 -07001633 }
1634
1635 if (conn == nullptr) {
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001636 native_handle_close_with_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001637 native_handle_delete(clone);
1638 } else {
1639 // add to list of direct connections
1640 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001641 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001642 }
1643 return conn;
1644}
1645
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001646int SensorService::configureRuntimeSensorDirectChannel(
1647 int sensorHandle, const SensorDirectConnection* c, const sensors_direct_cfg_t* config) {
1648 int deviceId = c->getDeviceId();
1649 int sensorDeviceId = getDeviceIdFromHandle(sensorHandle);
1650 if (sensorDeviceId != c->getDeviceId()) {
1651 ALOGE("Cannot configure direct channel created for device %d with a sensor that belongs"
1652 "to device %d", c->getDeviceId(), sensorDeviceId);
1653 return BAD_VALUE;
1654 }
1655 auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1656 if (runtimeSensorCallback == mRuntimeSensorCallbacks.end()) {
1657 ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1658 return BAD_VALUE;
1659 }
1660 return runtimeSensorCallback->second->onDirectChannelConfigured(
1661 c->getHalChannelHandle(), sensorHandle, config->rate_level);
1662}
1663
Peng Xudd5c5cb2017-03-16 17:39:43 -07001664int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001665 int32_t handle, int32_t type,
1666 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001667 Mutex::Autolock _l(mLock);
1668
Alexey Polyudov88711e82017-05-23 19:54:04 -07001669 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001670 return PERMISSION_DENIED;
1671 }
1672
1673 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001674 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001675 size_t expectSize = INT32_MAX;
1676 switch (type) {
1677 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1678 isFloat = true;
1679 expectSize = 3;
1680 break;
1681 case AINFO_LOCAL_GRAVITY:
1682 isFloat = true;
1683 expectSize = 1;
1684 break;
1685 case AINFO_DOCK_STATE:
1686 case AINFO_HIGH_PERFORMANCE_MODE:
1687 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1688 isFloat = false;
1689 expectSize = 1;
1690 break;
1691 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001692 // CUSTOM events must only contain float data; it may have variable size
1693 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1694 ints.size() ||
1695 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1696 handle < 0) {
1697 return BAD_VALUE;
1698 }
1699 isFloat = true;
1700 isCustom = true;
1701 expectSize = floats.size();
1702 break;
1703 }
1704
1705 if (!isCustom && handle != -1) {
1706 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001707 }
1708
1709 // three events: first one is begin tag, last one is end tag, the one in the middle
1710 // is the payload.
1711 sensors_event_t event[3];
1712 int64_t timestamp = elapsedRealtimeNano();
1713 for (sensors_event_t* i = event; i < event + 3; i++) {
1714 *i = (sensors_event_t) {
1715 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001716 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001717 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1718 .timestamp = timestamp++,
1719 .additional_info = (additional_info_event_t) {
1720 .serial = 0
1721 }
1722 };
1723 }
1724
1725 event[0].additional_info.type = AINFO_BEGIN;
1726 event[1].additional_info.type = type;
1727 event[2].additional_info.type = AINFO_END;
1728
1729 if (isFloat) {
1730 if (floats.size() != expectSize) {
1731 return BAD_VALUE;
1732 }
1733 for (size_t i = 0; i < expectSize; ++i) {
1734 event[1].additional_info.data_float[i] = floats[i];
1735 }
1736 } else {
1737 if (ints.size() != expectSize) {
1738 return BAD_VALUE;
1739 }
1740 for (size_t i = 0; i < expectSize; ++i) {
1741 event[1].additional_info.data_int32[i] = ints[i];
1742 }
1743 }
1744
1745 SensorDevice& dev(SensorDevice::getInstance());
1746 for (sensors_event_t* i = event; i < event + 3; i++) {
1747 int ret = dev.injectSensorData(i);
1748 if (ret != NO_ERROR) {
1749 return ret;
1750 }
1751 }
1752 return NO_ERROR;
1753}
1754
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001755status_t SensorService::resetToNormalMode() {
1756 Mutex::Autolock _l(mLock);
1757 return resetToNormalModeLocked();
1758}
1759
1760status_t SensorService::resetToNormalModeLocked() {
1761 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001762 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301763 if (err == NO_ERROR) {
1764 mCurrentOperatingMode = NORMAL;
1765 dev.enableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001766 checkAndReportProxStateChangeLocked();
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301767 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001768 return err;
1769}
1770
Peng Xu47e96012016-03-28 17:55:56 -07001771void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001772 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001773 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001774 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001775 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001776 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001777 int handle = mActiveSensors.keyAt(i);
1778 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001779 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001780 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001781 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001782 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001783 } else {
1784 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001785 }
Brian Duddie7be85572021-12-21 10:44:55 -08001786 if (c->removeSensor(handle)) {
1787 BatteryService::disableSensor(c->getUid(), handle);
1788 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001789 }
1790 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001791 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001792 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001793 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001794 c, i, handle);
1795
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001796 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001797 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001798 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001799 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001800 delete rec;
1801 size--;
1802 } else {
1803 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001804 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001805 }
Aravind Akella8a969552014-09-28 17:52:41 -07001806 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001807 mConnectionHolder.removeEventConnection(connection);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001808 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001809 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001810 }
Peng Xu4f707f82016-09-26 11:28:32 -07001811
1812 SensorDevice& dev(SensorDevice::getInstance());
1813 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001814}
1815
Peng Xue36e3472016-11-03 11:57:10 -07001816void SensorService::cleanupConnection(SensorDirectConnection* c) {
1817 Mutex::Autolock _l(mLock);
1818
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001819 int deviceId = c->getDeviceId();
1820 if (deviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
1821 SensorDevice& dev(SensorDevice::getInstance());
1822 dev.unregisterDirectChannel(c->getHalChannelHandle());
1823 } else {
1824 auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1825 if (runtimeSensorCallback != mRuntimeSensorCallbacks.end()) {
1826 runtimeSensorCallback->second->onDirectChannelDestroyed(c->getHalChannelHandle());
1827 } else {
1828 ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1829 }
1830 }
Brian Duddie967ce172019-06-10 11:08:27 -07001831 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001832}
1833
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001834void SensorService::checkAndReportProxStateChangeLocked() {
1835 if (mProxSensorHandles.empty()) return;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001836
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001837 SensorDevice& dev(SensorDevice::getInstance());
1838 bool isActive = false;
1839 for (auto& sensor : mProxSensorHandles) {
1840 if (dev.isSensorActive(sensor)) {
1841 isActive = true;
1842 break;
1843 }
1844 }
1845 if (isActive != mLastReportedProxIsActive) {
1846 notifyProximityStateLocked(isActive, mProximityActiveListeners);
1847 mLastReportedProxIsActive = isActive;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001848 }
1849}
1850
1851void SensorService::notifyProximityStateLocked(
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001852 const bool isActive,
Santos Cordon7ea287a2021-06-14 13:45:29 +01001853 const std::vector<sp<ProximityActiveListener>>& listeners) {
Santos Cordon7ea287a2021-06-14 13:45:29 +01001854 const uint64_t mySeq = ++curProxCallbackSeq;
1855 std::thread t([isActive, mySeq, listenersCopy = listeners]() {
1856 while (completedCallbackSeq.load() != mySeq - 1)
1857 std::this_thread::sleep_for(1ms);
1858 for (auto& listener : listenersCopy)
1859 listener->onProximityActive(isActive);
1860 completedCallbackSeq++;
1861 });
1862 t.detach();
Andrew Lehmer3a602572021-03-25 15:19:56 -07001863}
1864
1865status_t SensorService::addProximityActiveListener(const sp<ProximityActiveListener>& callback) {
1866 if (callback == nullptr) {
1867 return BAD_VALUE;
1868 }
1869
1870 Mutex::Autolock _l(mLock);
1871
1872 // Check if the callback was already added.
1873 for (const auto& cb : mProximityActiveListeners) {
1874 if (cb == callback) {
1875 return ALREADY_EXISTS;
1876 }
1877 }
1878
1879 mProximityActiveListeners.push_back(callback);
1880 std::vector<sp<ProximityActiveListener>> listener(1, callback);
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001881 notifyProximityStateLocked(mLastReportedProxIsActive, listener);
Andrew Lehmer3a602572021-03-25 15:19:56 -07001882 return OK;
1883}
1884
1885status_t SensorService::removeProximityActiveListener(
1886 const sp<ProximityActiveListener>& callback) {
1887 if (callback == nullptr) {
1888 return BAD_VALUE;
1889 }
1890
1891 Mutex::Autolock _l(mLock);
1892
1893 for (auto iter = mProximityActiveListeners.begin();
1894 iter != mProximityActiveListeners.end();
1895 ++iter) {
1896 if (*iter == callback) {
1897 mProximityActiveListeners.erase(iter);
1898 return OK;
1899 }
1900 }
1901 return NAME_NOT_FOUND;
1902}
1903
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001904std::shared_ptr<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001905 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001906}
1907
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001908int SensorService::getDeviceIdFromHandle(int handle) const {
1909 int deviceId = RuntimeSensor::DEFAULT_DEVICE_ID;
1910 mSensors.forEachEntry(
1911 [&deviceId, handle] (const SensorServiceUtil::SensorList::Entry& e) -> bool {
1912 if (e.si->getSensor().getHandle() == handle) {
1913 deviceId = e.deviceId;
1914 return false; // stop iterating
1915 }
1916 return true;
1917 });
1918 return deviceId;
1919}
1920
Mathias Agopianfc328812010-07-14 23:41:37 -07001921status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001922 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001923 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001924 if (mInitCheck != NO_ERROR)
1925 return mInitCheck;
1926
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001927 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001928 if (sensor == nullptr ||
1929 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001930 return BAD_VALUE;
1931 }
1932
Brian Duddie967ce172019-06-10 11:08:27 -07001933 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Anthony Stange9bb16702023-01-03 22:42:31 +00001934 if (mCurrentOperatingMode != NORMAL && mCurrentOperatingMode != REPLAY_DATA_INJECTION &&
Anthony Stangecd01ec12023-01-06 18:35:13 +00001935 !isAllowListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001936 return INVALID_OPERATION;
1937 }
1938
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001939 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001940 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001941 rec = new SensorRecord(connection);
1942 mActiveSensors.add(handle, rec);
1943 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001944 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001945 }
Brian Stack26029ee2019-04-22 17:25:49 -07001946
1947 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1948 // the recent event as stale to ensure that the previous event is not sent to a client. This
1949 // ensures on-change events that were generated during a previous sensor activation are not
1950 // erroneously sent to newly connected clients, especially if a second client registers for
1951 // an on-change sensor before the first client receives the updated event. Once an updated
1952 // event is received, the recent events will be marked as current, and any new clients will
1953 // immediately receive the most recent event.
1954 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1955 auto logger = mRecentEvent.find(handle);
1956 if (logger != mRecentEvent.end()) {
1957 logger->second->setLastEventStale();
1958 }
1959 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001960 } else {
1961 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001962 // this sensor is already activated, but we are adding a connection that uses it.
1963 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001964 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001965 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001966 // NOTE: The wake_up flag of this event may get set to
1967 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001968
1969 auto logger = mRecentEvent.find(handle);
1970 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001971 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001972 // Verify that the last sensor event was generated from the current activation
1973 // of the sensor. If not, it is possible for an on-change sensor to receive a
1974 // sensor event that is stale if two clients re-activate the sensor
1975 // simultaneously.
1976 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001977 event.sensor = handle;
1978 if (event.version == sizeof(sensors_event_t)) {
1979 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1980 setWakeLockAcquiredLocked(true);
1981 }
Yi Kong8f313e32018-07-17 14:13:29 -07001982 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001983 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001984 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001985 }
1986 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001987 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001988 }
1989 }
1990 }
1991 }
1992
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001993 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001994 BatteryService::enableSensor(connection->getUid(), handle);
1995 // the sensor was added (which means it wasn't already there)
1996 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001997 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001998 } else {
1999 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
2000 handle, connection.get());
2001 }
2002
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05302003 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07002004 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05302005 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
2006 samplingPeriodNs = maxDelayNs;
2007 }
2008
Aravind Akella724d91d2013-06-27 12:04:23 -07002009 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2010 if (samplingPeriodNs < minDelayNs) {
2011 samplingPeriodNs = minDelayNs;
2012 }
2013
Aravind Akella6c2664a2014-08-13 12:24:50 -07002014 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
2015 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07002016 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
2017
Aravind Akella4949c502015-02-11 15:54:35 -08002018 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07002019 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07002020
Peng Xu20483c42015-10-26 15:14:43 -07002021 // Call flush() before calling activate() on the sensor. Wait for a first
2022 // flush complete event before sending events on this connection. Ignore
2023 // one-shot sensors which don't support flush(). Ignore on-change sensors
2024 // to maintain the on-change logic (any on-change events except the initial
2025 // one should be trigger by a change in value). Also if this sensor isn't
2026 // already active, don't call flush().
2027 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08002028 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07002029 rec->getNumConnections() > 1) {
2030 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07002031 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07002032 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07002033 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07002034 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07002035 } else {
2036 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07002037 }
2038 }
Aravind Akella724d91d2013-06-27 12:04:23 -07002039
2040 if (err == NO_ERROR) {
2041 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
2042 err = sensor->activate(connection.get(), true);
2043 }
2044
Aravind Akella8a969552014-09-28 17:52:41 -07002045 if (err == NO_ERROR) {
2046 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08002047
Brian Stack240d1d62019-05-17 09:49:39 -07002048 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
2049 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07002050 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
2051 }
2052
Peng Xu51224682017-03-10 16:57:27 -08002053 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2054 SensorRegistrationInfo(handle, connection->getPackageName(),
2055 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07002056 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07002057 }
2058
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002059 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07002060 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002061 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002062 }
2063 return err;
2064}
2065
Peng Xu47e96012016-03-28 17:55:56 -07002066status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002067 if (mInitCheck != NO_ERROR)
2068 return mInitCheck;
2069
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002070 Mutex::Autolock _l(mLock);
2071 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002072 if (err == NO_ERROR) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002073 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002074 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07002075
2076 }
2077 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08002078 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2079 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07002080 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002081 }
2082 return err;
2083}
2084
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002085status_t SensorService::cleanupWithoutDisable(
2086 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002087 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002088 return cleanupWithoutDisableLocked(connection, handle);
2089}
2090
2091status_t SensorService::cleanupWithoutDisableLocked(
2092 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002093 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002094 if (rec) {
2095 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07002096 if (connection->removeSensor(handle)) {
2097 BatteryService::disableSensor(connection->getUid(), handle);
2098 }
Mathias Agopianfc328812010-07-14 23:41:37 -07002099 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07002100 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07002101 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07002102 }
2103 // see if this sensor becomes inactive
2104 if (rec->removeConnection(connection)) {
2105 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002106 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002107 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07002108 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002109 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002110 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002111 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07002112}
2113
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002114status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07002115 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002116 if (mInitCheck != NO_ERROR)
2117 return mInitCheck;
2118
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002119 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002120 if (sensor == nullptr ||
2121 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00002122 return BAD_VALUE;
2123 }
2124
Mathias Agopian1cd70002010-07-21 15:59:50 -07002125 if (ns < 0)
2126 return BAD_VALUE;
2127
Mathias Agopian62569ec2011-11-07 21:21:47 -08002128 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2129 if (ns < minDelayNs) {
2130 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07002131 }
2132
Mathias Agopianf001c922010-11-11 17:58:51 -08002133 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07002134}
2135
Svetoslavb412f6e2015-04-29 16:50:41 -07002136status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
2137 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00002138 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002139 SensorDevice& dev(SensorDevice::getInstance());
2140 const int halVersion = dev.getHalDeviceVersion();
2141 status_t err(NO_ERROR);
2142 Mutex::Autolock _l(mLock);
2143 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07002144 for (int handle : connection->getActiveSensorHandles()) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002145 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002146 if (sensor == nullptr) {
2147 continue;
2148 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002149 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
2150 ALOGE("flush called on a one-shot sensor");
2151 err = INVALID_OPERATION;
2152 continue;
2153 }
Aravind Akella8493b792014-09-08 15:45:47 -07002154 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002155 // For older devices just increment pending flush count which will send a trivial
2156 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07002157 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
2158 ALOGE("flush called on an inaccessible sensor");
2159 err = INVALID_OPERATION;
2160 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002161 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002162 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
2163 err = INVALID_OPERATION;
2164 continue;
2165 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002166 status_t err_flush = sensor->flush(connection.get(), handle);
2167 if (err_flush == NO_ERROR) {
2168 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07002169 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002170 }
2171 err = (err_flush != NO_ERROR) ? err_flush : err;
2172 }
Aravind Akella70018042014-04-07 22:52:37 +00002173 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07002174 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07002175}
Aravind Akella70018042014-04-07 22:52:37 +00002176
Svetoslavb412f6e2015-04-29 16:50:41 -07002177bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
2178 const String16& opPackageName) {
Brian Duddie4a4d0462022-05-09 16:49:49 -07002179 // Special case for Head Tracker sensor type: currently restricted to system usage only, unless
2180 // the restriction is specially lifted for testing
2181 if (sensor.getType() == SENSOR_TYPE_HEAD_TRACKER &&
2182 !isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
2183 if (!mHtRestricted) {
2184 ALOGI("Permitting access to HT sensor type outside system (%s)",
2185 String8(opPackageName).string());
2186 } else {
2187 ALOGW("%s %s a sensor (%s) as a non-system client", String8(opPackageName).string(),
2188 operation, sensor.getName().string());
2189 return false;
2190 }
2191 }
2192
Brian Stack793f4642019-04-18 17:21:34 -07002193 // Check if a permission is required for this sensor
2194 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00002195 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07002196 }
2197
Brian Stack793f4642019-04-18 17:21:34 -07002198 const int32_t opCode = sensor.getRequiredAppOp();
Brian Duddie457e6392020-06-19 11:38:29 -07002199 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07002200
Brian Stack793f4642019-04-18 17:21:34 -07002201 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07002202 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
2203 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
2204 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
2205 // Allow access to step sensors if the application targets pre-Q, which is before the
2206 // requirement to hold the AR permission to access Step Counter and Step Detector events
2207 // was introduced.
2208 canAccess = true;
2209 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07002210 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002211 if (opCode >= 0) {
2212 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
2213 IPCThreadState::self()->getCallingUid(), opPackageName);
2214 canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
2215 } else {
Brian Stack793f4642019-04-18 17:21:34 -07002216 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07002217 }
Brian Stack793f4642019-04-18 17:21:34 -07002218 }
2219
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002220 if (!canAccess) {
Brian Duddie457e6392020-06-19 11:38:29 -07002221 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
2222 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07002223 }
2224
2225 return canAccess;
2226}
2227
2228bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07002229 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07002230 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07002231
2232 // Runtime permissions can't use the cache as they may change.
2233 if (sensor.isRequiredPermissionRuntime()) {
2234 hasPermission = checkPermission(String16(requiredPermission),
matthuang65794462022-03-24 16:02:57 +08002235 IPCThreadState::self()->getCallingPid(),
2236 IPCThreadState::self()->getCallingUid(),
2237 /*logPermissionFailure=*/ false);
Aravind Akella70018042014-04-07 22:52:37 +00002238 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002239 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
2240 }
Brian Stack793f4642019-04-18 17:21:34 -07002241 return hasPermission;
2242}
Svetoslavb412f6e2015-04-29 16:50:41 -07002243
Brian Stack793f4642019-04-18 17:21:34 -07002244int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Anthony Stange07eb4212020-08-28 14:50:28 -04002245 // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
2246 // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
2247 // give it elevated privileges.
2248 if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
2249 return -1;
2250 }
2251
Brian Stack793f4642019-04-18 17:21:34 -07002252 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2253 int targetSdkVersion = -1;
2254 auto entry = sPackageTargetVersion.find(opPackageName);
2255 if (entry != sPackageTargetVersion.end()) {
2256 targetSdkVersion = entry->second;
2257 } else {
2258 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2259 if (binder != nullptr) {
2260 sp<content::pm::IPackageManagerNative> packageManager =
2261 interface_cast<content::pm::IPackageManagerNative>(binder);
2262 if (packageManager != nullptr) {
2263 binder::Status status = packageManager->getTargetSdkVersionForPackage(
2264 opPackageName, &targetSdkVersion);
2265 if (!status.isOk()) {
2266 targetSdkVersion = -1;
2267 }
2268 }
Svetoslavb412f6e2015-04-29 16:50:41 -07002269 }
Brian Stack793f4642019-04-18 17:21:34 -07002270 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07002271 }
Brian Stack793f4642019-04-18 17:21:34 -07002272 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00002273}
2274
Brian Duddie0d4ac562022-05-23 17:47:50 -07002275void SensorService::resetTargetSdkVersionCache(const String16& opPackageName) {
2276 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2277 auto iter = sPackageTargetVersion.find(opPackageName);
2278 if (iter != sPackageTargetVersion.end()) {
2279 sPackageTargetVersion.erase(iter);
2280 }
2281}
2282
Anthony Stangec1608152023-01-06 21:14:46 +00002283bool SensorService::getTargetOperatingMode(const std::string &inputString, Mode *targetModeOut) {
2284 if (inputString == std::string("restrict")) {
2285 *targetModeOut = RESTRICTED;
2286 return true;
2287 }
2288 if (inputString == std::string("enable")) {
2289 *targetModeOut = NORMAL;
2290 return true;
2291 }
2292 if (inputString == std::string("data_injection")) {
2293 *targetModeOut = DATA_INJECTION;
2294 return true;
2295 }
2296 if (inputString == std::string("replay_data_injection")) {
2297 *targetModeOut = REPLAY_DATA_INJECTION;
2298 return true;
2299 }
2300 return false;
2301}
2302
2303status_t SensorService::changeOperatingMode(const Vector<String16>& args,
2304 Mode targetOperatingMode) {
2305 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2306 SensorDevice& dev(SensorDevice::getInstance());
2307 if (mCurrentOperatingMode == targetOperatingMode) {
2308 return NO_ERROR;
2309 }
2310 if (targetOperatingMode != NORMAL && args.size() < 2) {
2311 return INVALID_OPERATION;
2312 }
2313 switch (targetOperatingMode) {
2314 case NORMAL:
2315 // If currently in restricted mode, reset back to NORMAL mode else ignore.
2316 if (mCurrentOperatingMode == RESTRICTED) {
2317 mCurrentOperatingMode = NORMAL;
2318 // enable sensors and recover all sensor direct report
2319 enableAllSensorsLocked(&connLock);
2320 }
2321 if (mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
2322 dev.disableAllSensors();
2323 }
2324 if (mCurrentOperatingMode == DATA_INJECTION ||
2325 mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
2326 resetToNormalModeLocked();
2327 }
2328 mAllowListedPackage.clear();
2329 return status_t(NO_ERROR);
2330 case RESTRICTED:
2331 // If in any mode other than normal, ignore.
2332 if (mCurrentOperatingMode != NORMAL) {
2333 return INVALID_OPERATION;
2334 }
2335
2336 mCurrentOperatingMode = RESTRICTED;
2337 // temporarily stop all sensor direct report and disable sensors
2338 disableAllSensorsLocked(&connLock);
2339 mAllowListedPackage.setTo(String8(args[1]));
2340 return status_t(NO_ERROR);
2341 case REPLAY_DATA_INJECTION:
2342 if (SensorServiceUtil::isUserBuild()) {
2343 return INVALID_OPERATION;
2344 }
2345 FALLTHROUGH_INTENDED;
2346 case DATA_INJECTION:
2347 if (mCurrentOperatingMode == NORMAL) {
2348 dev.disableAllSensors();
2349 // Always use DATA_INJECTION here since this value goes to the HAL and the HAL
2350 // doesn't have an understanding of replay vs. normal data injection.
2351 status_t err = dev.setMode(DATA_INJECTION);
2352 if (err == NO_ERROR) {
2353 mCurrentOperatingMode = targetOperatingMode;
2354 }
2355 if (err != NO_ERROR || targetOperatingMode == REPLAY_DATA_INJECTION) {
2356 // Re-enable sensors.
2357 dev.enableAllSensors();
2358 }
2359 mAllowListedPackage.setTo(String8(args[1]));
2360 return NO_ERROR;
2361 } else {
2362 // Transition to data injection mode supported only from NORMAL mode.
2363 return INVALID_OPERATION;
2364 }
2365 break;
2366 default:
2367 break;
2368 }
2369 return NO_ERROR;
2370}
2371
Aravind Akella9a844cf2014-02-11 18:58:52 -08002372void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07002373 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2374 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08002375}
2376
Brian Duddie967ce172019-06-10 11:08:27 -07002377void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002378 if (!mWakeLockAcquired) {
2379 return;
2380 }
2381 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07002382 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
2383 if (connection->needsWakeLock()) {
2384 releaseLock = false;
2385 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08002386 }
2387 }
2388 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07002389 setWakeLockAcquiredLocked(false);
2390 }
2391}
2392
2393void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
2394 Mutex::Autolock _l(mLock);
2395 connection->writeToSocketFromCache();
2396 if (connection->needsWakeLock()) {
2397 setWakeLockAcquiredLocked(true);
2398 }
2399}
2400
Anthony Stangecd01ec12023-01-06 18:35:13 +00002401bool SensorService::isAllowListedPackage(const String8& packageName) {
2402 return (packageName.contains(mAllowListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08002403}
2404
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002405bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08002406 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07002407 String8 package(opPackageName);
Anthony Stangecd01ec12023-01-06 18:35:13 +00002408 return !isAllowListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07002409 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002410 return false;
Peng Xue36e3472016-11-03 11:57:10 -07002411}
2412
Svet Ganove752a5c2018-01-15 17:14:20 -08002413void SensorService::UidPolicy::registerSelf() {
2414 ActivityManager am;
2415 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
2416 | ActivityManager::UID_OBSERVER_IDLE
2417 | ActivityManager::UID_OBSERVER_ACTIVE,
2418 ActivityManager::PROCESS_STATE_UNKNOWN,
2419 String16("android"));
2420}
2421
2422void SensorService::UidPolicy::unregisterSelf() {
2423 ActivityManager am;
2424 am.unregisterUidObserver(this);
2425}
2426
2427void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
2428 onUidIdle(uid, disabled);
2429}
2430
2431void SensorService::UidPolicy::onUidActive(uid_t uid) {
2432 {
2433 Mutex::Autolock _l(mUidLock);
2434 mActiveUids.insert(uid);
2435 }
2436 sp<SensorService> service = mService.promote();
2437 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002438 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002439 }
2440}
2441
2442void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
2443 bool deleted = false;
2444 {
2445 Mutex::Autolock _l(mUidLock);
2446 if (mActiveUids.erase(uid) > 0) {
2447 deleted = true;
2448 }
2449 }
2450 if (deleted) {
2451 sp<SensorService> service = mService.promote();
2452 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002453 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002454 }
2455 }
2456}
2457
2458void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
2459 updateOverrideUid(uid, active, true);
2460}
2461
2462void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
2463 updateOverrideUid(uid, false, false);
2464}
2465
2466void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
2467 bool wasActive = false;
2468 bool isActive = false;
2469 {
2470 Mutex::Autolock _l(mUidLock);
2471 wasActive = isUidActiveLocked(uid);
2472 mOverrideUids.erase(uid);
2473 if (insert) {
2474 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2475 }
2476 isActive = isUidActiveLocked(uid);
2477 }
2478 if (wasActive != isActive) {
2479 sp<SensorService> service = mService.promote();
2480 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002481 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002482 }
2483 }
2484}
2485
2486bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2487 // Non-app UIDs are considered always active
2488 if (uid < FIRST_APPLICATION_UID) {
2489 return true;
2490 }
2491 Mutex::Autolock _l(mUidLock);
2492 return isUidActiveLocked(uid);
2493}
2494
2495bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2496 // Non-app UIDs are considered always active
2497 if (uid < FIRST_APPLICATION_UID) {
2498 return true;
2499 }
2500 auto it = mOverrideUids.find(uid);
2501 if (it != mOverrideUids.end()) {
2502 return it->second;
2503 }
2504 return mActiveUids.find(uid) != mActiveUids.end();
2505}
2506
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002507bool SensorService::isUidActive(uid_t uid) {
2508 return mUidPolicy->isUidActive(uid);
2509}
2510
Anh Phamaf91a912021-02-10 14:10:53 +01002511bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2512 int targetSdk = getTargetSdkVersion(opPackageName);
Anh Phama5538232021-06-23 08:41:11 +02002513 bool hasSamplingRatePermission = checkPermission(sAccessHighSensorSamplingRatePermission,
2514 IPCThreadState::self()->getCallingPid(),
matthuang65794462022-03-24 16:02:57 +08002515 IPCThreadState::self()->getCallingUid(),
2516 /*logPermissionFailure=*/ false);
Anh Phamaf91a912021-02-10 14:10:53 +01002517 if (targetSdk < __ANDROID_API_S__ ||
2518 (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2519 return false;
2520 }
2521 return true;
2522}
2523
Anh Pham3dae77f2021-06-11 16:24:37 +02002524/**
2525 * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS
2526 * permission.
2527 *
2528 * This needs to be kept in sync with the list defined on the Java side
2529 * in frameworks/base/core/java/android/hardware/SystemSensorManager.java
2530 */
Anh Phamaf91a912021-02-10 14:10:53 +01002531bool SensorService::isSensorInCappedSet(int sensorType) {
2532 return (sensorType == SENSOR_TYPE_ACCELEROMETER
2533 || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2534 || sensorType == SENSOR_TYPE_GYROSCOPE
2535 || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2536 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2537 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2538}
2539
2540status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2541 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002542 if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2543 return OK;
2544 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002545 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002546 if (shouldCapBasedOnPermission) {
2547 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2548 if (isPackageDebuggable(opPackageName)) {
2549 return PERMISSION_DENIED;
2550 }
2551 return OK;
2552 }
Evan Severson4c197852022-01-27 10:44:27 -08002553 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002554 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2555 return OK;
2556 }
Anh Phamaf91a912021-02-10 14:10:53 +01002557 return OK;
2558}
2559
2560status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2561 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002562 if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2563 return OK;
2564 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002565 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002566 if (shouldCapBasedOnPermission) {
2567 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2568 if (isPackageDebuggable(opPackageName)) {
2569 return PERMISSION_DENIED;
2570 }
2571 return OK;
2572 }
Evan Severson4c197852022-01-27 10:44:27 -08002573 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002574 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2575 return OK;
2576 }
Anh Phamaf91a912021-02-10 14:10:53 +01002577 return OK;
2578}
2579
Michael Groover5e1f60b2018-12-04 22:34:29 -08002580void SensorService::SensorPrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002581 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002582 SensorPrivacyManager spm;
2583 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2584 spm.addSensorPrivacyListener(this);
2585}
2586
2587void SensorService::SensorPrivacyPolicy::unregisterSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002588 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002589 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002590 spm.removeSensorPrivacyListener(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -08002591}
2592
2593bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2594 return mSensorPrivacyEnabled;
2595}
2596
Evan Severson4c197852022-01-27 10:44:27 -08002597binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2598 int sensor __unused, bool enabled) {
Michael Groover5e1f60b2018-12-04 22:34:29 -08002599 mSensorPrivacyEnabled = enabled;
2600 sp<SensorService> service = mService.promote();
Anh Pham5198c992021-02-10 14:15:30 +01002601
Michael Groover5e1f60b2018-12-04 22:34:29 -08002602 if (service != nullptr) {
Evan Severson4c197852022-01-27 10:44:27 -08002603 if (enabled) {
2604 service->disableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002605 } else {
Evan Severson4c197852022-01-27 10:44:27 -08002606 service->enableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002607 }
2608 }
2609 return binder::Status::ok();
2610}
Brian Duddie967ce172019-06-10 11:08:27 -07002611
Evan Severson4c197852022-01-27 10:44:27 -08002612void SensorService::MicrophonePrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002613 AutoCallerClear acc;
Anh Pham5198c992021-02-10 14:15:30 +01002614 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002615 mSensorPrivacyEnabled =
2616 spm.isToggleSensorPrivacyEnabled(
2617 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
2618 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE)
2619 || spm.isToggleSensorPrivacyEnabled(
2620 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE,
2621 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE);
2622 spm.addToggleSensorPrivacyListener(this);
Anh Pham5198c992021-02-10 14:15:30 +01002623}
2624
Evan Severson4c197852022-01-27 10:44:27 -08002625void SensorService::MicrophonePrivacyPolicy::unregisterSelf() {
2626 AutoCallerClear acc;
2627 SensorPrivacyManager spm;
2628 spm.removeToggleSensorPrivacyListener(this);
2629}
2630
2631binder::Status SensorService::MicrophonePrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2632 int sensor, bool enabled) {
2633 if (sensor != SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE) {
2634 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002635 }
Evan Severson4c197852022-01-27 10:44:27 -08002636 mSensorPrivacyEnabled = enabled;
2637 sp<SensorService> service = mService.promote();
2638
2639 if (service != nullptr) {
2640 if (enabled) {
2641 service->capRates();
2642 } else {
2643 service->uncapRates();
2644 }
2645 }
2646 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002647}
2648
Brian Duddie967ce172019-06-10 11:08:27 -07002649SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2650 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2651 : mConnectionHolder(holder), mAutolock(mutex) {}
2652
2653template<typename ConnectionType>
2654const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2655 const SortedVector<wp<ConnectionType>>& connectionList,
2656 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2657 referenceHolder->emplace_back();
2658 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2659 for (const wp<ConnectionType>& weakConnection : connectionList){
2660 sp<ConnectionType> connection = weakConnection.promote();
2661 if (connection != nullptr) {
2662 connections.push_back(std::move(connection));
2663 }
2664 }
2665 return connections;
2666}
2667
2668const std::vector<sp<SensorService::SensorEventConnection>>&
2669 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2670 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2671 &mReferencedActiveConnections);
2672}
2673
2674const std::vector<sp<SensorService::SensorDirectConnection>>&
2675 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2676 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2677 &mReferencedDirectConnections);
2678}
2679
2680void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2681 const sp<SensorService::SensorEventConnection>& connection) {
2682 if (mActiveConnections.indexOf(connection) < 0) {
2683 mActiveConnections.add(connection);
2684 }
2685}
2686
2687void SensorService::SensorConnectionHolder::removeEventConnection(
2688 const wp<SensorService::SensorEventConnection>& connection) {
2689 mActiveConnections.remove(connection);
2690}
2691
2692void SensorService::SensorConnectionHolder::addDirectConnection(
2693 const sp<SensorService::SensorDirectConnection>& connection) {
2694 mDirectConnections.add(connection);
2695}
2696
2697void SensorService::SensorConnectionHolder::removeDirectConnection(
2698 const wp<SensorService::SensorDirectConnection>& connection) {
2699 mDirectConnections.remove(connection);
2700}
2701
2702SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2703 return ConnectionSafeAutolock(*this, mutex);
2704}
2705
Anh Phamaf91a912021-02-10 14:10:53 +01002706bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2707 bool debugMode = false;
2708 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2709 if (binder != nullptr) {
2710 sp<content::pm::IPackageManagerNative> packageManager =
2711 interface_cast<content::pm::IPackageManagerNative>(binder);
2712 if (packageManager != nullptr) {
2713 binder::Status status = packageManager->isPackageDebuggable(
2714 opPackageName, &debugMode);
2715 }
2716 }
2717 return debugMode;
2718}
Brian Duddie967ce172019-06-10 11:08:27 -07002719} // namespace android