blob: 70ca7025d4c53a37c82587ed9280ab9a86a07c37 [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 */
Rocky Fangbeb0dff2023-12-15 01:59:46 +000016#include "SensorService.h"
17
Vladimir Komsiyski29d2afd2022-12-06 13:24:10 +010018#include <aidl/android/hardware/sensors/ISensors.h>
Anh Phamaf91a912021-02-10 14:10:53 +010019#include <android-base/strings.h>
Brian Stack793f4642019-04-18 17:21:34 -070020#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080021#include <android/util/ProtoOutputStream.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080022#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070023#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070024#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070025#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080026#include <binder/PermissionController.h>
Rocky Fangbeb0dff2023-12-15 01:59:46 +000027#include <com_android_frameworks_sensorservice_flags.h>
Peng Xue36e3472016-11-03 11:57:10 -070028#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080029#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070030#include <cutils/properties.h>
Brian Duddie0a4cebb2022-08-25 19:20:18 +000031#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070032#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070033#include <hardware_legacy/power.h>
Rocky Fangbeb0dff2023-12-15 01:59:46 +000034#include <inttypes.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080035#include <log/log.h>
Rocky Fangbeb0dff2023-12-15 01:59:46 +000036#include <math.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070037#include <openssl/digest.h>
38#include <openssl/hmac.h>
39#include <openssl/rand.h>
Rocky Fangbeb0dff2023-12-15 01:59:46 +000040#include <private/android_filesystem_config.h>
41#include <sched.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070042#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080043#include <sensorprivacy/SensorPrivacyManager.h>
Rocky Fangbeb0dff2023-12-15 01:59:46 +000044#include <stdint.h>
45#include <sys/socket.h>
46#include <sys/stat.h>
47#include <sys/types.h>
48#include <unistd.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070049#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070050
Rocky Fangbeb0dff2023-12-15 01:59:46 +000051#include <condition_variable>
52#include <ctime>
53#include <future>
54#include <mutex>
55#include <string>
56
Mathias Agopian787ac1b2012-09-18 18:49:18 -070057#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070058#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080059#include "GravitySensor.h"
Tyler Trephanc7b92632021-07-21 10:39:38 -070060#include "LimitedAxesImuSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080061#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070062#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080063#include "RotationVectorSensor.h"
Peng Xue36e3472016-11-03 11:57:10 -070064#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080065#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080066#include "SensorEventConnection.h"
Rocky Fangbeb0dff2023-12-15 01:59:46 +000067#include "SensorFusion.h"
68#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080069#include "SensorRecord.h"
70#include "SensorRegistrationInfo.h"
Anthony Stange9bb16702023-01-03 22:42:31 +000071#include "SensorServiceUtils.h"
Peng Xueb4d6282015-12-10 18:02:41 -080072
Andrew Lehmer3a602572021-03-25 15:19:56 -070073using namespace std::chrono_literals;
Rocky Fangbeb0dff2023-12-15 01:59:46 +000074namespace sensorservice_flags = com::android::frameworks::sensorservice::flags;
Andrew Lehmer3a602572021-03-25 15:19:56 -070075
Mathias Agopianfc328812010-07-14 23:41:37 -070076namespace android {
77// ---------------------------------------------------------------------------
78
Mathias Agopian33015422011-05-27 18:18:13 -070079/*
80 * Notes:
81 *
82 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070083 * - run mag sensor from time to time to force calibration
84 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
85 *
86 */
87
Aravind Akella8ef3c892015-07-10 11:24:28 -070088const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070089uint8_t SensorService::sHmacGlobalKey[128] = {};
90bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070091std::map<String16, int> SensorService::sPackageTargetVersion;
92Mutex SensorService::sPackageTargetVersionLock;
Anthony Stange07eb4212020-08-28 14:50:28 -040093String16 SensorService::sSensorInterfaceDescriptorPrefix =
Rocky Fang47a7a4a2023-12-11 22:30:30 +000094 String16("android.frameworks.sensorservice");
Brian Stack793f4642019-04-18 17:21:34 -070095AppOpsManager SensorService::sAppOpsManager;
Andrew Lehmer3a602572021-03-25 15:19:56 -070096std::atomic_uint64_t SensorService::curProxCallbackSeq(0);
97std::atomic_uint64_t SensorService::completedCallbackSeq(0);
Greg Kaiser53ca2e02016-06-21 16:11:14 -070098
99#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
100#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -0700101#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700102
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700103// Permissions.
Anh Phamaf91a912021-02-10 14:10:53 +0100104static const String16 sAccessHighSensorSamplingRatePermission(
105 "android.permission.HIGH_SAMPLING_RATE_SENSORS");
Peng Xudd5c5cb2017-03-16 17:39:43 -0700106static const String16 sDumpPermission("android.permission.DUMP");
107static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -0800108static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700109
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200110namespace {
111
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200112int32_t nextRuntimeSensorHandle() {
Vladimir Komsiyski29d2afd2022-12-06 13:24:10 +0100113 using ::aidl::android::hardware::sensors::ISensors;
114 static int32_t nextHandle = ISensors::RUNTIME_SENSORS_HANDLE_BASE;
115 if (nextHandle == ISensors::RUNTIME_SENSORS_HANDLE_END) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200116 return -1;
117 }
118 return nextHandle++;
119}
120
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100121class RuntimeSensorCallbackProxy : public RuntimeSensor::SensorCallback {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200122 public:
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100123 RuntimeSensorCallbackProxy(sp<SensorService::RuntimeSensorCallback> callback)
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200124 : mCallback(std::move(callback)) {}
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100125 status_t onConfigurationChanged(int handle, bool enabled, int64_t samplingPeriodNs,
126 int64_t batchReportLatencyNs) override {
127 return mCallback->onConfigurationChanged(handle, enabled, samplingPeriodNs,
128 batchReportLatencyNs);
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200129 }
130 private:
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100131 sp<SensorService::RuntimeSensorCallback> mCallback;
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200132};
133
134} // namespace
135
Tyler Trephanc7b92632021-07-21 10:39:38 -0700136static bool isAutomotive() {
137 sp<IServiceManager> serviceManager = defaultServiceManager();
138 if (serviceManager.get() == nullptr) {
139 ALOGE("%s: unable to access native ServiceManager", __func__);
140 return false;
141 }
142
143 sp<content::pm::IPackageManagerNative> packageManager;
144 sp<IBinder> binder = serviceManager->waitForService(String16("package_native"));
145 packageManager = interface_cast<content::pm::IPackageManagerNative>(binder);
146 if (packageManager == nullptr) {
147 ALOGE("%s: unable to access native PackageManager", __func__);
148 return false;
149 }
150
151 bool isAutomotive = false;
152 binder::Status status =
153 packageManager->hasSystemFeature(String16("android.hardware.type.automotive"), 0,
154 &isAutomotive);
155 if (!status.isOk()) {
156 ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str());
157 return false;
158 }
159
160 return isAutomotive;
161}
162
Mathias Agopianfc328812010-07-14 23:41:37 -0700163SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -0700164 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700165 mWakeLockAcquired(false), mLastReportedProxIsActive(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +0900166 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800167 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Evan Severson4c197852022-01-27 10:44:27 -0800168 mMicSensorPrivacyPolicy = new MicrophonePrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700169}
170
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200171int SensorService::registerRuntimeSensor(
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100172 const sensor_t& sensor, int deviceId, sp<RuntimeSensorCallback> callback) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200173 int handle = 0;
174 while (handle == 0 || !mSensors.isNewHandle(handle)) {
175 handle = nextRuntimeSensorHandle();
176 if (handle < 0) {
177 // Ran out of the dedicated range for runtime sensors.
178 return handle;
179 }
180 }
181
182 ALOGI("Registering runtime sensor handle 0x%x, type %d, name %s",
183 handle, sensor.type, sensor.name);
184
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100185 sp<RuntimeSensor::SensorCallback> runtimeSensorCallback(
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100186 new RuntimeSensorCallbackProxy(callback));
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200187 sensor_t runtimeSensor = sensor;
188 // force the handle to be consistent
189 runtimeSensor.handle = handle;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100190 auto si = std::make_shared<RuntimeSensor>(runtimeSensor, std::move(runtimeSensorCallback));
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200191
192 Mutex::Autolock _l(mLock);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100193 if (!registerSensor(std::move(si), /* isDebug= */ false, /* isVirtual= */ false, deviceId)) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200194 // The registration was unsuccessful.
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100195 return mSensors.getNonSensor().getHandle();
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200196 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100197
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100198 if (mRuntimeSensorCallbacks.find(deviceId) == mRuntimeSensorCallbacks.end()) {
199 mRuntimeSensorCallbacks.emplace(deviceId, callback);
200 }
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +0200201
202 if (mRuntimeSensorHandler == nullptr) {
203 mRuntimeSensorEventBuffer =
204 new sensors_event_t[SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT];
205 mRuntimeSensorHandler = new RuntimeSensorHandler(this);
206 // Use PRIORITY_URGENT_DISPLAY as the injected sensor events should be dispatched as soon as
207 // possible, and also for consistency within the SensorService.
208 mRuntimeSensorHandler->run("RuntimeSensorHandler", PRIORITY_URGENT_DISPLAY);
209 }
210
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200211 return handle;
212}
213
214status_t SensorService::unregisterRuntimeSensor(int handle) {
215 ALOGI("Unregistering runtime sensor handle 0x%x disconnected", handle);
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100216 int deviceId = getDeviceIdFromHandle(handle);
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200217 {
218 Mutex::Autolock _l(mLock);
219 if (!unregisterDynamicSensorLocked(handle)) {
220 ALOGE("Runtime sensor release error.");
221 return UNKNOWN_ERROR;
222 }
223 }
224
225 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
226 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
227 connection->removeSensor(handle);
228 }
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100229
230 // If this was the last sensor for this device, remove its callback.
231 bool deviceHasSensors = false;
232 mSensors.forEachEntry(
233 [&deviceId, &deviceHasSensors] (const SensorServiceUtil::SensorList::Entry& e) -> bool {
234 if (e.deviceId == deviceId) {
235 deviceHasSensors = true;
236 return false; // stop iterating
237 }
238 return true;
239 });
240 if (!deviceHasSensors) {
241 mRuntimeSensorCallbacks.erase(deviceId);
242 }
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200243 return OK;
244}
245
246status_t SensorService::sendRuntimeSensorEvent(const sensors_event_t& event) {
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +0200247 std::unique_lock<std::mutex> lock(mRutimeSensorThreadMutex);
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200248 mRuntimeSensorEventQueue.push(event);
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +0200249 mRuntimeSensorsCv.notify_all();
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200250 return OK;
251}
252
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700253bool SensorService::initializeHmacKey() {
254 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
255 if (fd != -1) {
256 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
257 close(fd);
258 if (result == sizeof(sHmacGlobalKey)) {
259 return true;
260 }
261 ALOGW("Unable to read HMAC key; generating new one.");
262 }
263
264 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
265 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
266 return false;
267 }
268
269 // We need to make sure this is only readable to us.
270 bool wroteKey = false;
271 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
272 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
273 S_IRUSR|S_IWUSR);
274 if (fd != -1) {
275 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
276 close(fd);
277 wroteKey = (result == sizeof(sHmacGlobalKey));
278 }
279 if (wroteKey) {
280 ALOGI("Generated new HMAC key.");
281 } else {
282 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
283 "after reboot.");
284 }
285 // Even if we failed to write the key we return true, because we did
286 // initialize the HMAC key.
287 return true;
288}
289
Peng Xu98d30f62016-08-01 18:12:11 -0700290// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
291void SensorService::enableSchedFifoMode() {
292 struct sched_param param = {0};
293 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
294 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
295 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
296 }
297}
298
Peng Xu47e96012016-03-28 17:55:56 -0700299void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000300 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800301 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700302
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700303 sHmacGlobalKeyIsValid = initializeHmacKey();
304
Mathias Agopianf001c922010-11-11 17:58:51 -0800305 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800306 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700307 ssize_t count = dev.getSensorList(&list);
308 if (count > 0) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700309 bool hasGyro = false, hasAccel = false, hasMag = false;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700310 bool hasGyroUncalibrated = false;
311 bool hasAccelUncalibrated = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700312 uint32_t virtualSensorsNeeds =
313 (1<<SENSOR_TYPE_GRAVITY) |
314 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700315 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
316 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
317 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700318
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700319 for (ssize_t i=0 ; i<count ; i++) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700320 bool useThisSensor = true;
Peng Xuf66684a2015-07-23 11:41:53 -0700321
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700322 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700323 case SENSOR_TYPE_ACCELEROMETER:
324 hasAccel = true;
325 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700326 case SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED:
327 hasAccelUncalibrated = true;
328 break;
Aravind Akellaf5047892015-07-20 17:29:33 -0700329 case SENSOR_TYPE_MAGNETIC_FIELD:
330 hasMag = true;
331 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700332 case SENSOR_TYPE_GYROSCOPE:
333 hasGyro = true;
334 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700335 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
336 hasGyroUncalibrated = true;
337 break;
Rocky Fangbeb0dff2023-12-15 01:59:46 +0000338 case SENSOR_TYPE_DYNAMIC_SENSOR_META:
339 if (sensorservice_flags::dynamic_sensor_hal_reconnect_handling()) {
340 mDynamicMetaSensorHandle = list[i].handle;
341 }
342 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700343 case SENSOR_TYPE_GRAVITY:
344 case SENSOR_TYPE_LINEAR_ACCELERATION:
345 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700346 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
347 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
348 if (IGNORE_HARDWARE_FUSION) {
349 useThisSensor = false;
350 } else {
351 virtualSensorsNeeds &= ~(1<<list[i].type);
352 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700353 break;
Arthur Ishiguro2fd90a72021-11-12 17:24:41 +0000354 default:
355 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700356 }
Peng Xuf66684a2015-07-23 11:41:53 -0700357 if (useThisSensor) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700358 if (list[i].type == SENSOR_TYPE_PROXIMITY) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100359 auto s = std::make_shared<ProximitySensor>(list[i], *this);
360 const int handle = s->getSensor().getHandle();
361 if (registerSensor(std::move(s))) {
362 mProxSensorHandles.push_back(handle);
363 }
Andrew Lehmer3a602572021-03-25 15:19:56 -0700364 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100365 registerSensor(std::make_shared<HardwareSensor>(list[i]));
Andrew Lehmer3a602572021-03-25 15:19:56 -0700366 }
Peng Xuf66684a2015-07-23 11:41:53 -0700367 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700368 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700369
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700370 // it's safe to instantiate the SensorFusion object here
371 // (it wants to be instantiated after h/w sensors have been
372 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700373 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700374
Tyler Trephanc7b92632021-07-21 10:39:38 -0700375 if ((hasGyro || hasGyroUncalibrated) && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700376 // Add Android virtual sensors if they're not already
377 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700378 bool needRotationVector =
379 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100380 registerVirtualSensor(std::make_shared<RotationVectorSensor>(),
381 /* isDebug= */ !needRotationVector);
382 registerVirtualSensor(std::make_shared<OrientationSensor>(),
383 /* isDebug= */ !needRotationVector);
Mathias Agopian03193062013-05-10 19:32:39 -0700384
Peng Xu0cc8f802016-04-05 23:46:03 -0700385 // virtual debugging sensors are not for user
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100386 registerVirtualSensor(std::make_shared<CorrectedGyroSensor>(list, count),
387 /* isDebug= */ true);
388 registerVirtualSensor(std::make_shared<GyroDriftSensor>(), /* isDebug= */ true);
Mathias Agopian33264862012-06-28 19:46:54 -0700389 }
390
Tyler Trephanc7b92632021-07-21 10:39:38 -0700391 if (hasAccel && (hasGyro || hasGyroUncalibrated)) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700392 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100393 registerVirtualSensor(std::make_shared<GravitySensor>(list, count),
394 /* isDebug= */ !needGravitySensor);
Peng Xuf66684a2015-07-23 11:41:53 -0700395
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800396 bool needLinearAcceleration =
397 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100398 registerVirtualSensor(std::make_shared<LinearAccelerationSensor>(list, count),
399 /* isDebug= */ !needLinearAcceleration);
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800400
Peng Xu0cc8f802016-04-05 23:46:03 -0700401 bool needGameRotationVector =
402 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100403 registerVirtualSensor(std::make_shared<GameRotationVectorSensor>(),
404 /* isDebug= */ !needGameRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700405 }
406
407 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700408 bool needGeoMagRotationVector =
409 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100410 registerVirtualSensor(std::make_shared<GeoMagRotationVectorSensor>(),
411 /* isDebug= */ !needGeoMagRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700412 }
413
Tyler Trephanc7b92632021-07-21 10:39:38 -0700414 if (isAutomotive()) {
415 if (hasAccel) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100416 registerVirtualSensor(
417 std::make_shared<LimitedAxesImuSensor>(
418 list, count, SENSOR_TYPE_ACCELEROMETER));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700419 }
420
421 if (hasGyro) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100422 registerVirtualSensor(
423 std::make_shared<LimitedAxesImuSensor>(
424 list, count, SENSOR_TYPE_GYROSCOPE));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700425 }
426
427 if (hasAccelUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100428 registerVirtualSensor(
429 std::make_shared<LimitedAxesImuSensor>(
430 list, count, SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700431 }
432
433 if (hasGyroUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100434 registerVirtualSensor(
435 std::make_shared<LimitedAxesImuSensor>(
436 list, count, SENSOR_TYPE_GYROSCOPE_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700437 }
438 }
439
Aravind Akella5466c3d2014-08-22 16:11:10 -0700440 // Check if the device really supports batching by looking at the FIFO event
441 // counts for each sensor.
442 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700443 mSensors.forEachSensor(
444 [&batchingSupported] (const Sensor& s) -> bool {
445 if (s.getFifoMaxEventCount() > 0) {
446 batchingSupported = true;
447 }
448 return !batchingSupported;
449 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700450
451 if (batchingSupported) {
452 // Increase socket buffer size to a max of 100 KB for batching capabilities.
453 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
454 } else {
455 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
456 }
457
458 // Compare the socketBufferSize value against the system limits and limit
459 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700460 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
461 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700462 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700463 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700464 size_t maxSystemSocketBufferSize;
465 sscanf(line, "%zu", &maxSystemSocketBufferSize);
466 if (mSocketBufferSize > maxSystemSocketBufferSize) {
467 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700468 }
469 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700470 if (fp) {
471 fclose(fp);
472 }
473
Aravind Akella9a844cf2014-02-11 18:58:52 -0800474 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700475 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700476 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
477 mSensorEventBuffer = new sensors_event_t[minBufferSize];
478 mSensorEventScratch = new sensors_event_t[minBufferSize];
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +0200479 mRuntimeSensorEventBuffer = nullptr;
Peng Xueb059472016-08-12 16:39:44 -0700480 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700481 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700482
Aravind Akella18d6d512015-06-18 14:18:28 -0700483 mNextSensorRegIndex = 0;
484 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
485 mLastNSensorRegistrations.push();
486 }
487
488 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700489 mAckReceiver = new SensorEventAckReceiver(this);
490 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700491 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700492
493 // priority can only be changed after run
494 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800495
496 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800497 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800498
499 // Start watching sensor privacy changes
500 mSensorPrivacyPolicy->registerSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800501
502 // Start watching mic sensor privacy changes
503 mMicSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800504 }
505 }
506}
507
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700508void SensorService::onUidStateChanged(uid_t uid, UidState state) {
509 SensorDevice& dev(SensorDevice::getInstance());
510
Brian Duddie967ce172019-06-10 11:08:27 -0700511 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700512 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700513 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700514 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700515 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700516 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700517
518 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
519 if (conn->getUid() == uid) {
520 // Update sensor subscriptions if needed
521 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
522 conn->onSensorAccessChanged(hasAccess);
523 }
524 }
Chris Kuiper587ef9b2021-10-12 16:36:43 -0700525 checkAndReportProxStateChangeLocked();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700526}
527
528bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
529 Mutex::Autolock _l(mLock);
530 return hasSensorAccessLocked(uid, opPackageName);
531}
532
533bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
534 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
535 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700536}
537
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100538bool SensorService::registerSensor(std::shared_ptr<SensorInterface> s, bool isDebug, bool isVirtual,
539 int deviceId) {
540 const int handle = s->getSensor().getHandle();
541 const int type = s->getSensor().getType();
542 if (mSensors.add(handle, std::move(s), isDebug, isVirtual, deviceId)) {
Brian Stack4baa5be2018-09-18 14:03:13 -0700543 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100544 return true;
Peng Xu0cc8f802016-04-05 23:46:03 -0700545 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100546 LOG_FATAL("Failed to register sensor with handle %d", handle);
547 return false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700548 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800549}
550
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100551bool SensorService::registerDynamicSensorLocked(std::shared_ptr<SensorInterface> s, bool isDebug) {
552 return registerSensor(std::move(s), isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800553}
554
Peng Xu6a2d3a02015-12-21 12:00:23 -0800555bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700556 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800557
558 const auto i = mRecentEvent.find(handle);
559 if (i != mRecentEvent.end()) {
560 delete i->second;
561 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800562 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700563 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800564}
565
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100566bool SensorService::registerVirtualSensor(std::shared_ptr<SensorInterface> s, bool isDebug) {
567 return registerSensor(std::move(s), isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700568}
569
Peng Xu47e96012016-03-28 17:55:56 -0700570SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800571 for (auto && entry : mRecentEvent) {
572 delete entry.second;
573 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800574 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800575 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800576 mMicSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700577}
578
579status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700580 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700581 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800582 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700583 IPCThreadState::self()->getCallingPid(),
584 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700585 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700586 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700587 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800588 return INVALID_OPERATION;
589 }
Anthony Stangec1608152023-01-06 21:14:46 +0000590 if (args.size() > 0) {
591 Mode targetOperatingMode = NORMAL;
Tomasz Wasilczyk02fd95c2023-08-30 17:51:31 +0000592 std::string inputStringMode = String8(args[0]).c_str();
Anthony Stangec1608152023-01-06 21:14:46 +0000593 if (getTargetOperatingMode(inputStringMode, &targetOperatingMode)) {
594 status_t error = changeOperatingMode(args, targetOperatingMode);
595 // Dump the latest state only if no error was encountered.
596 if (error != NO_ERROR) {
597 return error;
598 }
Aravind Akella444f2672015-05-07 12:40:52 -0700599 }
Anthony Stangec1608152023-01-06 21:14:46 +0000600 }
Peng Xue36e3472016-11-03 11:57:10 -0700601
Anthony Stangec1608152023-01-06 21:14:46 +0000602 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
603 // Run the following logic if a transition isn't requested above based on the input
604 // argument parsing.
605 if (args.size() == 1 && args[0] == String16("--proto")) {
Mike Ma24743862020-01-29 00:36:55 -0800606 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700607 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700608 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700609 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700610 } else {
611 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700612 //
Brian Stack51498e62018-10-03 10:52:21 -0700613 timespec curTime;
614 clock_gettime(CLOCK_REALTIME, &curTime);
615 struct tm* timeinfo = localtime(&(curTime.tv_sec));
616 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
617 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800618 result.append("Sensor Device:\n");
619 result.append(SensorDevice::getInstance().dump().c_str());
620
621 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700622 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700623
Peng Xu6a2d3a02015-12-21 12:00:23 -0800624 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700625 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700626
Peng Xu0cc8f802016-04-05 23:46:03 -0700627 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800628 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100629 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
630 if (!i.second->isEmpty() && s != nullptr) {
Tomasz Wasilczyke50b2de2023-08-14 18:03:09 +0000631 if (privileged || s->getSensor().getRequiredPermission().empty()) {
Peng Xufba3c112016-09-08 12:36:59 -0700632 i.second->setFormat("normal");
633 } else {
634 i.second->setFormat("mask_data");
635 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800636 // if there is events and sensor does not need special permission.
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000637 result.appendFormat("%s: ", s->getSensor().getName().c_str());
Peng Xu6a2d3a02015-12-21 12:00:23 -0800638 result.append(i.second->dump().c_str());
639 }
640 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700641
Aravind Akella444f2672015-05-07 12:40:52 -0700642 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700643 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700644 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
645 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700646 if (dev.isSensorActive(handle)) {
647 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000648 getSensorName(handle).c_str(),
Brian Stackbce04d72019-03-21 10:54:10 -0700649 handle,
650 mActiveSensors.valueAt(i)->getNumConnections());
651 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700652 }
653
Andreas Gamped4036b62015-07-28 13:49:04 -0700654 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700655 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700656 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
657 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700658 result.appendFormat("Mode :");
659 switch(mCurrentOperatingMode) {
660 case NORMAL:
661 result.appendFormat(" NORMAL\n");
662 break;
663 case RESTRICTED:
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000664 result.appendFormat(" RESTRICTED : %s\n", mAllowListedPackage.c_str());
Aravind Akella444f2672015-05-07 12:40:52 -0700665 break;
666 case DATA_INJECTION:
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000667 result.appendFormat(" DATA_INJECTION : %s\n", mAllowListedPackage.c_str());
Anthony Stange9bb16702023-01-03 22:42:31 +0000668 break;
669 case REPLAY_DATA_INJECTION:
670 result.appendFormat(" REPLAY_DATA_INJECTION : %s\n",
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000671 mAllowListedPackage.c_str());
Anthony Stange9bb16702023-01-03 22:42:31 +0000672 break;
Mark Wheatley8f285d92023-07-07 20:07:18 +0000673 case HAL_BYPASS_REPLAY_DATA_INJECTION:
674 result.appendFormat(" HAL_BYPASS_REPLAY_DATA_INJECTION : %s\n",
675 mAllowListedPackage.c_str());
676 break;
Anthony Stange9bb16702023-01-03 22:42:31 +0000677 default:
678 result.appendFormat(" UNKNOWN\n");
679 break;
Mathias Agopianba02cd22013-07-03 16:20:57 -0700680 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800681 result.appendFormat("Sensor Privacy: %s\n",
682 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700683
Brian Duddie967ce172019-06-10 11:08:27 -0700684 const auto& activeConnections = connLock.getActiveConnections();
685 result.appendFormat("%zd active connections\n", activeConnections.size());
686 for (size_t i=0 ; i < activeConnections.size() ; i++) {
687 result.appendFormat("Connection Number: %zu \n", i);
688 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700689 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700690
Brian Duddie967ce172019-06-10 11:08:27 -0700691 const auto& directConnections = connLock.getDirectConnections();
692 result.appendFormat("%zd direct connections\n", directConnections.size());
693 for (size_t i = 0 ; i < directConnections.size() ; i++) {
694 result.appendFormat("Direct connection %zu:\n", i);
695 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700696 }
697
Aravind Akella18d6d512015-06-18 14:18:28 -0700698 result.appendFormat("Previous Registrations:\n");
699 // Log in the reverse chronological order.
700 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
701 SENSOR_REGISTRATIONS_BUF_SIZE;
702 const int startIndex = currentIndex;
703 do {
704 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
705 if (SensorRegistrationInfo::isSentinel(reg_info)) {
706 // Ignore sentinel, proceed to next item.
707 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
708 SENSOR_REGISTRATIONS_BUF_SIZE;
709 continue;
710 }
Peng Xu51224682017-03-10 16:57:27 -0800711 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700712 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
713 SENSOR_REGISTRATIONS_BUF_SIZE;
714 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700715 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700716 }
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000717 write(fd, result.c_str(), result.size());
Mathias Agopianfc328812010-07-14 23:41:37 -0700718 return NO_ERROR;
719}
720
Mike Ma24743862020-01-29 00:36:55 -0800721/**
722 * Dump debugging information as android.service.SensorServiceProto protobuf message using
723 * ProtoOutputStream.
724 *
725 * See proto definition and some notes about ProtoOutputStream in
726 * frameworks/base/core/proto/android/service/sensor_service.proto
727 */
728status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
729 using namespace service::SensorServiceProto;
730 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800731 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
732 if (!mSensors.hasAnySensor()) {
733 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
734 }
Mike Ma24743862020-01-29 00:36:55 -0800735 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
736
737 timespec curTime;
738 clock_gettime(CLOCK_REALTIME, &curTime);
739 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
740
741 // Write SensorDeviceProto
742 uint64_t token = proto.start(SENSOR_DEVICE);
743 SensorDevice::getInstance().dump(&proto);
744 proto.end(token);
745
746 // Write SensorListProto
747 token = proto.start(SENSORS);
748 mSensors.dump(&proto);
749 proto.end(token);
750
751 // Write SensorFusionProto
752 token = proto.start(FUSION_STATE);
753 SensorFusion::getInstance().dump(&proto);
754 proto.end(token);
755
756 // Write SensorEventsProto
757 token = proto.start(SENSOR_EVENTS);
758 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100759 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
760 if (!i.second->isEmpty() && s != nullptr) {
Tomasz Wasilczyke50b2de2023-08-14 18:03:09 +0000761 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().empty() ?
Mike Ma24743862020-01-29 00:36:55 -0800762 "normal" : "mask_data");
763 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
764 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000765 std::string(s->getSensor().getName().c_str()));
Mike Ma24743862020-01-29 00:36:55 -0800766 i.second->dump(&proto);
767 proto.end(mToken);
768 }
769 }
770 proto.end(token);
771
772 // Write ActiveSensorProto
773 SensorDevice& dev = SensorDevice::getInstance();
774 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
775 int handle = mActiveSensors.keyAt(i);
776 if (dev.isSensorActive(handle)) {
777 token = proto.start(ACTIVE_SENSORS);
778 proto.write(service::ActiveSensorProto::NAME,
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000779 std::string(getSensorName(handle).c_str()));
Mike Ma24743862020-01-29 00:36:55 -0800780 proto.write(service::ActiveSensorProto::HANDLE, handle);
781 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
782 int(mActiveSensors.valueAt(i)->getNumConnections()));
783 proto.end(token);
784 }
785 }
786
787 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
788 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
789 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
790
791 switch(mCurrentOperatingMode) {
792 case NORMAL:
793 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
794 break;
795 case RESTRICTED:
796 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000797 proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.c_str()));
Mike Ma24743862020-01-29 00:36:55 -0800798 break;
799 case DATA_INJECTION:
800 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000801 proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.c_str()));
Mike Ma24743862020-01-29 00:36:55 -0800802 break;
803 default:
804 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
805 }
806 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
807
808 // Write repeated SensorEventConnectionProto
809 const auto& activeConnections = connLock->getActiveConnections();
810 for (size_t i = 0; i < activeConnections.size(); i++) {
811 token = proto.start(ACTIVE_CONNECTIONS);
812 activeConnections[i]->dump(&proto);
813 proto.end(token);
814 }
815
816 // Write repeated SensorDirectConnectionProto
817 const auto& directConnections = connLock->getDirectConnections();
818 for (size_t i = 0 ; i < directConnections.size() ; i++) {
819 token = proto.start(DIRECT_CONNECTIONS);
820 directConnections[i]->dump(&proto);
821 proto.end(token);
822 }
823
824 // Write repeated SensorRegistrationInfoProto
825 const int startIndex = mNextSensorRegIndex;
826 int curr = startIndex;
827 do {
828 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
829 if (SensorRegistrationInfo::isSentinel(reg_info)) {
830 // Ignore sentinel, proceed to next item.
831 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
832 continue;
833 }
834 token = proto.start(PREVIOUS_REGISTRATIONS);
835 reg_info.dump(&proto);
836 proto.end(token);
837 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
838 } while (startIndex != curr);
839
840 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
841}
842
Michael Groover5e1f60b2018-12-04 22:34:29 -0800843void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700844 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
845 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800846}
847
Brian Duddie967ce172019-06-10 11:08:27 -0700848void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800849 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700850 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
851 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
852 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800853 }
854 dev.disableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700855 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800856 // Clear all pending flush connections for all active sensors. If one of the active
857 // connections has called flush() and the underlying sensor has been disabled before a
858 // flush complete event is returned, we need to remove the connection from this queue.
859 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
860 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
861 }
862}
863
864void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700865 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
866 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800867}
868
Brian Duddie967ce172019-06-10 11:08:27 -0700869void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800870 // sensors should only be enabled if the operating state is not restricted and sensor
871 // privacy is not enabled.
872 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
873 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
874 mCurrentOperatingMode,
875 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
876 return;
877 }
878 SensorDevice& dev(SensorDevice::getInstance());
879 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700880 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
881 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
882 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800883 }
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700884 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800885}
886
Evan Severson4c197852022-01-27 10:44:27 -0800887void SensorService::capRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100888 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
889 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800890 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100891 }
892
893 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800894 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100895 }
896}
897
Evan Severson4c197852022-01-27 10:44:27 -0800898void SensorService::uncapRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100899 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
900 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800901 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100902 }
903
904 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800905 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100906 }
907}
Brian Duddie967ce172019-06-10 11:08:27 -0700908
Svet Ganove752a5c2018-01-15 17:14:20 -0800909// NOTE: This is a remote API - make sure all args are validated
910status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
911 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
912 return PERMISSION_DENIED;
913 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700914 if (args.size() == 0) {
915 return BAD_INDEX;
916 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800917 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
918 return BAD_VALUE;
919 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700920 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800921 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700922 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800923 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700924 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800925 return handleGetUidState(args, out, err);
Brian Duddie4a4d0462022-05-09 16:49:49 -0700926 } else if (args[0] == String16("unrestrict-ht")) {
927 mHtRestricted = false;
928 return NO_ERROR;
929 } else if (args[0] == String16("restrict-ht")) {
930 mHtRestricted = true;
931 return NO_ERROR;
Svet Ganove752a5c2018-01-15 17:14:20 -0800932 } else if (args.size() == 1 && args[0] == String16("help")) {
933 printHelp(out);
934 return NO_ERROR;
935 }
936 printHelp(err);
937 return BAD_VALUE;
938}
939
Tanmay Patild33a1822019-04-11 18:38:55 -0700940static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800941 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700942 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800943 if (uid <= 0) {
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000944 ALOGE("Unknown package: '%s'", String8(packageName).c_str());
945 dprintf(err, "Unknown package: '%s'\n", String8(packageName).c_str());
Svet Ganove752a5c2018-01-15 17:14:20 -0800946 return BAD_VALUE;
947 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700948
949 if (userId < 0) {
950 ALOGE("Invalid user: %d", userId);
951 dprintf(err, "Invalid user: %d\n", userId);
952 return BAD_VALUE;
953 }
954
955 uid = multiuser_get_uid(userId, uid);
956 return NO_ERROR;
957}
958
959status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
960 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
961 if (!(args.size() == 3 || args.size() == 5)) {
962 printHelp(err);
963 return BAD_VALUE;
964 }
965
Svet Ganove752a5c2018-01-15 17:14:20 -0800966 bool active = false;
967 if (args[2] == String16("active")) {
968 active = true;
969 } else if ((args[2] != String16("idle"))) {
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +0000970 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).c_str());
Svet Ganove752a5c2018-01-15 17:14:20 -0800971 return BAD_VALUE;
972 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700973
974 int userId = 0;
975 if (args.size() == 5 && args[3] == String16("--user")) {
976 userId = atoi(String8(args[4]));
977 }
978
979 uid_t uid;
980 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
981 return BAD_VALUE;
982 }
983
Svet Ganove752a5c2018-01-15 17:14:20 -0800984 mUidPolicy->addOverrideUid(uid, active);
985 return NO_ERROR;
986}
987
988status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700989 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
990 if (!(args.size() == 2 || args.size() == 4)) {
991 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800992 return BAD_VALUE;
993 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700994
995 int userId = 0;
996 if (args.size() == 4 && args[2] == String16("--user")) {
997 userId = atoi(String8(args[3]));
998 }
999
1000 uid_t uid;
1001 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1002 return BAD_VALUE;
1003 }
1004
Svet Ganove752a5c2018-01-15 17:14:20 -08001005 mUidPolicy->removeOverrideUid(uid);
1006 return NO_ERROR;
1007}
1008
1009status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -07001010 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1011 if (!(args.size() == 2 || args.size() == 4)) {
1012 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -08001013 return BAD_VALUE;
1014 }
Tanmay Patild33a1822019-04-11 18:38:55 -07001015
1016 int userId = 0;
1017 if (args.size() == 4 && args[2] == String16("--user")) {
1018 userId = atoi(String8(args[3]));
1019 }
1020
1021 uid_t uid;
1022 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1023 return BAD_VALUE;
1024 }
1025
Svet Ganove752a5c2018-01-15 17:14:20 -08001026 if (mUidPolicy->isUidActive(uid)) {
1027 return dprintf(out, "active\n");
1028 } else {
1029 return dprintf(out, "idle\n");
1030 }
1031}
1032
1033status_t SensorService::printHelp(int out) {
1034 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -07001035 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1036 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1037 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -08001038 " help print this message\n");
1039}
1040
Peng Xu0cc8f802016-04-05 23:46:03 -07001041//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -08001042void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001043 sensors_event_t const* buffer, const int count) {
1044 for (int i=0 ; i<count ; i++) {
1045 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -07001046 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1047 handle = buffer[i].meta_data.sensor;
1048 }
Aravind Akella0e025c52014-06-03 19:19:57 -07001049 if (connection->hasSensor(handle)) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001050 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -07001051 // If this buffer has an event from a one_shot sensor and this connection is registered
1052 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -07001053 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -07001054 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1055 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001056 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001057 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001058
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001059 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001060 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001061}
1062
Rocky Fangbeb0dff2023-12-15 01:59:46 +00001063void SensorService::sendEventsToAllClients(
1064 const std::vector<sp<SensorEventConnection>>& activeConnections,
1065 ssize_t count) {
1066 // Send our events to clients. Check the state of wake lock for each client
1067 // and release the lock if none of the clients need it.
1068 bool needsWakeLock = false;
1069 for (const sp<SensorEventConnection>& connection : activeConnections) {
1070 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1071 mMapFlushEventsToConnections);
1072 needsWakeLock |= connection->needsWakeLock();
1073 // If the connection has one-shot sensors, it may be cleaned up after
1074 // first trigger. Early check for one-shot sensors.
1075 if (connection->hasOneShotSensors()) {
1076 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
1077 }
1078 }
1079
1080 if (mWakeLockAcquired && !needsWakeLock) {
1081 setWakeLockAcquiredLocked(false);
1082 }
1083}
1084
1085void SensorService::disconnectDynamicSensor(
1086 int handle,
1087 const std::vector<sp<SensorEventConnection>>& activeConnections) {
1088 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1089 SensorDevice::getInstance().handleDynamicSensorConnection(
1090 handle, false /*connected*/);
1091 if (!unregisterDynamicSensorLocked(handle)) {
1092 ALOGE("Dynamic sensor release error.");
1093 }
1094 for (const sp<SensorEventConnection>& connection : activeConnections) {
1095 connection->removeSensor(handle);
1096 }
1097}
1098
1099void SensorService::handleDeviceReconnection(SensorDevice& device) {
1100 if (sensorservice_flags::dynamic_sensor_hal_reconnect_handling()) {
1101 const std::vector<sp<SensorEventConnection>> activeConnections =
1102 mConnectionHolder.lock(mLock).getActiveConnections();
1103
1104 for (int32_t handle : device.getDynamicSensorHandles()) {
1105 if (mDynamicMetaSensorHandle.has_value()) {
1106 // Sending one event at a time to prevent the number of handle is more than the
1107 // buffer can hold.
1108 mSensorEventBuffer[0].type = SENSOR_TYPE_DYNAMIC_SENSOR_META;
1109 mSensorEventBuffer[0].sensor = *mDynamicMetaSensorHandle;
1110 mSensorEventBuffer[0].dynamic_sensor_meta.connected = false;
1111 mSensorEventBuffer[0].dynamic_sensor_meta.handle = handle;
1112 mMapFlushEventsToConnections[0] = nullptr;
1113
1114 disconnectDynamicSensor(handle, activeConnections);
1115 sendEventsToAllClients(activeConnections, 1);
1116 } else {
1117 ALOGE("Failed to find mDynamicMetaSensorHandle during init.");
1118 break;
1119 }
1120 }
1121 }
1122 device.reconnect();
1123}
1124
Peng Xu47e96012016-03-28 17:55:56 -07001125bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +00001126 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -07001127
Peng Xueb4d6282015-12-10 18:02:41 -08001128 // each virtual sensor could generate an event per "real" event, that's why we need to size
1129 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
1130 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -07001131 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001132 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -07001133 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001134
Mathias Agopianf001c922010-11-11 17:58:51 -08001135 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -07001136
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001137 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -07001138 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001139 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
1140 if (count < 0) {
Rocky Fangbeb0dff2023-12-15 01:59:46 +00001141 if (count == DEAD_OBJECT && device.isReconnecting()) {
1142 handleDeviceReconnection(device);
Vladimir Komsiyski574ac3e2023-07-28 07:13:46 +00001143 continue;
Brian Stack156da082018-10-01 15:58:53 -07001144 } else {
1145 ALOGE("sensor poll failed (%s)", strerror(-count));
1146 break;
1147 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001148 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001149
1150 // Reset sensors_event_t.flags to zero for all events in the buffer.
1151 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001152 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001153 }
Brian Duddie967ce172019-06-10 11:08:27 -07001154 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -07001155
Aravind Akella9a844cf2014-02-11 18:58:52 -08001156 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
1157 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
1158 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
1159 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
1160 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001161 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001162 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001163 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001164 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001165 }
1166 }
1167
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001168 if (wakeEvents > 0) {
1169 if (!mWakeLockAcquired) {
1170 setWakeLockAcquiredLocked(true);
1171 }
1172 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001173 }
Aravind Akella8493b792014-09-08 15:45:47 -07001174 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -08001175
Mathias Agopianf001c922010-11-11 17:58:51 -08001176 // handle virtual sensors
1177 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -07001178 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -07001179 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001180 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -07001181 SensorFusion& fusion(SensorFusion::getInstance());
1182 if (fusion.isEnabled()) {
1183 for (size_t i=0 ; i<size_t(count) ; i++) {
1184 fusion.process(event[i]);
1185 }
1186 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001187 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -07001188 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001189 if (count + k >= minBufferSize) {
1190 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -07001191 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001192 count, k, minBufferSize);
1193 break;
1194 }
Mathias Agopianf001c922010-11-11 17:58:51 -08001195 sensors_event_t out;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001196 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001197 if (si == nullptr) {
1198 ALOGE("handle %d is not an valid virtual sensor", handle);
1199 continue;
1200 }
1201
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001202 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -07001203 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -08001204 k++;
1205 }
1206 }
1207 }
1208 if (k) {
1209 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -07001210 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -08001211 count += k;
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +02001212 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -07001213 }
1214 }
1215 }
1216
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001217 // handle backward compatibility for RotationVector sensor
1218 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
1219 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001220 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001221 // All the 4 components of the quaternion should be available
1222 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -07001223 mSensorEventBuffer[i].data[4] = -1;
1224 }
1225 }
1226 }
1227
Brian Duddie967ce172019-06-10 11:08:27 -07001228 // Cache the list of active connections, since we use it in multiple places below but won't
1229 // modify it here
1230 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
1231
Aravind Akella8493b792014-09-08 15:45:47 -07001232 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -07001233 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
1234 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
1235 // SensorEventConnection mapped to the corresponding flush_complete_event in
1236 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -07001237 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -07001238 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
1239 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
1240 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001241 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -07001242 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
1243 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001244 }
1245 }
Peng Xu2576cb62016-01-20 00:22:09 -08001246 // handle dynamic sensor meta events, process registration and unregistration of dynamic
1247 // sensor based on content of event.
1248 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
1249 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
1250 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1251 const sensor_t& dynamicSensor =
1252 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
1253 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
1254 handle, dynamicSensor.type, dynamicSensor.name);
1255
Peng Xu0cc8f802016-04-05 23:46:03 -07001256 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -08001257 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -07001258 sensor_t s = dynamicSensor;
1259 // make sure the dynamic sensor flag is set
1260 s.flags |= DYNAMIC_SENSOR_MASK;
1261 // force the handle to be consistent
1262 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -08001263
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001264 auto si = std::make_shared<HardwareSensor>(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -08001265
Peng Xu0cc8f802016-04-05 23:46:03 -07001266 // This will release hold on dynamic sensor meta, so it should be called
1267 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -07001268 device.handleDynamicSensorConnection(handle, true /*connected*/);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001269 registerDynamicSensorLocked(std::move(si));
Peng Xu47e96012016-03-28 17:55:56 -07001270 } else {
1271 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
1272 }
Peng Xu2576cb62016-01-20 00:22:09 -08001273 } else {
1274 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
Rocky Fangbeb0dff2023-12-15 01:59:46 +00001275 disconnectDynamicSensor(handle, activeConnections);
Rocky Fang65beac92024-05-20 21:01:21 +00001276 device.cleanupDisconnectedDynamicSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001277 }
1278 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001279 }
1280
Aravind Akella9a844cf2014-02-11 18:58:52 -08001281 // Send our events to clients. Check the state of wake lock for each client and release the
1282 // lock if none of the clients need it.
Rocky Fangbeb0dff2023-12-15 01:59:46 +00001283 sendEventsToAllClients(activeConnections, count);
Aravind Akella8493b792014-09-08 15:45:47 -07001284 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001285
Steve Block3c20fbe2012-01-05 23:22:43 +00001286 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001287 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001288 return false;
1289}
1290
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +02001291void SensorService::processRuntimeSensorEvents() {
1292 size_t count = 0;
1293 const size_t maxBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
1294
1295 {
1296 std::unique_lock<std::mutex> lock(mRutimeSensorThreadMutex);
1297
1298 if (mRuntimeSensorEventQueue.empty()) {
1299 mRuntimeSensorsCv.wait(lock, [this] { return !mRuntimeSensorEventQueue.empty(); });
1300 }
1301
1302 // Pop the events from the queue into the buffer until it's empty or the buffer is full.
1303 while (!mRuntimeSensorEventQueue.empty()) {
1304 if (count >= maxBufferSize) {
1305 ALOGE("buffer too small to hold all events: count=%zd, size=%zu", count,
1306 maxBufferSize);
1307 break;
1308 }
1309 mRuntimeSensorEventBuffer[count] = mRuntimeSensorEventQueue.front();
1310 mRuntimeSensorEventQueue.pop();
1311 count++;
1312 }
1313 }
1314
1315 if (count) {
1316 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1317
1318 recordLastValueLocked(mRuntimeSensorEventBuffer, count);
1319 sortEventBuffer(mRuntimeSensorEventBuffer, count);
1320
1321 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1322 connection->sendEvents(mRuntimeSensorEventBuffer, count, /* scratch= */ nullptr,
1323 /* mapFlushEventsToConnections= */ nullptr);
1324 if (connection->hasOneShotSensors()) {
1325 cleanupAutoDisabledSensorLocked(connection, mRuntimeSensorEventBuffer, count);
1326 }
1327 }
1328 }
1329}
1330
Aravind Akella56ae4262014-07-10 16:01:10 -07001331sp<Looper> SensorService::getLooper() const {
1332 return mLooper;
1333}
1334
Aravind Akellab4373ac2014-10-29 17:55:20 -07001335void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001336 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1337 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1338 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001339 }
Brian Duddie967ce172019-06-10 11:08:27 -07001340 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001341}
1342
1343void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1344 if (acquire) {
1345 if (!mWakeLockAcquired) {
1346 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1347 mWakeLockAcquired = true;
1348 }
1349 mLooper->wake();
1350 } else {
1351 if (mWakeLockAcquired) {
1352 release_wake_lock(WAKE_LOCK_NAME);
1353 mWakeLockAcquired = false;
1354 }
1355 }
1356}
1357
Aravind Akellab4373ac2014-10-29 17:55:20 -07001358bool SensorService::isWakeLockAcquired() {
1359 Mutex::Autolock _l(mLock);
1360 return mWakeLockAcquired;
1361}
1362
Aravind Akella56ae4262014-07-10 16:01:10 -07001363bool SensorService::SensorEventAckReceiver::threadLoop() {
1364 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001365 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001366 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001367 bool wakeLockAcquired = mService->isWakeLockAcquired();
1368 int timeout = -1;
1369 if (wakeLockAcquired) timeout = 5000;
1370 int ret = looper->pollOnce(timeout);
1371 if (ret == ALOOPER_POLL_TIMEOUT) {
1372 mService->resetAllWakeLockRefCounts();
1373 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001374 } while(!Thread::exitPending());
1375 return false;
1376}
1377
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +02001378bool SensorService::RuntimeSensorHandler::threadLoop() {
1379 ALOGD("new thread RuntimeSensorHandler");
1380 do {
1381 mService->processRuntimeSensorEvents();
1382 } while (!Thread::exitPending());
1383 return false;
1384}
1385
Aravind Akella9a844cf2014-02-11 18:58:52 -08001386void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001387 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001388 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001389 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1390 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001391 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001392 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001393 }
Peng Xu2576cb62016-01-20 00:22:09 -08001394
Peng Xu6a2d3a02015-12-21 12:00:23 -08001395 auto logger = mRecentEvent.find(buffer[i].sensor);
1396 if (logger != mRecentEvent.end()) {
1397 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001398 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001399 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001400}
1401
Peng Xu47e96012016-03-28 17:55:56 -07001402void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001403 struct compar {
1404 static int cmp(void const* lhs, void const* rhs) {
1405 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1406 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001407 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001408 }
1409 };
1410 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1411}
1412
Mathias Agopian5d270722010-07-19 15:20:39 -07001413String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001414 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001415}
1416
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001417String8 SensorService::getSensorStringType(int handle) const {
1418 return mSensors.getStringType(handle);
1419}
1420
Aravind Akellab4099e72013-10-15 15:43:10 -07001421bool SensorService::isVirtualSensor(int handle) const {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001422 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001423 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001424}
1425
Aravind Akella9a844cf2014-02-11 18:58:52 -08001426bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001427 int handle = event.sensor;
1428 if (event.type == SENSOR_TYPE_META_DATA) {
1429 handle = event.meta_data.sensor;
1430 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001431 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001432 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001433}
1434
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001435int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1436 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1437 // UUID is not supported for this device.
1438 return 0;
1439 }
1440 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1441 // This sensor can be uniquely identified in the system by
1442 // the combination of its type and name.
1443 return -1;
1444 }
1445
1446 // We have a dynamic sensor.
1447
1448 if (!sHmacGlobalKeyIsValid) {
lifr3ab0a1b2021-08-06 00:14:26 +08001449 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001450 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1451 return 0;
1452 }
1453
1454 // We want each app author/publisher to get a different ID, so that the
1455 // same dynamic sensor cannot be tracked across apps by multiple
1456 // authors/publishers. So we use both our UUID and our User ID.
1457 // Note potential confusion:
1458 // UUID => Universally Unique Identifier.
1459 // UID => User Identifier.
1460 // We refrain from using "uid" except as needed by API to try to
1461 // keep this distinction clear.
1462
1463 auto appUserId = IPCThreadState::self()->getCallingUid();
1464 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1465 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1466 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1467
1468 // Now we use our key on our UUID/app combo to get the hash.
1469 uint8_t hash[EVP_MAX_MD_SIZE];
1470 unsigned int hashLen;
1471 if (HMAC(EVP_sha256(),
1472 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1473 uuidAndApp, sizeof(uuidAndApp),
1474 hash, &hashLen) == nullptr) {
lifr3ab0a1b2021-08-06 00:14:26 +08001475 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001476 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1477 return 0;
1478 }
1479
1480 int32_t id = 0;
1481 if (hashLen < sizeof(id)) {
1482 // We never expect this case, but out of paranoia, we handle it.
1483 // Our 'id' length is already quite small, we don't want the
1484 // effective length of it to be even smaller.
1485 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1486 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1487 return 0;
1488 }
1489
1490 // This is almost certainly less than all of 'hash', but it's as secure
1491 // as we can be with our current 'id' length.
1492 memcpy(&id, hash, sizeof(id));
1493
1494 // Note at the beginning of the function that we return the values of
1495 // 0 and -1 to represent special cases. As a result, we can't return
1496 // those as dynamic sensor IDs. If we happened to hash to one of those
1497 // values, we change 'id' so we report as a dynamic sensor, and not as
1498 // one of those special cases.
1499 if (id == -1) {
1500 id = -2;
1501 } else if (id == 0) {
1502 id = 1;
1503 }
1504 return id;
1505}
1506
1507void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1508 for (auto &sensor : sensorList) {
1509 int32_t id = getIdFromUuid(sensor.getUuid());
1510 sensor.setId(id);
Eric Laurente3f27df2022-01-05 19:20:32 +01001511 // The sensor UUID must always be anonymized here for non privileged clients.
1512 // There is no other checks after this point before returning to client process.
1513 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1514 sensor.anonymizeUuid();
1515 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001516 }
1517}
1518
Anh Pham4e291332021-02-10 14:17:56 +01001519Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -07001520 char value[PROPERTY_VALUE_MAX];
1521 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001522 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001523 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001524 Vector<Sensor> accessibleSensorList;
Anh Pham4e291332021-02-10 14:17:56 +01001525
Brian Duddie0d4ac562022-05-23 17:47:50 -07001526 resetTargetSdkVersionCache(opPackageName);
Anh Pham4e291332021-02-10 14:17:56 +01001527 bool isCapped = isRateCappedBasedOnPermission(opPackageName);
Aravind Akella70018042014-04-07 22:52:37 +00001528 for (size_t i = 0; i < initialSensorList.size(); i++) {
1529 Sensor sensor = initialSensorList[i];
Anh Pham4e291332021-02-10 14:17:56 +01001530 if (isCapped && isSensorInCappedSet(sensor.getType())) {
1531 sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
1532 sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
1533 }
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001534 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001535 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001536 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001537 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001538}
1539
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001540void SensorService::addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
1541 Vector<Sensor>& accessibleSensorList) {
1542 if (canAccessSensor(sensor, "can't see", opPackageName)) {
1543 accessibleSensorList.add(sensor);
1544 } else if (sensor.getType() != SENSOR_TYPE_HEAD_TRACKER) {
1545 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
Tomasz Wasilczyk02fd95c2023-08-30 17:51:31 +00001546 sensor.getName().c_str(), sensor.getRequiredPermission().c_str(),
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001547 sensor.getRequiredAppOp());
1548 }
1549}
1550
Peng Xu47e96012016-03-28 17:55:56 -07001551Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001552 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001553 mSensors.forEachSensor(
Brian Duddie4a4d0462022-05-09 16:49:49 -07001554 [this, &opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001555 if (sensor.isDynamicSensor()) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001556 addSensorIfAccessible(opPackageName, sensor, accessibleSensorList);
1557 }
1558 return true;
1559 });
1560 makeUuidsIntoIdsForSensorList(accessibleSensorList);
1561 return accessibleSensorList;
1562}
1563
1564Vector<Sensor> SensorService::getRuntimeSensorList(const String16& opPackageName, int deviceId) {
1565 Vector<Sensor> accessibleSensorList;
1566 mSensors.forEachEntry(
1567 [this, &opPackageName, deviceId, &accessibleSensorList] (
1568 const SensorServiceUtil::SensorList::Entry& e) -> bool {
1569 if (e.deviceId == deviceId) {
1570 addSensorIfAccessible(opPackageName, e.si->getSensor(), accessibleSensorList);
Peng Xu0cc8f802016-04-05 23:46:03 -07001571 }
1572 return true;
1573 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001574 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001575 return accessibleSensorList;
1576}
1577
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001578sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001579 int requestedMode, const String16& opPackageName, const String16& attributionTag) {
Mark Wheatley8f285d92023-07-07 20:07:18 +00001580 // Only 4 modes supported for a SensorEventConnection ... NORMAL, DATA_INJECTION,
1581 // REPLAY_DATA_INJECTION and HAL_BYPASS_REPLAY_DATA_INJECTION
1582 if (requestedMode != NORMAL && !isInjectionMode(requestedMode)) {
Yi Kong8f313e32018-07-17 14:13:29 -07001583 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001584 }
Brian Duddie0d4ac562022-05-23 17:47:50 -07001585 resetTargetSdkVersionCache(opPackageName);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001586
1587 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001588 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1589 // operating in DI mode.
1590 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001591 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
Anthony Stangecd01ec12023-01-06 18:35:13 +00001592 if (!isAllowListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001593 }
1594
Mathias Agopian5307d172012-09-18 17:02:43 -07001595 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001596 pid_t pid = IPCThreadState::self()->getCallingPid();
1597
1598 String8 connPackageName =
1599 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1600 String16 connOpPackageName =
1601 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1602 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Mark Wheatley8f285d92023-07-07 20:07:18 +00001603 isInjectionMode(requestedMode),
1604 connOpPackageName, attributionTag));
1605 if (isInjectionMode(requestedMode)) {
Brian Duddie967ce172019-06-10 11:08:27 -07001606 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001607 // Add the associated file descriptor to the Looper for polling whenever there is data to
1608 // be injected.
1609 result->updateLooperRegistration(mLooper);
1610 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001611 return result;
1612}
1613
Aravind Akella841a5922015-06-29 12:37:48 -07001614int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001615 Mutex::Autolock _l(mLock);
Mark Wheatley8f285d92023-07-07 20:07:18 +00001616 return mCurrentOperatingMode == DATA_INJECTION;
1617}
1618
1619int SensorService::isReplayDataInjectionEnabled() {
1620 Mutex::Autolock _l(mLock);
1621 return mCurrentOperatingMode == REPLAY_DATA_INJECTION;
1622}
1623
1624int SensorService::isHalBypassReplayDataInjectionEnabled() {
1625 Mutex::Autolock _l(mLock);
1626 return mCurrentOperatingMode == HAL_BYPASS_REPLAY_DATA_INJECTION;
1627}
1628
1629bool SensorService::isInjectionMode(int mode) {
1630 return (mode == DATA_INJECTION || mode == REPLAY_DATA_INJECTION ||
1631 mode == HAL_BYPASS_REPLAY_DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001632}
1633
Peng Xue36e3472016-11-03 11:57:10 -07001634sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001635 const String16& opPackageName, int deviceId, uint32_t size, int32_t type, int32_t format,
Peng Xue36e3472016-11-03 11:57:10 -07001636 const native_handle *resource) {
Brian Duddie0d4ac562022-05-23 17:47:50 -07001637 resetTargetSdkVersionCache(opPackageName);
Brian Duddie967ce172019-06-10 11:08:27 -07001638 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001639
Michael Groover5e1f60b2018-12-04 22:34:29 -08001640 // No new direct connections are allowed when sensor privacy is enabled
1641 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1642 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1643 return nullptr;
1644 }
1645
Peng Xue36e3472016-11-03 11:57:10 -07001646 struct sensors_direct_mem_t mem = {
1647 .type = type,
1648 .format = format,
1649 .size = size,
1650 .handle = resource,
1651 };
1652 uid_t uid = IPCThreadState::self()->getCallingUid();
1653
1654 if (mem.handle == nullptr) {
1655 ALOGE("Failed to clone resource handle");
1656 return nullptr;
1657 }
1658
1659 // check format
1660 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1661 ALOGE("Direct channel format %d is unsupported!", format);
1662 return nullptr;
1663 }
1664
1665 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001666 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1667 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001668 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001669 return nullptr;
1670 }
1671 }
1672
1673 // check specific to memory type
1674 switch(type) {
1675 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001676 if (resource->numFds < 1) {
1677 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1678 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1679 return nullptr;
1680 }
Peng Xue36e3472016-11-03 11:57:10 -07001681 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001682 if (!ashmem_valid(fd)) {
1683 ALOGE("Supplied Ashmem memory region is invalid");
1684 return nullptr;
1685 }
1686
Peng Xue36e3472016-11-03 11:57:10 -07001687 int size2 = ashmem_get_size_region(fd);
1688 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001689 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001690 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1691 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001692 return nullptr;
1693 }
1694 break;
1695 }
1696 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001697 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001698 break;
1699 default:
1700 ALOGE("Unknown direct connection memory type %d", type);
1701 return nullptr;
1702 }
1703
1704 native_handle_t *clone = native_handle_clone(resource);
1705 if (!clone) {
1706 return nullptr;
1707 }
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001708 native_handle_set_fdsan_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001709
Brian Duddie967ce172019-06-10 11:08:27 -07001710 sp<SensorDirectConnection> conn;
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001711 int channelHandle = 0;
1712 if (deviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
1713 SensorDevice& dev(SensorDevice::getInstance());
1714 channelHandle = dev.registerDirectChannel(&mem);
1715 } else {
1716 auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1717 if (runtimeSensorCallback == mRuntimeSensorCallbacks.end()) {
1718 ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1719 } else {
1720 int fd = dup(clone->data[0]);
1721 channelHandle = runtimeSensorCallback->second->onDirectChannelCreated(fd);
1722 }
1723 }
Peng Xue36e3472016-11-03 11:57:10 -07001724
1725 if (channelHandle <= 0) {
1726 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1727 } else {
1728 mem.handle = clone;
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001729 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName, deviceId);
Peng Xue36e3472016-11-03 11:57:10 -07001730 }
1731
1732 if (conn == nullptr) {
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001733 native_handle_close_with_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001734 native_handle_delete(clone);
1735 } else {
1736 // add to list of direct connections
1737 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001738 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001739 }
1740 return conn;
1741}
1742
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001743int SensorService::configureRuntimeSensorDirectChannel(
1744 int sensorHandle, const SensorDirectConnection* c, const sensors_direct_cfg_t* config) {
1745 int deviceId = c->getDeviceId();
1746 int sensorDeviceId = getDeviceIdFromHandle(sensorHandle);
1747 if (sensorDeviceId != c->getDeviceId()) {
Vladimir Komsiyski3494fd52023-03-22 10:31:22 +01001748 ALOGE("Cannot configure direct channel created for device %d with a sensor that belongs "
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001749 "to device %d", c->getDeviceId(), sensorDeviceId);
1750 return BAD_VALUE;
1751 }
1752 auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1753 if (runtimeSensorCallback == mRuntimeSensorCallbacks.end()) {
1754 ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1755 return BAD_VALUE;
1756 }
1757 return runtimeSensorCallback->second->onDirectChannelConfigured(
1758 c->getHalChannelHandle(), sensorHandle, config->rate_level);
1759}
1760
Peng Xudd5c5cb2017-03-16 17:39:43 -07001761int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001762 int32_t handle, int32_t type,
1763 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001764 Mutex::Autolock _l(mLock);
1765
Alexey Polyudov88711e82017-05-23 19:54:04 -07001766 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001767 return PERMISSION_DENIED;
1768 }
1769
1770 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001771 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001772 size_t expectSize = INT32_MAX;
1773 switch (type) {
1774 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1775 isFloat = true;
1776 expectSize = 3;
1777 break;
1778 case AINFO_LOCAL_GRAVITY:
1779 isFloat = true;
1780 expectSize = 1;
1781 break;
1782 case AINFO_DOCK_STATE:
1783 case AINFO_HIGH_PERFORMANCE_MODE:
1784 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1785 isFloat = false;
1786 expectSize = 1;
1787 break;
1788 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001789 // CUSTOM events must only contain float data; it may have variable size
1790 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1791 ints.size() ||
1792 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1793 handle < 0) {
1794 return BAD_VALUE;
1795 }
1796 isFloat = true;
1797 isCustom = true;
1798 expectSize = floats.size();
1799 break;
1800 }
1801
1802 if (!isCustom && handle != -1) {
1803 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001804 }
1805
1806 // three events: first one is begin tag, last one is end tag, the one in the middle
1807 // is the payload.
1808 sensors_event_t event[3];
1809 int64_t timestamp = elapsedRealtimeNano();
1810 for (sensors_event_t* i = event; i < event + 3; i++) {
1811 *i = (sensors_event_t) {
1812 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001813 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001814 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1815 .timestamp = timestamp++,
1816 .additional_info = (additional_info_event_t) {
1817 .serial = 0
1818 }
1819 };
1820 }
1821
1822 event[0].additional_info.type = AINFO_BEGIN;
1823 event[1].additional_info.type = type;
1824 event[2].additional_info.type = AINFO_END;
1825
1826 if (isFloat) {
1827 if (floats.size() != expectSize) {
1828 return BAD_VALUE;
1829 }
1830 for (size_t i = 0; i < expectSize; ++i) {
1831 event[1].additional_info.data_float[i] = floats[i];
1832 }
1833 } else {
1834 if (ints.size() != expectSize) {
1835 return BAD_VALUE;
1836 }
1837 for (size_t i = 0; i < expectSize; ++i) {
1838 event[1].additional_info.data_int32[i] = ints[i];
1839 }
1840 }
1841
1842 SensorDevice& dev(SensorDevice::getInstance());
1843 for (sensors_event_t* i = event; i < event + 3; i++) {
1844 int ret = dev.injectSensorData(i);
1845 if (ret != NO_ERROR) {
1846 return ret;
1847 }
1848 }
1849 return NO_ERROR;
1850}
1851
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001852status_t SensorService::resetToNormalMode() {
1853 Mutex::Autolock _l(mLock);
1854 return resetToNormalModeLocked();
1855}
1856
1857status_t SensorService::resetToNormalModeLocked() {
1858 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001859 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301860 if (err == NO_ERROR) {
1861 mCurrentOperatingMode = NORMAL;
1862 dev.enableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001863 checkAndReportProxStateChangeLocked();
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301864 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001865 return err;
1866}
1867
Peng Xu47e96012016-03-28 17:55:56 -07001868void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001869 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001870 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001871 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001872 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001873 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001874 int handle = mActiveSensors.keyAt(i);
1875 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001876 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001877 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001878 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001879 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001880 } else {
1881 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001882 }
Brian Duddie7be85572021-12-21 10:44:55 -08001883 if (c->removeSensor(handle)) {
1884 BatteryService::disableSensor(c->getUid(), handle);
1885 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001886 }
1887 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001888 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001889 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001890 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001891 c, i, handle);
1892
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001893 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001894 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001895 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001896 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001897 delete rec;
1898 size--;
1899 } else {
1900 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001901 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001902 }
Aravind Akella8a969552014-09-28 17:52:41 -07001903 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001904 mConnectionHolder.removeEventConnection(connection);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001905 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001906 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001907 }
Peng Xu4f707f82016-09-26 11:28:32 -07001908
1909 SensorDevice& dev(SensorDevice::getInstance());
1910 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001911}
1912
Peng Xue36e3472016-11-03 11:57:10 -07001913void SensorService::cleanupConnection(SensorDirectConnection* c) {
1914 Mutex::Autolock _l(mLock);
1915
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001916 int deviceId = c->getDeviceId();
1917 if (deviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
1918 SensorDevice& dev(SensorDevice::getInstance());
1919 dev.unregisterDirectChannel(c->getHalChannelHandle());
1920 } else {
1921 auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1922 if (runtimeSensorCallback != mRuntimeSensorCallbacks.end()) {
1923 runtimeSensorCallback->second->onDirectChannelDestroyed(c->getHalChannelHandle());
1924 } else {
1925 ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1926 }
1927 }
Brian Duddie967ce172019-06-10 11:08:27 -07001928 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001929}
1930
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001931void SensorService::checkAndReportProxStateChangeLocked() {
1932 if (mProxSensorHandles.empty()) return;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001933
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001934 SensorDevice& dev(SensorDevice::getInstance());
1935 bool isActive = false;
1936 for (auto& sensor : mProxSensorHandles) {
1937 if (dev.isSensorActive(sensor)) {
1938 isActive = true;
1939 break;
1940 }
1941 }
1942 if (isActive != mLastReportedProxIsActive) {
1943 notifyProximityStateLocked(isActive, mProximityActiveListeners);
1944 mLastReportedProxIsActive = isActive;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001945 }
1946}
1947
1948void SensorService::notifyProximityStateLocked(
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001949 const bool isActive,
Santos Cordon7ea287a2021-06-14 13:45:29 +01001950 const std::vector<sp<ProximityActiveListener>>& listeners) {
Santos Cordon7ea287a2021-06-14 13:45:29 +01001951 const uint64_t mySeq = ++curProxCallbackSeq;
1952 std::thread t([isActive, mySeq, listenersCopy = listeners]() {
1953 while (completedCallbackSeq.load() != mySeq - 1)
1954 std::this_thread::sleep_for(1ms);
1955 for (auto& listener : listenersCopy)
1956 listener->onProximityActive(isActive);
1957 completedCallbackSeq++;
1958 });
1959 t.detach();
Andrew Lehmer3a602572021-03-25 15:19:56 -07001960}
1961
1962status_t SensorService::addProximityActiveListener(const sp<ProximityActiveListener>& callback) {
1963 if (callback == nullptr) {
1964 return BAD_VALUE;
1965 }
1966
1967 Mutex::Autolock _l(mLock);
1968
1969 // Check if the callback was already added.
1970 for (const auto& cb : mProximityActiveListeners) {
1971 if (cb == callback) {
1972 return ALREADY_EXISTS;
1973 }
1974 }
1975
1976 mProximityActiveListeners.push_back(callback);
1977 std::vector<sp<ProximityActiveListener>> listener(1, callback);
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001978 notifyProximityStateLocked(mLastReportedProxIsActive, listener);
Andrew Lehmer3a602572021-03-25 15:19:56 -07001979 return OK;
1980}
1981
1982status_t SensorService::removeProximityActiveListener(
1983 const sp<ProximityActiveListener>& callback) {
1984 if (callback == nullptr) {
1985 return BAD_VALUE;
1986 }
1987
1988 Mutex::Autolock _l(mLock);
1989
1990 for (auto iter = mProximityActiveListeners.begin();
1991 iter != mProximityActiveListeners.end();
1992 ++iter) {
1993 if (*iter == callback) {
1994 mProximityActiveListeners.erase(iter);
1995 return OK;
1996 }
1997 }
1998 return NAME_NOT_FOUND;
1999}
2000
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002001std::shared_ptr<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07002002 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07002003}
2004
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01002005int SensorService::getDeviceIdFromHandle(int handle) const {
2006 int deviceId = RuntimeSensor::DEFAULT_DEVICE_ID;
2007 mSensors.forEachEntry(
2008 [&deviceId, handle] (const SensorServiceUtil::SensorList::Entry& e) -> bool {
2009 if (e.si->getSensor().getHandle() == handle) {
2010 deviceId = e.deviceId;
2011 return false; // stop iterating
2012 }
2013 return true;
2014 });
2015 return deviceId;
2016}
2017
Mathias Agopianfc328812010-07-14 23:41:37 -07002018status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07002019 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07002020 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002021 if (mInitCheck != NO_ERROR)
2022 return mInitCheck;
2023
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002024 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002025 if (sensor == nullptr ||
2026 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00002027 return BAD_VALUE;
2028 }
2029
Brian Duddie967ce172019-06-10 11:08:27 -07002030 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Anthony Stange9bb16702023-01-03 22:42:31 +00002031 if (mCurrentOperatingMode != NORMAL && mCurrentOperatingMode != REPLAY_DATA_INJECTION &&
Anthony Stangecd01ec12023-01-06 18:35:13 +00002032 !isAllowListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08002033 return INVALID_OPERATION;
2034 }
2035
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002036 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07002037 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002038 rec = new SensorRecord(connection);
2039 mActiveSensors.add(handle, rec);
2040 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07002041 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002042 }
Brian Stack26029ee2019-04-22 17:25:49 -07002043
2044 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
2045 // the recent event as stale to ensure that the previous event is not sent to a client. This
2046 // ensures on-change events that were generated during a previous sensor activation are not
2047 // erroneously sent to newly connected clients, especially if a second client registers for
2048 // an on-change sensor before the first client receives the updated event. Once an updated
2049 // event is received, the recent events will be marked as current, and any new clients will
2050 // immediately receive the most recent event.
2051 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
2052 auto logger = mRecentEvent.find(handle);
2053 if (logger != mRecentEvent.end()) {
2054 logger->second->setLastEventStale();
2055 }
2056 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002057 } else {
2058 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002059 // this sensor is already activated, but we are adding a connection that uses it.
2060 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002061 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07002062 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002063 // NOTE: The wake_up flag of this event may get set to
2064 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08002065
2066 auto logger = mRecentEvent.find(handle);
2067 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07002068 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07002069 // Verify that the last sensor event was generated from the current activation
2070 // of the sensor. If not, it is possible for an on-change sensor to receive a
2071 // sensor event that is stale if two clients re-activate the sensor
2072 // simultaneously.
2073 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07002074 event.sensor = handle;
2075 if (event.version == sizeof(sensors_event_t)) {
2076 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
2077 setWakeLockAcquiredLocked(true);
2078 }
Yi Kong8f313e32018-07-17 14:13:29 -07002079 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07002080 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07002081 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07002082 }
2083 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08002084 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002085 }
2086 }
2087 }
2088 }
2089
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07002090 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002091 BatteryService::enableSensor(connection->getUid(), handle);
2092 // the sensor was added (which means it wasn't already there)
2093 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07002094 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002095 } else {
2096 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
2097 handle, connection.get());
2098 }
2099
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05302100 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07002101 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05302102 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
2103 samplingPeriodNs = maxDelayNs;
2104 }
2105
Aravind Akella724d91d2013-06-27 12:04:23 -07002106 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2107 if (samplingPeriodNs < minDelayNs) {
2108 samplingPeriodNs = minDelayNs;
2109 }
2110
Aravind Akella6c2664a2014-08-13 12:24:50 -07002111 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
2112 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07002113 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
2114
Aravind Akella4949c502015-02-11 15:54:35 -08002115 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07002116 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07002117
Peng Xu20483c42015-10-26 15:14:43 -07002118 // Call flush() before calling activate() on the sensor. Wait for a first
2119 // flush complete event before sending events on this connection. Ignore
2120 // one-shot sensors which don't support flush(). Ignore on-change sensors
2121 // to maintain the on-change logic (any on-change events except the initial
2122 // one should be trigger by a change in value). Also if this sensor isn't
2123 // already active, don't call flush().
2124 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08002125 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07002126 rec->getNumConnections() > 1) {
2127 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07002128 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07002129 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07002130 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07002131 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07002132 } else {
2133 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07002134 }
2135 }
Aravind Akella724d91d2013-06-27 12:04:23 -07002136
2137 if (err == NO_ERROR) {
2138 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
2139 err = sensor->activate(connection.get(), true);
2140 }
2141
Aravind Akella8a969552014-09-28 17:52:41 -07002142 if (err == NO_ERROR) {
2143 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08002144
Brian Stack240d1d62019-05-17 09:49:39 -07002145 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
2146 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07002147 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
2148 }
2149
Peng Xu51224682017-03-10 16:57:27 -08002150 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2151 SensorRegistrationInfo(handle, connection->getPackageName(),
2152 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07002153 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07002154 }
2155
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002156 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07002157 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002158 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002159 }
2160 return err;
2161}
2162
Peng Xu47e96012016-03-28 17:55:56 -07002163status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002164 if (mInitCheck != NO_ERROR)
2165 return mInitCheck;
2166
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002167 Mutex::Autolock _l(mLock);
2168 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002169 if (err == NO_ERROR) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002170 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002171 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07002172
2173 }
2174 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08002175 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2176 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07002177 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002178 }
2179 return err;
2180}
2181
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002182status_t SensorService::cleanupWithoutDisable(
2183 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002184 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002185 return cleanupWithoutDisableLocked(connection, handle);
2186}
2187
2188status_t SensorService::cleanupWithoutDisableLocked(
2189 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002190 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002191 if (rec) {
2192 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07002193 if (connection->removeSensor(handle)) {
2194 BatteryService::disableSensor(connection->getUid(), handle);
2195 }
Mathias Agopianfc328812010-07-14 23:41:37 -07002196 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07002197 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07002198 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07002199 }
2200 // see if this sensor becomes inactive
2201 if (rec->removeConnection(connection)) {
2202 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002203 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002204 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07002205 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002206 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002207 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002208 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07002209}
2210
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002211status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07002212 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002213 if (mInitCheck != NO_ERROR)
2214 return mInitCheck;
2215
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002216 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002217 if (sensor == nullptr ||
2218 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00002219 return BAD_VALUE;
2220 }
2221
Mathias Agopian1cd70002010-07-21 15:59:50 -07002222 if (ns < 0)
2223 return BAD_VALUE;
2224
Mathias Agopian62569ec2011-11-07 21:21:47 -08002225 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2226 if (ns < minDelayNs) {
2227 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07002228 }
2229
Mathias Agopianf001c922010-11-11 17:58:51 -08002230 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07002231}
2232
Svetoslavb412f6e2015-04-29 16:50:41 -07002233status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
2234 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00002235 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002236 SensorDevice& dev(SensorDevice::getInstance());
2237 const int halVersion = dev.getHalDeviceVersion();
2238 status_t err(NO_ERROR);
2239 Mutex::Autolock _l(mLock);
2240 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07002241 for (int handle : connection->getActiveSensorHandles()) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002242 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002243 if (sensor == nullptr) {
2244 continue;
2245 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002246 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
2247 ALOGE("flush called on a one-shot sensor");
2248 err = INVALID_OPERATION;
2249 continue;
2250 }
Aravind Akella8493b792014-09-08 15:45:47 -07002251 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002252 // For older devices just increment pending flush count which will send a trivial
2253 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07002254 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
2255 ALOGE("flush called on an inaccessible sensor");
2256 err = INVALID_OPERATION;
2257 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002258 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002259 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
2260 err = INVALID_OPERATION;
2261 continue;
2262 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002263 status_t err_flush = sensor->flush(connection.get(), handle);
2264 if (err_flush == NO_ERROR) {
2265 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07002266 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002267 }
2268 err = (err_flush != NO_ERROR) ? err_flush : err;
2269 }
Aravind Akella70018042014-04-07 22:52:37 +00002270 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07002271 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07002272}
Aravind Akella70018042014-04-07 22:52:37 +00002273
Svetoslavb412f6e2015-04-29 16:50:41 -07002274bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
2275 const String16& opPackageName) {
Brian Duddie4a4d0462022-05-09 16:49:49 -07002276 // Special case for Head Tracker sensor type: currently restricted to system usage only, unless
2277 // the restriction is specially lifted for testing
2278 if (sensor.getType() == SENSOR_TYPE_HEAD_TRACKER &&
2279 !isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
2280 if (!mHtRestricted) {
2281 ALOGI("Permitting access to HT sensor type outside system (%s)",
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +00002282 String8(opPackageName).c_str());
Brian Duddie4a4d0462022-05-09 16:49:49 -07002283 } else {
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +00002284 ALOGW("%s %s a sensor (%s) as a non-system client", String8(opPackageName).c_str(),
2285 operation, sensor.getName().c_str());
Brian Duddie4a4d0462022-05-09 16:49:49 -07002286 return false;
2287 }
2288 }
2289
Brian Stack793f4642019-04-18 17:21:34 -07002290 // Check if a permission is required for this sensor
2291 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00002292 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07002293 }
2294
Brian Stack793f4642019-04-18 17:21:34 -07002295 const int32_t opCode = sensor.getRequiredAppOp();
Brian Duddie457e6392020-06-19 11:38:29 -07002296 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07002297
Brian Stack793f4642019-04-18 17:21:34 -07002298 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07002299 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
2300 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
2301 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
2302 // Allow access to step sensors if the application targets pre-Q, which is before the
2303 // requirement to hold the AR permission to access Step Counter and Step Detector events
2304 // was introduced.
2305 canAccess = true;
Rocky Fangcb142de2024-04-12 19:25:27 +00002306 } else if (IPCThreadState::self()->getCallingUid() == AID_SYSTEM) {
2307 // Allow access if it is requested from system.
2308 canAccess = true;
Brian Duddie457e6392020-06-19 11:38:29 -07002309 } else if (hasPermissionForSensor(sensor)) {
Rocky Fangcb142de2024-04-12 19:25:27 +00002310 // Ensure that the AppOp is allowed, or that there is no necessary app op
2311 // for the sensor
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002312 if (opCode >= 0) {
Rocky Fangcb142de2024-04-12 19:25:27 +00002313 const int32_t appOpMode =
2314 sAppOpsManager.checkOp(opCode, IPCThreadState::self()->getCallingUid(),
2315 opPackageName);
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002316 canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
2317 } else {
Brian Stack793f4642019-04-18 17:21:34 -07002318 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07002319 }
Brian Stack793f4642019-04-18 17:21:34 -07002320 }
2321
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002322 if (!canAccess) {
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +00002323 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).c_str(),
2324 operation, sensor.getName().c_str(), sensor.getRequiredPermission().c_str());
Brian Stack793f4642019-04-18 17:21:34 -07002325 }
2326
2327 return canAccess;
2328}
2329
2330bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07002331 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07002332 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07002333
2334 // Runtime permissions can't use the cache as they may change.
2335 if (sensor.isRequiredPermissionRuntime()) {
2336 hasPermission = checkPermission(String16(requiredPermission),
matthuang65794462022-03-24 16:02:57 +08002337 IPCThreadState::self()->getCallingPid(),
2338 IPCThreadState::self()->getCallingUid(),
2339 /*logPermissionFailure=*/ false);
Aravind Akella70018042014-04-07 22:52:37 +00002340 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002341 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
2342 }
Brian Stack793f4642019-04-18 17:21:34 -07002343 return hasPermission;
2344}
Svetoslavb412f6e2015-04-29 16:50:41 -07002345
Brian Stack793f4642019-04-18 17:21:34 -07002346int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Rocky Fang47a7a4a2023-12-11 22:30:30 +00002347 // Don't query the SDK version for the ISensorManager descriptor as it
2348 // doesn't have one. This descriptor tends to be used for VNDK clients, but
2349 // can technically be set by anyone so don't give it elevated privileges.
2350 bool isVNDK = opPackageName.startsWith(sSensorInterfaceDescriptorPrefix) &&
2351 opPackageName.contains(String16("@"));
2352 if (isVNDK) {
Anthony Stange07eb4212020-08-28 14:50:28 -04002353 return -1;
2354 }
2355
Brian Stack793f4642019-04-18 17:21:34 -07002356 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2357 int targetSdkVersion = -1;
2358 auto entry = sPackageTargetVersion.find(opPackageName);
2359 if (entry != sPackageTargetVersion.end()) {
2360 targetSdkVersion = entry->second;
2361 } else {
2362 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2363 if (binder != nullptr) {
2364 sp<content::pm::IPackageManagerNative> packageManager =
2365 interface_cast<content::pm::IPackageManagerNative>(binder);
2366 if (packageManager != nullptr) {
2367 binder::Status status = packageManager->getTargetSdkVersionForPackage(
2368 opPackageName, &targetSdkVersion);
2369 if (!status.isOk()) {
2370 targetSdkVersion = -1;
2371 }
2372 }
Svetoslavb412f6e2015-04-29 16:50:41 -07002373 }
Brian Stack793f4642019-04-18 17:21:34 -07002374 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07002375 }
Brian Stack793f4642019-04-18 17:21:34 -07002376 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00002377}
2378
Brian Duddie0d4ac562022-05-23 17:47:50 -07002379void SensorService::resetTargetSdkVersionCache(const String16& opPackageName) {
2380 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2381 auto iter = sPackageTargetVersion.find(opPackageName);
2382 if (iter != sPackageTargetVersion.end()) {
2383 sPackageTargetVersion.erase(iter);
2384 }
2385}
2386
Anthony Stangec1608152023-01-06 21:14:46 +00002387bool SensorService::getTargetOperatingMode(const std::string &inputString, Mode *targetModeOut) {
2388 if (inputString == std::string("restrict")) {
2389 *targetModeOut = RESTRICTED;
2390 return true;
2391 }
2392 if (inputString == std::string("enable")) {
2393 *targetModeOut = NORMAL;
2394 return true;
2395 }
2396 if (inputString == std::string("data_injection")) {
2397 *targetModeOut = DATA_INJECTION;
2398 return true;
2399 }
2400 if (inputString == std::string("replay_data_injection")) {
2401 *targetModeOut = REPLAY_DATA_INJECTION;
2402 return true;
2403 }
Mark Wheatley8f285d92023-07-07 20:07:18 +00002404 if (inputString == std::string("hal_bypass_replay_data_injection")) {
2405 *targetModeOut = HAL_BYPASS_REPLAY_DATA_INJECTION;
2406 return true;
2407 }
Anthony Stangec1608152023-01-06 21:14:46 +00002408 return false;
2409}
2410
2411status_t SensorService::changeOperatingMode(const Vector<String16>& args,
2412 Mode targetOperatingMode) {
2413 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2414 SensorDevice& dev(SensorDevice::getInstance());
2415 if (mCurrentOperatingMode == targetOperatingMode) {
2416 return NO_ERROR;
2417 }
2418 if (targetOperatingMode != NORMAL && args.size() < 2) {
2419 return INVALID_OPERATION;
2420 }
2421 switch (targetOperatingMode) {
2422 case NORMAL:
2423 // If currently in restricted mode, reset back to NORMAL mode else ignore.
2424 if (mCurrentOperatingMode == RESTRICTED) {
2425 mCurrentOperatingMode = NORMAL;
2426 // enable sensors and recover all sensor direct report
2427 enableAllSensorsLocked(&connLock);
2428 }
2429 if (mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
2430 dev.disableAllSensors();
2431 }
2432 if (mCurrentOperatingMode == DATA_INJECTION ||
Mark Wheatley8f285d92023-07-07 20:07:18 +00002433 mCurrentOperatingMode == REPLAY_DATA_INJECTION ||
2434 mCurrentOperatingMode == HAL_BYPASS_REPLAY_DATA_INJECTION) {
Anthony Stangec1608152023-01-06 21:14:46 +00002435 resetToNormalModeLocked();
2436 }
2437 mAllowListedPackage.clear();
2438 return status_t(NO_ERROR);
2439 case RESTRICTED:
2440 // If in any mode other than normal, ignore.
2441 if (mCurrentOperatingMode != NORMAL) {
2442 return INVALID_OPERATION;
2443 }
2444
2445 mCurrentOperatingMode = RESTRICTED;
2446 // temporarily stop all sensor direct report and disable sensors
2447 disableAllSensorsLocked(&connLock);
Tomasz Wasilczykd89f6092023-08-24 16:57:29 +00002448 mAllowListedPackage = String8(args[1]);
Anthony Stangec1608152023-01-06 21:14:46 +00002449 return status_t(NO_ERROR);
Mark Wheatley8f285d92023-07-07 20:07:18 +00002450 case HAL_BYPASS_REPLAY_DATA_INJECTION:
2451 FALLTHROUGH_INTENDED;
Anthony Stangec1608152023-01-06 21:14:46 +00002452 case REPLAY_DATA_INJECTION:
2453 if (SensorServiceUtil::isUserBuild()) {
2454 return INVALID_OPERATION;
2455 }
2456 FALLTHROUGH_INTENDED;
2457 case DATA_INJECTION:
2458 if (mCurrentOperatingMode == NORMAL) {
2459 dev.disableAllSensors();
Mark Wheatley8f285d92023-07-07 20:07:18 +00002460 status_t err = NO_ERROR;
2461 if (targetOperatingMode == HAL_BYPASS_REPLAY_DATA_INJECTION) {
2462 // Set SensorDevice to HAL_BYPASS_REPLAY_DATA_INJECTION_MODE. This value is not
2463 // injected into the HAL, nor will any events be injected into the HAL
2464 err = dev.setMode(HAL_BYPASS_REPLAY_DATA_INJECTION);
2465 } else {
2466 // Otherwise use DATA_INJECTION here since this value goes to the HAL and the HAL
2467 // doesn't have an understanding of replay vs. normal data injection.
2468 err = dev.setMode(DATA_INJECTION);
2469 }
Anthony Stangec1608152023-01-06 21:14:46 +00002470 if (err == NO_ERROR) {
2471 mCurrentOperatingMode = targetOperatingMode;
2472 }
2473 if (err != NO_ERROR || targetOperatingMode == REPLAY_DATA_INJECTION) {
2474 // Re-enable sensors.
2475 dev.enableAllSensors();
2476 }
Tomasz Wasilczykd89f6092023-08-24 16:57:29 +00002477 mAllowListedPackage = String8(args[1]);
Anthony Stangec1608152023-01-06 21:14:46 +00002478 return NO_ERROR;
2479 } else {
2480 // Transition to data injection mode supported only from NORMAL mode.
2481 return INVALID_OPERATION;
2482 }
2483 break;
2484 default:
2485 break;
2486 }
2487 return NO_ERROR;
2488}
2489
Aravind Akella9a844cf2014-02-11 18:58:52 -08002490void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07002491 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2492 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08002493}
2494
Brian Duddie967ce172019-06-10 11:08:27 -07002495void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002496 if (!mWakeLockAcquired) {
2497 return;
2498 }
2499 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07002500 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
2501 if (connection->needsWakeLock()) {
2502 releaseLock = false;
2503 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08002504 }
2505 }
2506 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07002507 setWakeLockAcquiredLocked(false);
2508 }
2509}
2510
2511void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
2512 Mutex::Autolock _l(mLock);
2513 connection->writeToSocketFromCache();
2514 if (connection->needsWakeLock()) {
2515 setWakeLockAcquiredLocked(true);
2516 }
2517}
2518
Anthony Stangecd01ec12023-01-06 18:35:13 +00002519bool SensorService::isAllowListedPackage(const String8& packageName) {
Tomasz Wasilczyk83aa0ab2023-08-11 00:06:51 +00002520 return (packageName.contains(mAllowListedPackage.c_str()));
Aravind Akella4949c502015-02-11 15:54:35 -08002521}
2522
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002523bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08002524 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07002525 String8 package(opPackageName);
Anthony Stangecd01ec12023-01-06 18:35:13 +00002526 return !isAllowListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07002527 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002528 return false;
Peng Xue36e3472016-11-03 11:57:10 -07002529}
2530
Svet Ganove752a5c2018-01-15 17:14:20 -08002531void SensorService::UidPolicy::registerSelf() {
2532 ActivityManager am;
2533 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
2534 | ActivityManager::UID_OBSERVER_IDLE
2535 | ActivityManager::UID_OBSERVER_ACTIVE,
2536 ActivityManager::PROCESS_STATE_UNKNOWN,
2537 String16("android"));
2538}
2539
2540void SensorService::UidPolicy::unregisterSelf() {
2541 ActivityManager am;
2542 am.unregisterUidObserver(this);
2543}
2544
2545void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
2546 onUidIdle(uid, disabled);
2547}
2548
2549void SensorService::UidPolicy::onUidActive(uid_t uid) {
2550 {
2551 Mutex::Autolock _l(mUidLock);
2552 mActiveUids.insert(uid);
2553 }
2554 sp<SensorService> service = mService.promote();
2555 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002556 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002557 }
2558}
2559
2560void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
2561 bool deleted = false;
2562 {
2563 Mutex::Autolock _l(mUidLock);
2564 if (mActiveUids.erase(uid) > 0) {
2565 deleted = true;
2566 }
2567 }
2568 if (deleted) {
2569 sp<SensorService> service = mService.promote();
2570 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002571 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002572 }
2573 }
2574}
2575
2576void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
2577 updateOverrideUid(uid, active, true);
2578}
2579
2580void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
2581 updateOverrideUid(uid, false, false);
2582}
2583
2584void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
2585 bool wasActive = false;
2586 bool isActive = false;
2587 {
2588 Mutex::Autolock _l(mUidLock);
2589 wasActive = isUidActiveLocked(uid);
2590 mOverrideUids.erase(uid);
2591 if (insert) {
2592 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2593 }
2594 isActive = isUidActiveLocked(uid);
2595 }
2596 if (wasActive != isActive) {
2597 sp<SensorService> service = mService.promote();
2598 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002599 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002600 }
2601 }
2602}
2603
2604bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2605 // Non-app UIDs are considered always active
2606 if (uid < FIRST_APPLICATION_UID) {
2607 return true;
2608 }
2609 Mutex::Autolock _l(mUidLock);
2610 return isUidActiveLocked(uid);
2611}
2612
2613bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2614 // Non-app UIDs are considered always active
2615 if (uid < FIRST_APPLICATION_UID) {
2616 return true;
2617 }
2618 auto it = mOverrideUids.find(uid);
2619 if (it != mOverrideUids.end()) {
2620 return it->second;
2621 }
2622 return mActiveUids.find(uid) != mActiveUids.end();
2623}
2624
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002625bool SensorService::isUidActive(uid_t uid) {
2626 return mUidPolicy->isUidActive(uid);
2627}
2628
Anh Phamaf91a912021-02-10 14:10:53 +01002629bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2630 int targetSdk = getTargetSdkVersion(opPackageName);
Anh Phama5538232021-06-23 08:41:11 +02002631 bool hasSamplingRatePermission = checkPermission(sAccessHighSensorSamplingRatePermission,
2632 IPCThreadState::self()->getCallingPid(),
matthuang65794462022-03-24 16:02:57 +08002633 IPCThreadState::self()->getCallingUid(),
2634 /*logPermissionFailure=*/ false);
Anh Phamaf91a912021-02-10 14:10:53 +01002635 if (targetSdk < __ANDROID_API_S__ ||
2636 (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2637 return false;
2638 }
2639 return true;
2640}
2641
Anh Pham3dae77f2021-06-11 16:24:37 +02002642/**
2643 * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS
2644 * permission.
2645 *
2646 * This needs to be kept in sync with the list defined on the Java side
2647 * in frameworks/base/core/java/android/hardware/SystemSensorManager.java
2648 */
Anh Phamaf91a912021-02-10 14:10:53 +01002649bool SensorService::isSensorInCappedSet(int sensorType) {
2650 return (sensorType == SENSOR_TYPE_ACCELEROMETER
2651 || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2652 || sensorType == SENSOR_TYPE_GYROSCOPE
2653 || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2654 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2655 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2656}
2657
2658status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2659 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002660 if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2661 return OK;
2662 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002663 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002664 if (shouldCapBasedOnPermission) {
2665 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2666 if (isPackageDebuggable(opPackageName)) {
2667 return PERMISSION_DENIED;
2668 }
2669 return OK;
2670 }
Evan Severson4c197852022-01-27 10:44:27 -08002671 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002672 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2673 return OK;
2674 }
Anh Phamaf91a912021-02-10 14:10:53 +01002675 return OK;
2676}
2677
2678status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2679 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002680 if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2681 return OK;
2682 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002683 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002684 if (shouldCapBasedOnPermission) {
2685 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2686 if (isPackageDebuggable(opPackageName)) {
2687 return PERMISSION_DENIED;
2688 }
2689 return OK;
2690 }
Evan Severson4c197852022-01-27 10:44:27 -08002691 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002692 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2693 return OK;
2694 }
Anh Phamaf91a912021-02-10 14:10:53 +01002695 return OK;
2696}
2697
Michael Groover5e1f60b2018-12-04 22:34:29 -08002698void SensorService::SensorPrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002699 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002700 SensorPrivacyManager spm;
2701 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2702 spm.addSensorPrivacyListener(this);
2703}
2704
2705void SensorService::SensorPrivacyPolicy::unregisterSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002706 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002707 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002708 spm.removeSensorPrivacyListener(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -08002709}
2710
2711bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2712 return mSensorPrivacyEnabled;
2713}
2714
Evan Severson4c197852022-01-27 10:44:27 -08002715binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2716 int sensor __unused, bool enabled) {
Michael Groover5e1f60b2018-12-04 22:34:29 -08002717 mSensorPrivacyEnabled = enabled;
2718 sp<SensorService> service = mService.promote();
Anh Pham5198c992021-02-10 14:15:30 +01002719
Michael Groover5e1f60b2018-12-04 22:34:29 -08002720 if (service != nullptr) {
Evan Severson4c197852022-01-27 10:44:27 -08002721 if (enabled) {
2722 service->disableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002723 } else {
Evan Severson4c197852022-01-27 10:44:27 -08002724 service->enableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002725 }
2726 }
2727 return binder::Status::ok();
2728}
Brian Duddie967ce172019-06-10 11:08:27 -07002729
Evan Severson4c197852022-01-27 10:44:27 -08002730void SensorService::MicrophonePrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002731 AutoCallerClear acc;
Anh Pham5198c992021-02-10 14:15:30 +01002732 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002733 mSensorPrivacyEnabled =
2734 spm.isToggleSensorPrivacyEnabled(
2735 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
2736 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE)
2737 || spm.isToggleSensorPrivacyEnabled(
2738 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE,
2739 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE);
2740 spm.addToggleSensorPrivacyListener(this);
Anh Pham5198c992021-02-10 14:15:30 +01002741}
2742
Evan Severson4c197852022-01-27 10:44:27 -08002743void SensorService::MicrophonePrivacyPolicy::unregisterSelf() {
2744 AutoCallerClear acc;
2745 SensorPrivacyManager spm;
2746 spm.removeToggleSensorPrivacyListener(this);
2747}
2748
2749binder::Status SensorService::MicrophonePrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2750 int sensor, bool enabled) {
2751 if (sensor != SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE) {
2752 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002753 }
Evan Severson4c197852022-01-27 10:44:27 -08002754 mSensorPrivacyEnabled = enabled;
2755 sp<SensorService> service = mService.promote();
2756
2757 if (service != nullptr) {
2758 if (enabled) {
2759 service->capRates();
2760 } else {
2761 service->uncapRates();
2762 }
2763 }
2764 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002765}
2766
Brian Duddie967ce172019-06-10 11:08:27 -07002767SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2768 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2769 : mConnectionHolder(holder), mAutolock(mutex) {}
2770
2771template<typename ConnectionType>
2772const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2773 const SortedVector<wp<ConnectionType>>& connectionList,
2774 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2775 referenceHolder->emplace_back();
2776 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2777 for (const wp<ConnectionType>& weakConnection : connectionList){
2778 sp<ConnectionType> connection = weakConnection.promote();
2779 if (connection != nullptr) {
2780 connections.push_back(std::move(connection));
2781 }
2782 }
2783 return connections;
2784}
2785
2786const std::vector<sp<SensorService::SensorEventConnection>>&
2787 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2788 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2789 &mReferencedActiveConnections);
2790}
2791
2792const std::vector<sp<SensorService::SensorDirectConnection>>&
2793 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2794 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2795 &mReferencedDirectConnections);
2796}
2797
2798void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2799 const sp<SensorService::SensorEventConnection>& connection) {
2800 if (mActiveConnections.indexOf(connection) < 0) {
2801 mActiveConnections.add(connection);
2802 }
2803}
2804
2805void SensorService::SensorConnectionHolder::removeEventConnection(
2806 const wp<SensorService::SensorEventConnection>& connection) {
2807 mActiveConnections.remove(connection);
2808}
2809
2810void SensorService::SensorConnectionHolder::addDirectConnection(
2811 const sp<SensorService::SensorDirectConnection>& connection) {
2812 mDirectConnections.add(connection);
2813}
2814
2815void SensorService::SensorConnectionHolder::removeDirectConnection(
2816 const wp<SensorService::SensorDirectConnection>& connection) {
2817 mDirectConnections.remove(connection);
2818}
2819
2820SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2821 return ConnectionSafeAutolock(*this, mutex);
2822}
2823
Anh Phamaf91a912021-02-10 14:10:53 +01002824bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2825 bool debugMode = false;
2826 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2827 if (binder != nullptr) {
2828 sp<content::pm::IPackageManagerNative> packageManager =
2829 interface_cast<content::pm::IPackageManagerNative>(binder);
2830 if (packageManager != nullptr) {
2831 binder::Status status = packageManager->isPackageDebuggable(
2832 opPackageName, &debugMode);
2833 }
2834 }
2835 return debugMode;
2836}
Brian Duddie967ce172019-06-10 11:08:27 -07002837} // namespace android