blob: cfafc69484021c5c812c135e79d70edc946cc3a2 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Vladimir Komsiyski29d2afd2022-12-06 13:24:10 +010016#include <aidl/android/hardware/sensors/ISensors.h>
Anh Phamaf91a912021-02-10 14:10:53 +010017#include <android-base/strings.h>
Brian Stack793f4642019-04-18 17:21:34 -070018#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080019#include <android/util/ProtoOutputStream.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080020#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070021#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070022#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070023#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080024#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070025#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080026#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070027#include <cutils/properties.h>
Brian Duddie0a4cebb2022-08-25 19:20:18 +000028#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070029#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070030#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080031#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070032#include <openssl/digest.h>
33#include <openssl/hmac.h>
34#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070035#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080036#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070037#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070038
Mathias Agopian787ac1b2012-09-18 18:49:18 -070039#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070040#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080041#include "GravitySensor.h"
Tyler Trephanc7b92632021-07-21 10:39:38 -070042#include "LimitedAxesImuSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080043#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070044#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080045#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070047#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048
Mathias Agopian984826c2011-05-17 22:54:42 -070049#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070050#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080051#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080052#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080053#include "SensorRecord.h"
54#include "SensorRegistrationInfo.h"
Anthony Stange9bb16702023-01-03 22:42:31 +000055#include "SensorServiceUtils.h"
Peng Xueb4d6282015-12-10 18:02:41 -080056
57#include <inttypes.h>
58#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070059#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080060#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080061#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070062#include <sys/stat.h>
63#include <sys/types.h>
64#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070065
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +020066#include <condition_variable>
Andrew Lehmer3a602572021-03-25 15:19:56 -070067#include <ctime>
68#include <future>
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +020069#include <mutex>
Anthony Stangec1608152023-01-06 21:14:46 +000070#include <string>
Andrew Lehmer3a602572021-03-25 15:19:56 -070071
Svet Ganove752a5c2018-01-15 17:14:20 -080072#include <private/android_filesystem_config.h>
73
Andrew Lehmer3a602572021-03-25 15:19:56 -070074using namespace std::chrono_literals;
75
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 =
94 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;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700338 case SENSOR_TYPE_GRAVITY:
339 case SENSOR_TYPE_LINEAR_ACCELERATION:
340 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700341 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
342 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
343 if (IGNORE_HARDWARE_FUSION) {
344 useThisSensor = false;
345 } else {
346 virtualSensorsNeeds &= ~(1<<list[i].type);
347 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700348 break;
Arthur Ishiguro2fd90a72021-11-12 17:24:41 +0000349 default:
350 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700351 }
Peng Xuf66684a2015-07-23 11:41:53 -0700352 if (useThisSensor) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700353 if (list[i].type == SENSOR_TYPE_PROXIMITY) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100354 auto s = std::make_shared<ProximitySensor>(list[i], *this);
355 const int handle = s->getSensor().getHandle();
356 if (registerSensor(std::move(s))) {
357 mProxSensorHandles.push_back(handle);
358 }
Andrew Lehmer3a602572021-03-25 15:19:56 -0700359 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100360 registerSensor(std::make_shared<HardwareSensor>(list[i]));
Andrew Lehmer3a602572021-03-25 15:19:56 -0700361 }
Peng Xuf66684a2015-07-23 11:41:53 -0700362 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700363 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700364
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700365 // it's safe to instantiate the SensorFusion object here
366 // (it wants to be instantiated after h/w sensors have been
367 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700368 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700369
Tyler Trephanc7b92632021-07-21 10:39:38 -0700370 if ((hasGyro || hasGyroUncalibrated) && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700371 // Add Android virtual sensors if they're not already
372 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700373 bool needRotationVector =
374 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100375 registerVirtualSensor(std::make_shared<RotationVectorSensor>(),
376 /* isDebug= */ !needRotationVector);
377 registerVirtualSensor(std::make_shared<OrientationSensor>(),
378 /* isDebug= */ !needRotationVector);
Mathias Agopian03193062013-05-10 19:32:39 -0700379
Peng Xu0cc8f802016-04-05 23:46:03 -0700380 // virtual debugging sensors are not for user
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100381 registerVirtualSensor(std::make_shared<CorrectedGyroSensor>(list, count),
382 /* isDebug= */ true);
383 registerVirtualSensor(std::make_shared<GyroDriftSensor>(), /* isDebug= */ true);
Mathias Agopian33264862012-06-28 19:46:54 -0700384 }
385
Tyler Trephanc7b92632021-07-21 10:39:38 -0700386 if (hasAccel && (hasGyro || hasGyroUncalibrated)) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700387 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100388 registerVirtualSensor(std::make_shared<GravitySensor>(list, count),
389 /* isDebug= */ !needGravitySensor);
Peng Xuf66684a2015-07-23 11:41:53 -0700390
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800391 bool needLinearAcceleration =
392 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100393 registerVirtualSensor(std::make_shared<LinearAccelerationSensor>(list, count),
394 /* isDebug= */ !needLinearAcceleration);
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800395
Peng Xu0cc8f802016-04-05 23:46:03 -0700396 bool needGameRotationVector =
397 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100398 registerVirtualSensor(std::make_shared<GameRotationVectorSensor>(),
399 /* isDebug= */ !needGameRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700400 }
401
402 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700403 bool needGeoMagRotationVector =
404 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100405 registerVirtualSensor(std::make_shared<GeoMagRotationVectorSensor>(),
406 /* isDebug= */ !needGeoMagRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700407 }
408
Tyler Trephanc7b92632021-07-21 10:39:38 -0700409 if (isAutomotive()) {
410 if (hasAccel) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100411 registerVirtualSensor(
412 std::make_shared<LimitedAxesImuSensor>(
413 list, count, SENSOR_TYPE_ACCELEROMETER));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700414 }
415
416 if (hasGyro) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100417 registerVirtualSensor(
418 std::make_shared<LimitedAxesImuSensor>(
419 list, count, SENSOR_TYPE_GYROSCOPE));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700420 }
421
422 if (hasAccelUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100423 registerVirtualSensor(
424 std::make_shared<LimitedAxesImuSensor>(
425 list, count, SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700426 }
427
428 if (hasGyroUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100429 registerVirtualSensor(
430 std::make_shared<LimitedAxesImuSensor>(
431 list, count, SENSOR_TYPE_GYROSCOPE_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700432 }
433 }
434
Aravind Akella5466c3d2014-08-22 16:11:10 -0700435 // Check if the device really supports batching by looking at the FIFO event
436 // counts for each sensor.
437 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700438 mSensors.forEachSensor(
439 [&batchingSupported] (const Sensor& s) -> bool {
440 if (s.getFifoMaxEventCount() > 0) {
441 batchingSupported = true;
442 }
443 return !batchingSupported;
444 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700445
446 if (batchingSupported) {
447 // Increase socket buffer size to a max of 100 KB for batching capabilities.
448 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
449 } else {
450 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
451 }
452
453 // Compare the socketBufferSize value against the system limits and limit
454 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700455 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
456 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700457 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700458 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700459 size_t maxSystemSocketBufferSize;
460 sscanf(line, "%zu", &maxSystemSocketBufferSize);
461 if (mSocketBufferSize > maxSystemSocketBufferSize) {
462 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700463 }
464 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700465 if (fp) {
466 fclose(fp);
467 }
468
Aravind Akella9a844cf2014-02-11 18:58:52 -0800469 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700470 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700471 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
472 mSensorEventBuffer = new sensors_event_t[minBufferSize];
473 mSensorEventScratch = new sensors_event_t[minBufferSize];
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +0200474 mRuntimeSensorEventBuffer = nullptr;
Peng Xueb059472016-08-12 16:39:44 -0700475 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700476 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700477
Aravind Akella18d6d512015-06-18 14:18:28 -0700478 mNextSensorRegIndex = 0;
479 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
480 mLastNSensorRegistrations.push();
481 }
482
483 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700484 mAckReceiver = new SensorEventAckReceiver(this);
485 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700486 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700487
488 // priority can only be changed after run
489 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800490
491 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800492 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800493
494 // Start watching sensor privacy changes
495 mSensorPrivacyPolicy->registerSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800496
497 // Start watching mic sensor privacy changes
498 mMicSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800499 }
500 }
501}
502
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700503void SensorService::onUidStateChanged(uid_t uid, UidState state) {
504 SensorDevice& dev(SensorDevice::getInstance());
505
Brian Duddie967ce172019-06-10 11:08:27 -0700506 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700507 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700508 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700509 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700510 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700511 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700512
513 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
514 if (conn->getUid() == uid) {
515 // Update sensor subscriptions if needed
516 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
517 conn->onSensorAccessChanged(hasAccess);
518 }
519 }
Chris Kuiper587ef9b2021-10-12 16:36:43 -0700520 checkAndReportProxStateChangeLocked();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700521}
522
523bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
524 Mutex::Autolock _l(mLock);
525 return hasSensorAccessLocked(uid, opPackageName);
526}
527
528bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
529 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
530 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700531}
532
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100533bool SensorService::registerSensor(std::shared_ptr<SensorInterface> s, bool isDebug, bool isVirtual,
534 int deviceId) {
535 const int handle = s->getSensor().getHandle();
536 const int type = s->getSensor().getType();
537 if (mSensors.add(handle, std::move(s), isDebug, isVirtual, deviceId)) {
Brian Stack4baa5be2018-09-18 14:03:13 -0700538 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100539 return true;
Peng Xu0cc8f802016-04-05 23:46:03 -0700540 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100541 LOG_FATAL("Failed to register sensor with handle %d", handle);
542 return false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700543 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800544}
545
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100546bool SensorService::registerDynamicSensorLocked(std::shared_ptr<SensorInterface> s, bool isDebug) {
547 return registerSensor(std::move(s), isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800548}
549
Peng Xu6a2d3a02015-12-21 12:00:23 -0800550bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700551 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800552
553 const auto i = mRecentEvent.find(handle);
554 if (i != mRecentEvent.end()) {
555 delete i->second;
556 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800557 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700558 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800559}
560
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100561bool SensorService::registerVirtualSensor(std::shared_ptr<SensorInterface> s, bool isDebug) {
562 return registerSensor(std::move(s), isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700563}
564
Peng Xu47e96012016-03-28 17:55:56 -0700565SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800566 for (auto && entry : mRecentEvent) {
567 delete entry.second;
568 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800569 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800570 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800571 mMicSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700572}
573
574status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700575 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700576 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800577 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700578 IPCThreadState::self()->getCallingPid(),
579 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700580 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700581 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700582 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800583 return INVALID_OPERATION;
584 }
Anthony Stangec1608152023-01-06 21:14:46 +0000585 if (args.size() > 0) {
586 Mode targetOperatingMode = NORMAL;
587 std::string inputStringMode = String8(args[0]).string();
588 if (getTargetOperatingMode(inputStringMode, &targetOperatingMode)) {
589 status_t error = changeOperatingMode(args, targetOperatingMode);
590 // Dump the latest state only if no error was encountered.
591 if (error != NO_ERROR) {
592 return error;
593 }
Aravind Akella444f2672015-05-07 12:40:52 -0700594 }
Anthony Stangec1608152023-01-06 21:14:46 +0000595 }
Peng Xue36e3472016-11-03 11:57:10 -0700596
Anthony Stangec1608152023-01-06 21:14:46 +0000597 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
598 // Run the following logic if a transition isn't requested above based on the input
599 // argument parsing.
600 if (args.size() == 1 && args[0] == String16("--proto")) {
Mike Ma24743862020-01-29 00:36:55 -0800601 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700602 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700603 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700604 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700605 } else {
606 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700607 //
Brian Stack51498e62018-10-03 10:52:21 -0700608 timespec curTime;
609 clock_gettime(CLOCK_REALTIME, &curTime);
610 struct tm* timeinfo = localtime(&(curTime.tv_sec));
611 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
612 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800613 result.append("Sensor Device:\n");
614 result.append(SensorDevice::getInstance().dump().c_str());
615
616 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700617 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700618
Peng Xu6a2d3a02015-12-21 12:00:23 -0800619 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700620 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700621
Peng Xu0cc8f802016-04-05 23:46:03 -0700622 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800623 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100624 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
625 if (!i.second->isEmpty() && s != nullptr) {
Peng Xufba3c112016-09-08 12:36:59 -0700626 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
627 i.second->setFormat("normal");
628 } else {
629 i.second->setFormat("mask_data");
630 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800631 // if there is events and sensor does not need special permission.
632 result.appendFormat("%s: ", s->getSensor().getName().string());
633 result.append(i.second->dump().c_str());
634 }
635 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700636
Aravind Akella444f2672015-05-07 12:40:52 -0700637 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700638 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700639 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
640 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700641 if (dev.isSensorActive(handle)) {
642 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
643 getSensorName(handle).string(),
644 handle,
645 mActiveSensors.valueAt(i)->getNumConnections());
646 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700647 }
648
Andreas Gamped4036b62015-07-28 13:49:04 -0700649 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700650 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700651 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
652 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700653 result.appendFormat("Mode :");
654 switch(mCurrentOperatingMode) {
655 case NORMAL:
656 result.appendFormat(" NORMAL\n");
657 break;
658 case RESTRICTED:
Anthony Stangecd01ec12023-01-06 18:35:13 +0000659 result.appendFormat(" RESTRICTED : %s\n", mAllowListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700660 break;
661 case DATA_INJECTION:
Anthony Stangecd01ec12023-01-06 18:35:13 +0000662 result.appendFormat(" DATA_INJECTION : %s\n", mAllowListedPackage.string());
Anthony Stange9bb16702023-01-03 22:42:31 +0000663 break;
664 case REPLAY_DATA_INJECTION:
665 result.appendFormat(" REPLAY_DATA_INJECTION : %s\n",
Anthony Stangecd01ec12023-01-06 18:35:13 +0000666 mAllowListedPackage.string());
Anthony Stange9bb16702023-01-03 22:42:31 +0000667 break;
668 default:
669 result.appendFormat(" UNKNOWN\n");
670 break;
Mathias Agopianba02cd22013-07-03 16:20:57 -0700671 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800672 result.appendFormat("Sensor Privacy: %s\n",
673 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700674
Brian Duddie967ce172019-06-10 11:08:27 -0700675 const auto& activeConnections = connLock.getActiveConnections();
676 result.appendFormat("%zd active connections\n", activeConnections.size());
677 for (size_t i=0 ; i < activeConnections.size() ; i++) {
678 result.appendFormat("Connection Number: %zu \n", i);
679 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700680 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700681
Brian Duddie967ce172019-06-10 11:08:27 -0700682 const auto& directConnections = connLock.getDirectConnections();
683 result.appendFormat("%zd direct connections\n", directConnections.size());
684 for (size_t i = 0 ; i < directConnections.size() ; i++) {
685 result.appendFormat("Direct connection %zu:\n", i);
686 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700687 }
688
Aravind Akella18d6d512015-06-18 14:18:28 -0700689 result.appendFormat("Previous Registrations:\n");
690 // Log in the reverse chronological order.
691 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
692 SENSOR_REGISTRATIONS_BUF_SIZE;
693 const int startIndex = currentIndex;
694 do {
695 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
696 if (SensorRegistrationInfo::isSentinel(reg_info)) {
697 // Ignore sentinel, proceed to next item.
698 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
699 SENSOR_REGISTRATIONS_BUF_SIZE;
700 continue;
701 }
Peng Xu51224682017-03-10 16:57:27 -0800702 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700703 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
704 SENSOR_REGISTRATIONS_BUF_SIZE;
705 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700706 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700707 }
708 write(fd, result.string(), result.size());
709 return NO_ERROR;
710}
711
Mike Ma24743862020-01-29 00:36:55 -0800712/**
713 * Dump debugging information as android.service.SensorServiceProto protobuf message using
714 * ProtoOutputStream.
715 *
716 * See proto definition and some notes about ProtoOutputStream in
717 * frameworks/base/core/proto/android/service/sensor_service.proto
718 */
719status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
720 using namespace service::SensorServiceProto;
721 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800722 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
723 if (!mSensors.hasAnySensor()) {
724 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
725 }
Mike Ma24743862020-01-29 00:36:55 -0800726 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
727
728 timespec curTime;
729 clock_gettime(CLOCK_REALTIME, &curTime);
730 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
731
732 // Write SensorDeviceProto
733 uint64_t token = proto.start(SENSOR_DEVICE);
734 SensorDevice::getInstance().dump(&proto);
735 proto.end(token);
736
737 // Write SensorListProto
738 token = proto.start(SENSORS);
739 mSensors.dump(&proto);
740 proto.end(token);
741
742 // Write SensorFusionProto
743 token = proto.start(FUSION_STATE);
744 SensorFusion::getInstance().dump(&proto);
745 proto.end(token);
746
747 // Write SensorEventsProto
748 token = proto.start(SENSOR_EVENTS);
749 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100750 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
751 if (!i.second->isEmpty() && s != nullptr) {
Mike Ma24743862020-01-29 00:36:55 -0800752 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
753 "normal" : "mask_data");
754 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
755 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
756 std::string(s->getSensor().getName().string()));
757 i.second->dump(&proto);
758 proto.end(mToken);
759 }
760 }
761 proto.end(token);
762
763 // Write ActiveSensorProto
764 SensorDevice& dev = SensorDevice::getInstance();
765 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
766 int handle = mActiveSensors.keyAt(i);
767 if (dev.isSensorActive(handle)) {
768 token = proto.start(ACTIVE_SENSORS);
769 proto.write(service::ActiveSensorProto::NAME,
770 std::string(getSensorName(handle).string()));
771 proto.write(service::ActiveSensorProto::HANDLE, handle);
772 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
773 int(mActiveSensors.valueAt(i)->getNumConnections()));
774 proto.end(token);
775 }
776 }
777
778 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
779 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
780 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
781
782 switch(mCurrentOperatingMode) {
783 case NORMAL:
784 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
785 break;
786 case RESTRICTED:
787 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
Anthony Stangecd01ec12023-01-06 18:35:13 +0000788 proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.string()));
Mike Ma24743862020-01-29 00:36:55 -0800789 break;
790 case DATA_INJECTION:
791 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
Anthony Stangecd01ec12023-01-06 18:35:13 +0000792 proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.string()));
Mike Ma24743862020-01-29 00:36:55 -0800793 break;
794 default:
795 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
796 }
797 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
798
799 // Write repeated SensorEventConnectionProto
800 const auto& activeConnections = connLock->getActiveConnections();
801 for (size_t i = 0; i < activeConnections.size(); i++) {
802 token = proto.start(ACTIVE_CONNECTIONS);
803 activeConnections[i]->dump(&proto);
804 proto.end(token);
805 }
806
807 // Write repeated SensorDirectConnectionProto
808 const auto& directConnections = connLock->getDirectConnections();
809 for (size_t i = 0 ; i < directConnections.size() ; i++) {
810 token = proto.start(DIRECT_CONNECTIONS);
811 directConnections[i]->dump(&proto);
812 proto.end(token);
813 }
814
815 // Write repeated SensorRegistrationInfoProto
816 const int startIndex = mNextSensorRegIndex;
817 int curr = startIndex;
818 do {
819 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
820 if (SensorRegistrationInfo::isSentinel(reg_info)) {
821 // Ignore sentinel, proceed to next item.
822 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
823 continue;
824 }
825 token = proto.start(PREVIOUS_REGISTRATIONS);
826 reg_info.dump(&proto);
827 proto.end(token);
828 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
829 } while (startIndex != curr);
830
831 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
832}
833
Michael Groover5e1f60b2018-12-04 22:34:29 -0800834void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700835 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
836 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800837}
838
Brian Duddie967ce172019-06-10 11:08:27 -0700839void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800840 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700841 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
842 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
843 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800844 }
845 dev.disableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700846 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800847 // Clear all pending flush connections for all active sensors. If one of the active
848 // connections has called flush() and the underlying sensor has been disabled before a
849 // flush complete event is returned, we need to remove the connection from this queue.
850 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
851 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
852 }
853}
854
855void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700856 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
857 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800858}
859
Brian Duddie967ce172019-06-10 11:08:27 -0700860void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800861 // sensors should only be enabled if the operating state is not restricted and sensor
862 // privacy is not enabled.
863 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
864 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
865 mCurrentOperatingMode,
866 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
867 return;
868 }
869 SensorDevice& dev(SensorDevice::getInstance());
870 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700871 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
872 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
873 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800874 }
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700875 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800876}
877
Evan Severson4c197852022-01-27 10:44:27 -0800878void SensorService::capRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100879 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
880 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800881 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100882 }
883
884 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800885 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100886 }
887}
888
Evan Severson4c197852022-01-27 10:44:27 -0800889void SensorService::uncapRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100890 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
891 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800892 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100893 }
894
895 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800896 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100897 }
898}
Brian Duddie967ce172019-06-10 11:08:27 -0700899
Svet Ganove752a5c2018-01-15 17:14:20 -0800900// NOTE: This is a remote API - make sure all args are validated
901status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
902 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
903 return PERMISSION_DENIED;
904 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700905 if (args.size() == 0) {
906 return BAD_INDEX;
907 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800908 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
909 return BAD_VALUE;
910 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700911 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800912 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700913 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800914 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700915 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800916 return handleGetUidState(args, out, err);
Brian Duddie4a4d0462022-05-09 16:49:49 -0700917 } else if (args[0] == String16("unrestrict-ht")) {
918 mHtRestricted = false;
919 return NO_ERROR;
920 } else if (args[0] == String16("restrict-ht")) {
921 mHtRestricted = true;
922 return NO_ERROR;
Svet Ganove752a5c2018-01-15 17:14:20 -0800923 } else if (args.size() == 1 && args[0] == String16("help")) {
924 printHelp(out);
925 return NO_ERROR;
926 }
927 printHelp(err);
928 return BAD_VALUE;
929}
930
Tanmay Patild33a1822019-04-11 18:38:55 -0700931static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800932 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700933 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800934 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700935 ALOGE("Unknown package: '%s'", String8(packageName).string());
936 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800937 return BAD_VALUE;
938 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700939
940 if (userId < 0) {
941 ALOGE("Invalid user: %d", userId);
942 dprintf(err, "Invalid user: %d\n", userId);
943 return BAD_VALUE;
944 }
945
946 uid = multiuser_get_uid(userId, uid);
947 return NO_ERROR;
948}
949
950status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
951 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
952 if (!(args.size() == 3 || args.size() == 5)) {
953 printHelp(err);
954 return BAD_VALUE;
955 }
956
Svet Ganove752a5c2018-01-15 17:14:20 -0800957 bool active = false;
958 if (args[2] == String16("active")) {
959 active = true;
960 } else if ((args[2] != String16("idle"))) {
961 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
962 return BAD_VALUE;
963 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700964
965 int userId = 0;
966 if (args.size() == 5 && args[3] == String16("--user")) {
967 userId = atoi(String8(args[4]));
968 }
969
970 uid_t uid;
971 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
972 return BAD_VALUE;
973 }
974
Svet Ganove752a5c2018-01-15 17:14:20 -0800975 mUidPolicy->addOverrideUid(uid, active);
976 return NO_ERROR;
977}
978
979status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700980 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
981 if (!(args.size() == 2 || args.size() == 4)) {
982 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800983 return BAD_VALUE;
984 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700985
986 int userId = 0;
987 if (args.size() == 4 && args[2] == String16("--user")) {
988 userId = atoi(String8(args[3]));
989 }
990
991 uid_t uid;
992 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
993 return BAD_VALUE;
994 }
995
Svet Ganove752a5c2018-01-15 17:14:20 -0800996 mUidPolicy->removeOverrideUid(uid);
997 return NO_ERROR;
998}
999
1000status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -07001001 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1002 if (!(args.size() == 2 || args.size() == 4)) {
1003 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -08001004 return BAD_VALUE;
1005 }
Tanmay Patild33a1822019-04-11 18:38:55 -07001006
1007 int userId = 0;
1008 if (args.size() == 4 && args[2] == String16("--user")) {
1009 userId = atoi(String8(args[3]));
1010 }
1011
1012 uid_t uid;
1013 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1014 return BAD_VALUE;
1015 }
1016
Svet Ganove752a5c2018-01-15 17:14:20 -08001017 if (mUidPolicy->isUidActive(uid)) {
1018 return dprintf(out, "active\n");
1019 } else {
1020 return dprintf(out, "idle\n");
1021 }
1022}
1023
1024status_t SensorService::printHelp(int out) {
1025 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -07001026 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1027 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1028 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -08001029 " help print this message\n");
1030}
1031
Peng Xu0cc8f802016-04-05 23:46:03 -07001032//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -08001033void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001034 sensors_event_t const* buffer, const int count) {
1035 for (int i=0 ; i<count ; i++) {
1036 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -07001037 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1038 handle = buffer[i].meta_data.sensor;
1039 }
Aravind Akella0e025c52014-06-03 19:19:57 -07001040 if (connection->hasSensor(handle)) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001041 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -07001042 // If this buffer has an event from a one_shot sensor and this connection is registered
1043 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -07001044 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -07001045 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1046 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001047 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001048 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001049
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001050 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001051 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001052}
1053
Peng Xu47e96012016-03-28 17:55:56 -07001054bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +00001055 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -07001056
Peng Xueb4d6282015-12-10 18:02:41 -08001057 // each virtual sensor could generate an event per "real" event, that's why we need to size
1058 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
1059 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -07001060 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001061 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -07001062 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001063
Mathias Agopianf001c922010-11-11 17:58:51 -08001064 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -07001065
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001066 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -07001067 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001068 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
1069 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -07001070 if(count == DEAD_OBJECT && device.isReconnecting()) {
1071 device.reconnect();
Vladimir Komsiyski574ac3e2023-07-28 07:13:46 +00001072 continue;
Brian Stack156da082018-10-01 15:58:53 -07001073 } else {
1074 ALOGE("sensor poll failed (%s)", strerror(-count));
1075 break;
1076 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001077 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001078
1079 // Reset sensors_event_t.flags to zero for all events in the buffer.
1080 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001081 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001082 }
Brian Duddie967ce172019-06-10 11:08:27 -07001083 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -07001084
Aravind Akella9a844cf2014-02-11 18:58:52 -08001085 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
1086 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
1087 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
1088 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
1089 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001090 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001091 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001092 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001093 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001094 }
1095 }
1096
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001097 if (wakeEvents > 0) {
1098 if (!mWakeLockAcquired) {
1099 setWakeLockAcquiredLocked(true);
1100 }
1101 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001102 }
Aravind Akella8493b792014-09-08 15:45:47 -07001103 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -08001104
Mathias Agopianf001c922010-11-11 17:58:51 -08001105 // handle virtual sensors
1106 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -07001107 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -07001108 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001109 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -07001110 SensorFusion& fusion(SensorFusion::getInstance());
1111 if (fusion.isEnabled()) {
1112 for (size_t i=0 ; i<size_t(count) ; i++) {
1113 fusion.process(event[i]);
1114 }
1115 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001116 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -07001117 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001118 if (count + k >= minBufferSize) {
1119 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -07001120 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001121 count, k, minBufferSize);
1122 break;
1123 }
Mathias Agopianf001c922010-11-11 17:58:51 -08001124 sensors_event_t out;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001125 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001126 if (si == nullptr) {
1127 ALOGE("handle %d is not an valid virtual sensor", handle);
1128 continue;
1129 }
1130
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001131 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -07001132 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -08001133 k++;
1134 }
1135 }
1136 }
1137 if (k) {
1138 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -07001139 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -08001140 count += k;
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +02001141 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -07001142 }
1143 }
1144 }
1145
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001146 // handle backward compatibility for RotationVector sensor
1147 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
1148 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001149 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001150 // All the 4 components of the quaternion should be available
1151 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -07001152 mSensorEventBuffer[i].data[4] = -1;
1153 }
1154 }
1155 }
1156
Brian Duddie967ce172019-06-10 11:08:27 -07001157 // Cache the list of active connections, since we use it in multiple places below but won't
1158 // modify it here
1159 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
1160
Aravind Akella8493b792014-09-08 15:45:47 -07001161 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -07001162 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
1163 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
1164 // SensorEventConnection mapped to the corresponding flush_complete_event in
1165 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -07001166 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -07001167 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
1168 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
1169 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001170 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -07001171 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
1172 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001173 }
1174 }
Peng Xu2576cb62016-01-20 00:22:09 -08001175
1176 // handle dynamic sensor meta events, process registration and unregistration of dynamic
1177 // sensor based on content of event.
1178 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
1179 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
1180 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1181 const sensor_t& dynamicSensor =
1182 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
1183 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
1184 handle, dynamicSensor.type, dynamicSensor.name);
1185
Peng Xu0cc8f802016-04-05 23:46:03 -07001186 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -08001187 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -07001188 sensor_t s = dynamicSensor;
1189 // make sure the dynamic sensor flag is set
1190 s.flags |= DYNAMIC_SENSOR_MASK;
1191 // force the handle to be consistent
1192 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -08001193
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001194 auto si = std::make_shared<HardwareSensor>(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -08001195
Peng Xu0cc8f802016-04-05 23:46:03 -07001196 // This will release hold on dynamic sensor meta, so it should be called
1197 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -07001198 device.handleDynamicSensorConnection(handle, true /*connected*/);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001199 registerDynamicSensorLocked(std::move(si));
Peng Xu47e96012016-03-28 17:55:56 -07001200 } else {
1201 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
1202 }
Peng Xu2576cb62016-01-20 00:22:09 -08001203 } else {
1204 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1205 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1206
1207 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001208 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -08001209 ALOGE("Dynamic sensor release error.");
1210 }
1211
Brian Duddie967ce172019-06-10 11:08:27 -07001212 for (const sp<SensorEventConnection>& connection : activeConnections) {
1213 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001214 }
1215 }
1216 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001217 }
1218
Aravind Akella9a844cf2014-02-11 18:58:52 -08001219 // Send our events to clients. Check the state of wake lock for each client and release the
1220 // lock if none of the clients need it.
1221 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001222 for (const sp<SensorEventConnection>& connection : activeConnections) {
1223 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +02001224 mMapFlushEventsToConnections);
Brian Duddie967ce172019-06-10 11:08:27 -07001225 needsWakeLock |= connection->needsWakeLock();
1226 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1227 // Early check for one-shot sensors.
1228 if (connection->hasOneShotSensors()) {
1229 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001230 }
1231 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001232
Aravind Akella9a844cf2014-02-11 18:58:52 -08001233 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001234 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001235 }
Aravind Akella8493b792014-09-08 15:45:47 -07001236 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001237
Steve Block3c20fbe2012-01-05 23:22:43 +00001238 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001239 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001240 return false;
1241}
1242
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +02001243void SensorService::processRuntimeSensorEvents() {
1244 size_t count = 0;
1245 const size_t maxBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
1246
1247 {
1248 std::unique_lock<std::mutex> lock(mRutimeSensorThreadMutex);
1249
1250 if (mRuntimeSensorEventQueue.empty()) {
1251 mRuntimeSensorsCv.wait(lock, [this] { return !mRuntimeSensorEventQueue.empty(); });
1252 }
1253
1254 // Pop the events from the queue into the buffer until it's empty or the buffer is full.
1255 while (!mRuntimeSensorEventQueue.empty()) {
1256 if (count >= maxBufferSize) {
1257 ALOGE("buffer too small to hold all events: count=%zd, size=%zu", count,
1258 maxBufferSize);
1259 break;
1260 }
1261 mRuntimeSensorEventBuffer[count] = mRuntimeSensorEventQueue.front();
1262 mRuntimeSensorEventQueue.pop();
1263 count++;
1264 }
1265 }
1266
1267 if (count) {
1268 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1269
1270 recordLastValueLocked(mRuntimeSensorEventBuffer, count);
1271 sortEventBuffer(mRuntimeSensorEventBuffer, count);
1272
1273 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1274 connection->sendEvents(mRuntimeSensorEventBuffer, count, /* scratch= */ nullptr,
1275 /* mapFlushEventsToConnections= */ nullptr);
1276 if (connection->hasOneShotSensors()) {
1277 cleanupAutoDisabledSensorLocked(connection, mRuntimeSensorEventBuffer, count);
1278 }
1279 }
1280 }
1281}
1282
Aravind Akella56ae4262014-07-10 16:01:10 -07001283sp<Looper> SensorService::getLooper() const {
1284 return mLooper;
1285}
1286
Aravind Akellab4373ac2014-10-29 17:55:20 -07001287void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001288 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1289 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1290 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001291 }
Brian Duddie967ce172019-06-10 11:08:27 -07001292 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001293}
1294
1295void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1296 if (acquire) {
1297 if (!mWakeLockAcquired) {
1298 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1299 mWakeLockAcquired = true;
1300 }
1301 mLooper->wake();
1302 } else {
1303 if (mWakeLockAcquired) {
1304 release_wake_lock(WAKE_LOCK_NAME);
1305 mWakeLockAcquired = false;
1306 }
1307 }
1308}
1309
Aravind Akellab4373ac2014-10-29 17:55:20 -07001310bool SensorService::isWakeLockAcquired() {
1311 Mutex::Autolock _l(mLock);
1312 return mWakeLockAcquired;
1313}
1314
Aravind Akella56ae4262014-07-10 16:01:10 -07001315bool SensorService::SensorEventAckReceiver::threadLoop() {
1316 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001317 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001318 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001319 bool wakeLockAcquired = mService->isWakeLockAcquired();
1320 int timeout = -1;
1321 if (wakeLockAcquired) timeout = 5000;
1322 int ret = looper->pollOnce(timeout);
1323 if (ret == ALOOPER_POLL_TIMEOUT) {
1324 mService->resetAllWakeLockRefCounts();
1325 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001326 } while(!Thread::exitPending());
1327 return false;
1328}
1329
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +02001330bool SensorService::RuntimeSensorHandler::threadLoop() {
1331 ALOGD("new thread RuntimeSensorHandler");
1332 do {
1333 mService->processRuntimeSensorEvents();
1334 } while (!Thread::exitPending());
1335 return false;
1336}
1337
Aravind Akella9a844cf2014-02-11 18:58:52 -08001338void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001339 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001340 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001341 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1342 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001343 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001344 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001345 }
Peng Xu2576cb62016-01-20 00:22:09 -08001346
Peng Xu6a2d3a02015-12-21 12:00:23 -08001347 auto logger = mRecentEvent.find(buffer[i].sensor);
1348 if (logger != mRecentEvent.end()) {
1349 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001350 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001351 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001352}
1353
Peng Xu47e96012016-03-28 17:55:56 -07001354void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001355 struct compar {
1356 static int cmp(void const* lhs, void const* rhs) {
1357 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1358 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001359 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001360 }
1361 };
1362 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1363}
1364
Mathias Agopian5d270722010-07-19 15:20:39 -07001365String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001366 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001367}
1368
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001369String8 SensorService::getSensorStringType(int handle) const {
1370 return mSensors.getStringType(handle);
1371}
1372
Aravind Akellab4099e72013-10-15 15:43:10 -07001373bool SensorService::isVirtualSensor(int handle) const {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001374 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001375 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001376}
1377
Aravind Akella9a844cf2014-02-11 18:58:52 -08001378bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001379 int handle = event.sensor;
1380 if (event.type == SENSOR_TYPE_META_DATA) {
1381 handle = event.meta_data.sensor;
1382 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001383 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001384 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001385}
1386
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001387int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1388 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1389 // UUID is not supported for this device.
1390 return 0;
1391 }
1392 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1393 // This sensor can be uniquely identified in the system by
1394 // the combination of its type and name.
1395 return -1;
1396 }
1397
1398 // We have a dynamic sensor.
1399
1400 if (!sHmacGlobalKeyIsValid) {
lifr3ab0a1b2021-08-06 00:14:26 +08001401 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001402 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1403 return 0;
1404 }
1405
1406 // We want each app author/publisher to get a different ID, so that the
1407 // same dynamic sensor cannot be tracked across apps by multiple
1408 // authors/publishers. So we use both our UUID and our User ID.
1409 // Note potential confusion:
1410 // UUID => Universally Unique Identifier.
1411 // UID => User Identifier.
1412 // We refrain from using "uid" except as needed by API to try to
1413 // keep this distinction clear.
1414
1415 auto appUserId = IPCThreadState::self()->getCallingUid();
1416 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1417 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1418 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1419
1420 // Now we use our key on our UUID/app combo to get the hash.
1421 uint8_t hash[EVP_MAX_MD_SIZE];
1422 unsigned int hashLen;
1423 if (HMAC(EVP_sha256(),
1424 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1425 uuidAndApp, sizeof(uuidAndApp),
1426 hash, &hashLen) == nullptr) {
lifr3ab0a1b2021-08-06 00:14:26 +08001427 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001428 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1429 return 0;
1430 }
1431
1432 int32_t id = 0;
1433 if (hashLen < sizeof(id)) {
1434 // We never expect this case, but out of paranoia, we handle it.
1435 // Our 'id' length is already quite small, we don't want the
1436 // effective length of it to be even smaller.
1437 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1438 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1439 return 0;
1440 }
1441
1442 // This is almost certainly less than all of 'hash', but it's as secure
1443 // as we can be with our current 'id' length.
1444 memcpy(&id, hash, sizeof(id));
1445
1446 // Note at the beginning of the function that we return the values of
1447 // 0 and -1 to represent special cases. As a result, we can't return
1448 // those as dynamic sensor IDs. If we happened to hash to one of those
1449 // values, we change 'id' so we report as a dynamic sensor, and not as
1450 // one of those special cases.
1451 if (id == -1) {
1452 id = -2;
1453 } else if (id == 0) {
1454 id = 1;
1455 }
1456 return id;
1457}
1458
1459void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1460 for (auto &sensor : sensorList) {
1461 int32_t id = getIdFromUuid(sensor.getUuid());
1462 sensor.setId(id);
Eric Laurente3f27df2022-01-05 19:20:32 +01001463 // The sensor UUID must always be anonymized here for non privileged clients.
1464 // There is no other checks after this point before returning to client process.
1465 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1466 sensor.anonymizeUuid();
1467 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001468 }
1469}
1470
Anh Pham4e291332021-02-10 14:17:56 +01001471Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -07001472 char value[PROPERTY_VALUE_MAX];
1473 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001474 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001475 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001476 Vector<Sensor> accessibleSensorList;
Anh Pham4e291332021-02-10 14:17:56 +01001477
Brian Duddie0d4ac562022-05-23 17:47:50 -07001478 resetTargetSdkVersionCache(opPackageName);
Anh Pham4e291332021-02-10 14:17:56 +01001479 bool isCapped = isRateCappedBasedOnPermission(opPackageName);
Aravind Akella70018042014-04-07 22:52:37 +00001480 for (size_t i = 0; i < initialSensorList.size(); i++) {
1481 Sensor sensor = initialSensorList[i];
Anh Pham4e291332021-02-10 14:17:56 +01001482 if (isCapped && isSensorInCappedSet(sensor.getType())) {
1483 sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
1484 sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
1485 }
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001486 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001487 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001488 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001489 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001490}
1491
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001492void SensorService::addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
1493 Vector<Sensor>& accessibleSensorList) {
1494 if (canAccessSensor(sensor, "can't see", opPackageName)) {
1495 accessibleSensorList.add(sensor);
1496 } else if (sensor.getType() != SENSOR_TYPE_HEAD_TRACKER) {
1497 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1498 sensor.getName().string(), sensor.getRequiredPermission().string(),
1499 sensor.getRequiredAppOp());
1500 }
1501}
1502
Peng Xu47e96012016-03-28 17:55:56 -07001503Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001504 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001505 mSensors.forEachSensor(
Brian Duddie4a4d0462022-05-09 16:49:49 -07001506 [this, &opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001507 if (sensor.isDynamicSensor()) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001508 addSensorIfAccessible(opPackageName, sensor, accessibleSensorList);
1509 }
1510 return true;
1511 });
1512 makeUuidsIntoIdsForSensorList(accessibleSensorList);
1513 return accessibleSensorList;
1514}
1515
1516Vector<Sensor> SensorService::getRuntimeSensorList(const String16& opPackageName, int deviceId) {
1517 Vector<Sensor> accessibleSensorList;
1518 mSensors.forEachEntry(
1519 [this, &opPackageName, deviceId, &accessibleSensorList] (
1520 const SensorServiceUtil::SensorList::Entry& e) -> bool {
1521 if (e.deviceId == deviceId) {
1522 addSensorIfAccessible(opPackageName, e.si->getSensor(), accessibleSensorList);
Peng Xu0cc8f802016-04-05 23:46:03 -07001523 }
1524 return true;
1525 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001526 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001527 return accessibleSensorList;
1528}
1529
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001530sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001531 int requestedMode, const String16& opPackageName, const String16& attributionTag) {
Anthony Stange9bb16702023-01-03 22:42:31 +00001532 // Only 3 modes supported for a SensorEventConnection ... NORMAL, DATA_INJECTION and
1533 // REPLAY_DATA_INJECTION.
1534 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION &&
1535 requestedMode != REPLAY_DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001536 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001537 }
Brian Duddie0d4ac562022-05-23 17:47:50 -07001538 resetTargetSdkVersionCache(opPackageName);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001539
1540 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001541 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1542 // operating in DI mode.
1543 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001544 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
Anthony Stangecd01ec12023-01-06 18:35:13 +00001545 if (!isAllowListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001546 }
1547
Mathias Agopian5307d172012-09-18 17:02:43 -07001548 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001549 pid_t pid = IPCThreadState::self()->getCallingPid();
1550
1551 String8 connPackageName =
1552 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1553 String16 connOpPackageName =
1554 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1555 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Anthony Stange9bb16702023-01-03 22:42:31 +00001556 requestedMode == DATA_INJECTION || requestedMode == REPLAY_DATA_INJECTION,
1557 connOpPackageName, attributionTag));
1558 if (requestedMode == DATA_INJECTION || requestedMode == REPLAY_DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001559 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001560 // Add the associated file descriptor to the Looper for polling whenever there is data to
1561 // be injected.
1562 result->updateLooperRegistration(mLooper);
1563 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001564 return result;
1565}
1566
Aravind Akella841a5922015-06-29 12:37:48 -07001567int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001568 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001569 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001570}
1571
Peng Xue36e3472016-11-03 11:57:10 -07001572sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001573 const String16& opPackageName, int deviceId, uint32_t size, int32_t type, int32_t format,
Peng Xue36e3472016-11-03 11:57:10 -07001574 const native_handle *resource) {
Brian Duddie0d4ac562022-05-23 17:47:50 -07001575 resetTargetSdkVersionCache(opPackageName);
Brian Duddie967ce172019-06-10 11:08:27 -07001576 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001577
Michael Groover5e1f60b2018-12-04 22:34:29 -08001578 // No new direct connections are allowed when sensor privacy is enabled
1579 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1580 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1581 return nullptr;
1582 }
1583
Peng Xue36e3472016-11-03 11:57:10 -07001584 struct sensors_direct_mem_t mem = {
1585 .type = type,
1586 .format = format,
1587 .size = size,
1588 .handle = resource,
1589 };
1590 uid_t uid = IPCThreadState::self()->getCallingUid();
1591
1592 if (mem.handle == nullptr) {
1593 ALOGE("Failed to clone resource handle");
1594 return nullptr;
1595 }
1596
1597 // check format
1598 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1599 ALOGE("Direct channel format %d is unsupported!", format);
1600 return nullptr;
1601 }
1602
1603 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001604 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1605 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001606 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001607 return nullptr;
1608 }
1609 }
1610
1611 // check specific to memory type
1612 switch(type) {
1613 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001614 if (resource->numFds < 1) {
1615 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1616 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1617 return nullptr;
1618 }
Peng Xue36e3472016-11-03 11:57:10 -07001619 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001620 if (!ashmem_valid(fd)) {
1621 ALOGE("Supplied Ashmem memory region is invalid");
1622 return nullptr;
1623 }
1624
Peng Xue36e3472016-11-03 11:57:10 -07001625 int size2 = ashmem_get_size_region(fd);
1626 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001627 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001628 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1629 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001630 return nullptr;
1631 }
1632 break;
1633 }
1634 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001635 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001636 break;
1637 default:
1638 ALOGE("Unknown direct connection memory type %d", type);
1639 return nullptr;
1640 }
1641
1642 native_handle_t *clone = native_handle_clone(resource);
1643 if (!clone) {
1644 return nullptr;
1645 }
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001646 native_handle_set_fdsan_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001647
Brian Duddie967ce172019-06-10 11:08:27 -07001648 sp<SensorDirectConnection> conn;
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001649 int channelHandle = 0;
1650 if (deviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
1651 SensorDevice& dev(SensorDevice::getInstance());
1652 channelHandle = dev.registerDirectChannel(&mem);
1653 } else {
1654 auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1655 if (runtimeSensorCallback == mRuntimeSensorCallbacks.end()) {
1656 ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1657 } else {
1658 int fd = dup(clone->data[0]);
1659 channelHandle = runtimeSensorCallback->second->onDirectChannelCreated(fd);
1660 }
1661 }
Peng Xue36e3472016-11-03 11:57:10 -07001662
1663 if (channelHandle <= 0) {
1664 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1665 } else {
1666 mem.handle = clone;
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001667 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName, deviceId);
Peng Xue36e3472016-11-03 11:57:10 -07001668 }
1669
1670 if (conn == nullptr) {
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001671 native_handle_close_with_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001672 native_handle_delete(clone);
1673 } else {
1674 // add to list of direct connections
1675 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001676 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001677 }
1678 return conn;
1679}
1680
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001681int SensorService::configureRuntimeSensorDirectChannel(
1682 int sensorHandle, const SensorDirectConnection* c, const sensors_direct_cfg_t* config) {
1683 int deviceId = c->getDeviceId();
1684 int sensorDeviceId = getDeviceIdFromHandle(sensorHandle);
1685 if (sensorDeviceId != c->getDeviceId()) {
Vladimir Komsiyski3494fd52023-03-22 10:31:22 +01001686 ALOGE("Cannot configure direct channel created for device %d with a sensor that belongs "
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001687 "to device %d", c->getDeviceId(), sensorDeviceId);
1688 return BAD_VALUE;
1689 }
1690 auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1691 if (runtimeSensorCallback == mRuntimeSensorCallbacks.end()) {
1692 ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1693 return BAD_VALUE;
1694 }
1695 return runtimeSensorCallback->second->onDirectChannelConfigured(
1696 c->getHalChannelHandle(), sensorHandle, config->rate_level);
1697}
1698
Peng Xudd5c5cb2017-03-16 17:39:43 -07001699int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001700 int32_t handle, int32_t type,
1701 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001702 Mutex::Autolock _l(mLock);
1703
Alexey Polyudov88711e82017-05-23 19:54:04 -07001704 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001705 return PERMISSION_DENIED;
1706 }
1707
1708 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001709 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001710 size_t expectSize = INT32_MAX;
1711 switch (type) {
1712 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1713 isFloat = true;
1714 expectSize = 3;
1715 break;
1716 case AINFO_LOCAL_GRAVITY:
1717 isFloat = true;
1718 expectSize = 1;
1719 break;
1720 case AINFO_DOCK_STATE:
1721 case AINFO_HIGH_PERFORMANCE_MODE:
1722 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1723 isFloat = false;
1724 expectSize = 1;
1725 break;
1726 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001727 // CUSTOM events must only contain float data; it may have variable size
1728 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1729 ints.size() ||
1730 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1731 handle < 0) {
1732 return BAD_VALUE;
1733 }
1734 isFloat = true;
1735 isCustom = true;
1736 expectSize = floats.size();
1737 break;
1738 }
1739
1740 if (!isCustom && handle != -1) {
1741 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001742 }
1743
1744 // three events: first one is begin tag, last one is end tag, the one in the middle
1745 // is the payload.
1746 sensors_event_t event[3];
1747 int64_t timestamp = elapsedRealtimeNano();
1748 for (sensors_event_t* i = event; i < event + 3; i++) {
1749 *i = (sensors_event_t) {
1750 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001751 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001752 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1753 .timestamp = timestamp++,
1754 .additional_info = (additional_info_event_t) {
1755 .serial = 0
1756 }
1757 };
1758 }
1759
1760 event[0].additional_info.type = AINFO_BEGIN;
1761 event[1].additional_info.type = type;
1762 event[2].additional_info.type = AINFO_END;
1763
1764 if (isFloat) {
1765 if (floats.size() != expectSize) {
1766 return BAD_VALUE;
1767 }
1768 for (size_t i = 0; i < expectSize; ++i) {
1769 event[1].additional_info.data_float[i] = floats[i];
1770 }
1771 } else {
1772 if (ints.size() != expectSize) {
1773 return BAD_VALUE;
1774 }
1775 for (size_t i = 0; i < expectSize; ++i) {
1776 event[1].additional_info.data_int32[i] = ints[i];
1777 }
1778 }
1779
1780 SensorDevice& dev(SensorDevice::getInstance());
1781 for (sensors_event_t* i = event; i < event + 3; i++) {
1782 int ret = dev.injectSensorData(i);
1783 if (ret != NO_ERROR) {
1784 return ret;
1785 }
1786 }
1787 return NO_ERROR;
1788}
1789
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001790status_t SensorService::resetToNormalMode() {
1791 Mutex::Autolock _l(mLock);
1792 return resetToNormalModeLocked();
1793}
1794
1795status_t SensorService::resetToNormalModeLocked() {
1796 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001797 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301798 if (err == NO_ERROR) {
1799 mCurrentOperatingMode = NORMAL;
1800 dev.enableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001801 checkAndReportProxStateChangeLocked();
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301802 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001803 return err;
1804}
1805
Peng Xu47e96012016-03-28 17:55:56 -07001806void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001807 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001808 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001809 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001810 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001811 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001812 int handle = mActiveSensors.keyAt(i);
1813 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001814 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001815 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001816 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001817 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001818 } else {
1819 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001820 }
Brian Duddie7be85572021-12-21 10:44:55 -08001821 if (c->removeSensor(handle)) {
1822 BatteryService::disableSensor(c->getUid(), handle);
1823 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001824 }
1825 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001826 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001827 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001828 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001829 c, i, handle);
1830
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001831 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001832 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001833 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001834 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001835 delete rec;
1836 size--;
1837 } else {
1838 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001839 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001840 }
Aravind Akella8a969552014-09-28 17:52:41 -07001841 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001842 mConnectionHolder.removeEventConnection(connection);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001843 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001844 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001845 }
Peng Xu4f707f82016-09-26 11:28:32 -07001846
1847 SensorDevice& dev(SensorDevice::getInstance());
1848 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001849}
1850
Peng Xue36e3472016-11-03 11:57:10 -07001851void SensorService::cleanupConnection(SensorDirectConnection* c) {
1852 Mutex::Autolock _l(mLock);
1853
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001854 int deviceId = c->getDeviceId();
1855 if (deviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
1856 SensorDevice& dev(SensorDevice::getInstance());
1857 dev.unregisterDirectChannel(c->getHalChannelHandle());
1858 } else {
1859 auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
1860 if (runtimeSensorCallback != mRuntimeSensorCallbacks.end()) {
1861 runtimeSensorCallback->second->onDirectChannelDestroyed(c->getHalChannelHandle());
1862 } else {
1863 ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
1864 }
1865 }
Brian Duddie967ce172019-06-10 11:08:27 -07001866 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001867}
1868
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001869void SensorService::checkAndReportProxStateChangeLocked() {
1870 if (mProxSensorHandles.empty()) return;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001871
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001872 SensorDevice& dev(SensorDevice::getInstance());
1873 bool isActive = false;
1874 for (auto& sensor : mProxSensorHandles) {
1875 if (dev.isSensorActive(sensor)) {
1876 isActive = true;
1877 break;
1878 }
1879 }
1880 if (isActive != mLastReportedProxIsActive) {
1881 notifyProximityStateLocked(isActive, mProximityActiveListeners);
1882 mLastReportedProxIsActive = isActive;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001883 }
1884}
1885
1886void SensorService::notifyProximityStateLocked(
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001887 const bool isActive,
Santos Cordon7ea287a2021-06-14 13:45:29 +01001888 const std::vector<sp<ProximityActiveListener>>& listeners) {
Santos Cordon7ea287a2021-06-14 13:45:29 +01001889 const uint64_t mySeq = ++curProxCallbackSeq;
1890 std::thread t([isActive, mySeq, listenersCopy = listeners]() {
1891 while (completedCallbackSeq.load() != mySeq - 1)
1892 std::this_thread::sleep_for(1ms);
1893 for (auto& listener : listenersCopy)
1894 listener->onProximityActive(isActive);
1895 completedCallbackSeq++;
1896 });
1897 t.detach();
Andrew Lehmer3a602572021-03-25 15:19:56 -07001898}
1899
1900status_t SensorService::addProximityActiveListener(const sp<ProximityActiveListener>& callback) {
1901 if (callback == nullptr) {
1902 return BAD_VALUE;
1903 }
1904
1905 Mutex::Autolock _l(mLock);
1906
1907 // Check if the callback was already added.
1908 for (const auto& cb : mProximityActiveListeners) {
1909 if (cb == callback) {
1910 return ALREADY_EXISTS;
1911 }
1912 }
1913
1914 mProximityActiveListeners.push_back(callback);
1915 std::vector<sp<ProximityActiveListener>> listener(1, callback);
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001916 notifyProximityStateLocked(mLastReportedProxIsActive, listener);
Andrew Lehmer3a602572021-03-25 15:19:56 -07001917 return OK;
1918}
1919
1920status_t SensorService::removeProximityActiveListener(
1921 const sp<ProximityActiveListener>& callback) {
1922 if (callback == nullptr) {
1923 return BAD_VALUE;
1924 }
1925
1926 Mutex::Autolock _l(mLock);
1927
1928 for (auto iter = mProximityActiveListeners.begin();
1929 iter != mProximityActiveListeners.end();
1930 ++iter) {
1931 if (*iter == callback) {
1932 mProximityActiveListeners.erase(iter);
1933 return OK;
1934 }
1935 }
1936 return NAME_NOT_FOUND;
1937}
1938
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001939std::shared_ptr<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001940 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001941}
1942
Vladimir Komsiyski4871f092023-01-19 18:25:43 +01001943int SensorService::getDeviceIdFromHandle(int handle) const {
1944 int deviceId = RuntimeSensor::DEFAULT_DEVICE_ID;
1945 mSensors.forEachEntry(
1946 [&deviceId, handle] (const SensorServiceUtil::SensorList::Entry& e) -> bool {
1947 if (e.si->getSensor().getHandle() == handle) {
1948 deviceId = e.deviceId;
1949 return false; // stop iterating
1950 }
1951 return true;
1952 });
1953 return deviceId;
1954}
1955
Mathias Agopianfc328812010-07-14 23:41:37 -07001956status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001957 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001958 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001959 if (mInitCheck != NO_ERROR)
1960 return mInitCheck;
1961
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001962 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001963 if (sensor == nullptr ||
1964 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001965 return BAD_VALUE;
1966 }
1967
Brian Duddie967ce172019-06-10 11:08:27 -07001968 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Anthony Stange9bb16702023-01-03 22:42:31 +00001969 if (mCurrentOperatingMode != NORMAL && mCurrentOperatingMode != REPLAY_DATA_INJECTION &&
Anthony Stangecd01ec12023-01-06 18:35:13 +00001970 !isAllowListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001971 return INVALID_OPERATION;
1972 }
1973
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001974 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001975 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001976 rec = new SensorRecord(connection);
1977 mActiveSensors.add(handle, rec);
1978 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001979 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001980 }
Brian Stack26029ee2019-04-22 17:25:49 -07001981
1982 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1983 // the recent event as stale to ensure that the previous event is not sent to a client. This
1984 // ensures on-change events that were generated during a previous sensor activation are not
1985 // erroneously sent to newly connected clients, especially if a second client registers for
1986 // an on-change sensor before the first client receives the updated event. Once an updated
1987 // event is received, the recent events will be marked as current, and any new clients will
1988 // immediately receive the most recent event.
1989 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1990 auto logger = mRecentEvent.find(handle);
1991 if (logger != mRecentEvent.end()) {
1992 logger->second->setLastEventStale();
1993 }
1994 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001995 } else {
1996 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001997 // this sensor is already activated, but we are adding a connection that uses it.
1998 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001999 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07002000 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002001 // NOTE: The wake_up flag of this event may get set to
2002 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08002003
2004 auto logger = mRecentEvent.find(handle);
2005 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07002006 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07002007 // Verify that the last sensor event was generated from the current activation
2008 // of the sensor. If not, it is possible for an on-change sensor to receive a
2009 // sensor event that is stale if two clients re-activate the sensor
2010 // simultaneously.
2011 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07002012 event.sensor = handle;
2013 if (event.version == sizeof(sensors_event_t)) {
2014 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
2015 setWakeLockAcquiredLocked(true);
2016 }
Yi Kong8f313e32018-07-17 14:13:29 -07002017 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07002018 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07002019 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07002020 }
2021 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08002022 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002023 }
2024 }
2025 }
2026 }
2027
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07002028 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002029 BatteryService::enableSensor(connection->getUid(), handle);
2030 // the sensor was added (which means it wasn't already there)
2031 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07002032 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002033 } else {
2034 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
2035 handle, connection.get());
2036 }
2037
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05302038 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07002039 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05302040 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
2041 samplingPeriodNs = maxDelayNs;
2042 }
2043
Aravind Akella724d91d2013-06-27 12:04:23 -07002044 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2045 if (samplingPeriodNs < minDelayNs) {
2046 samplingPeriodNs = minDelayNs;
2047 }
2048
Aravind Akella6c2664a2014-08-13 12:24:50 -07002049 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
2050 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07002051 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
2052
Aravind Akella4949c502015-02-11 15:54:35 -08002053 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07002054 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07002055
Peng Xu20483c42015-10-26 15:14:43 -07002056 // Call flush() before calling activate() on the sensor. Wait for a first
2057 // flush complete event before sending events on this connection. Ignore
2058 // one-shot sensors which don't support flush(). Ignore on-change sensors
2059 // to maintain the on-change logic (any on-change events except the initial
2060 // one should be trigger by a change in value). Also if this sensor isn't
2061 // already active, don't call flush().
2062 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08002063 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07002064 rec->getNumConnections() > 1) {
2065 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07002066 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07002067 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07002068 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07002069 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07002070 } else {
2071 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07002072 }
2073 }
Aravind Akella724d91d2013-06-27 12:04:23 -07002074
2075 if (err == NO_ERROR) {
2076 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
2077 err = sensor->activate(connection.get(), true);
2078 }
2079
Aravind Akella8a969552014-09-28 17:52:41 -07002080 if (err == NO_ERROR) {
2081 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08002082
Brian Stack240d1d62019-05-17 09:49:39 -07002083 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
2084 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07002085 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
2086 }
2087
Peng Xu51224682017-03-10 16:57:27 -08002088 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2089 SensorRegistrationInfo(handle, connection->getPackageName(),
2090 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07002091 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07002092 }
2093
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002094 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07002095 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002096 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002097 }
2098 return err;
2099}
2100
Peng Xu47e96012016-03-28 17:55:56 -07002101status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002102 if (mInitCheck != NO_ERROR)
2103 return mInitCheck;
2104
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002105 Mutex::Autolock _l(mLock);
2106 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002107 if (err == NO_ERROR) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002108 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002109 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07002110
2111 }
2112 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08002113 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2114 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07002115 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002116 }
2117 return err;
2118}
2119
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002120status_t SensorService::cleanupWithoutDisable(
2121 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002122 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002123 return cleanupWithoutDisableLocked(connection, handle);
2124}
2125
2126status_t SensorService::cleanupWithoutDisableLocked(
2127 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002128 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002129 if (rec) {
2130 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07002131 if (connection->removeSensor(handle)) {
2132 BatteryService::disableSensor(connection->getUid(), handle);
2133 }
Mathias Agopianfc328812010-07-14 23:41:37 -07002134 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07002135 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07002136 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07002137 }
2138 // see if this sensor becomes inactive
2139 if (rec->removeConnection(connection)) {
2140 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002141 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002142 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07002143 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002144 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002145 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002146 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07002147}
2148
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002149status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07002150 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002151 if (mInitCheck != NO_ERROR)
2152 return mInitCheck;
2153
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002154 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002155 if (sensor == nullptr ||
2156 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00002157 return BAD_VALUE;
2158 }
2159
Mathias Agopian1cd70002010-07-21 15:59:50 -07002160 if (ns < 0)
2161 return BAD_VALUE;
2162
Mathias Agopian62569ec2011-11-07 21:21:47 -08002163 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2164 if (ns < minDelayNs) {
2165 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07002166 }
2167
Mathias Agopianf001c922010-11-11 17:58:51 -08002168 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07002169}
2170
Svetoslavb412f6e2015-04-29 16:50:41 -07002171status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
2172 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00002173 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002174 SensorDevice& dev(SensorDevice::getInstance());
2175 const int halVersion = dev.getHalDeviceVersion();
2176 status_t err(NO_ERROR);
2177 Mutex::Autolock _l(mLock);
2178 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07002179 for (int handle : connection->getActiveSensorHandles()) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002180 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002181 if (sensor == nullptr) {
2182 continue;
2183 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002184 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
2185 ALOGE("flush called on a one-shot sensor");
2186 err = INVALID_OPERATION;
2187 continue;
2188 }
Aravind Akella8493b792014-09-08 15:45:47 -07002189 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002190 // For older devices just increment pending flush count which will send a trivial
2191 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07002192 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
2193 ALOGE("flush called on an inaccessible sensor");
2194 err = INVALID_OPERATION;
2195 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002196 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002197 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
2198 err = INVALID_OPERATION;
2199 continue;
2200 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002201 status_t err_flush = sensor->flush(connection.get(), handle);
2202 if (err_flush == NO_ERROR) {
2203 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07002204 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002205 }
2206 err = (err_flush != NO_ERROR) ? err_flush : err;
2207 }
Aravind Akella70018042014-04-07 22:52:37 +00002208 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07002209 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07002210}
Aravind Akella70018042014-04-07 22:52:37 +00002211
Svetoslavb412f6e2015-04-29 16:50:41 -07002212bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
2213 const String16& opPackageName) {
Brian Duddie4a4d0462022-05-09 16:49:49 -07002214 // Special case for Head Tracker sensor type: currently restricted to system usage only, unless
2215 // the restriction is specially lifted for testing
2216 if (sensor.getType() == SENSOR_TYPE_HEAD_TRACKER &&
2217 !isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
2218 if (!mHtRestricted) {
2219 ALOGI("Permitting access to HT sensor type outside system (%s)",
2220 String8(opPackageName).string());
2221 } else {
2222 ALOGW("%s %s a sensor (%s) as a non-system client", String8(opPackageName).string(),
2223 operation, sensor.getName().string());
2224 return false;
2225 }
2226 }
2227
Brian Stack793f4642019-04-18 17:21:34 -07002228 // Check if a permission is required for this sensor
2229 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00002230 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07002231 }
2232
Brian Stack793f4642019-04-18 17:21:34 -07002233 const int32_t opCode = sensor.getRequiredAppOp();
Brian Duddie457e6392020-06-19 11:38:29 -07002234 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07002235
Brian Stack793f4642019-04-18 17:21:34 -07002236 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07002237 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
2238 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
2239 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
2240 // Allow access to step sensors if the application targets pre-Q, which is before the
2241 // requirement to hold the AR permission to access Step Counter and Step Detector events
2242 // was introduced.
2243 canAccess = true;
2244 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07002245 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002246 if (opCode >= 0) {
2247 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
2248 IPCThreadState::self()->getCallingUid(), opPackageName);
2249 canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
2250 } else {
Brian Stack793f4642019-04-18 17:21:34 -07002251 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07002252 }
Brian Stack793f4642019-04-18 17:21:34 -07002253 }
2254
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002255 if (!canAccess) {
Brian Duddie457e6392020-06-19 11:38:29 -07002256 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
2257 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07002258 }
2259
2260 return canAccess;
2261}
2262
2263bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07002264 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07002265 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07002266
2267 // Runtime permissions can't use the cache as they may change.
2268 if (sensor.isRequiredPermissionRuntime()) {
2269 hasPermission = checkPermission(String16(requiredPermission),
matthuang65794462022-03-24 16:02:57 +08002270 IPCThreadState::self()->getCallingPid(),
2271 IPCThreadState::self()->getCallingUid(),
2272 /*logPermissionFailure=*/ false);
Aravind Akella70018042014-04-07 22:52:37 +00002273 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002274 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
2275 }
Brian Stack793f4642019-04-18 17:21:34 -07002276 return hasPermission;
2277}
Svetoslavb412f6e2015-04-29 16:50:41 -07002278
Brian Stack793f4642019-04-18 17:21:34 -07002279int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Anthony Stange07eb4212020-08-28 14:50:28 -04002280 // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
2281 // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
2282 // give it elevated privileges.
2283 if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
2284 return -1;
2285 }
2286
Brian Stack793f4642019-04-18 17:21:34 -07002287 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2288 int targetSdkVersion = -1;
2289 auto entry = sPackageTargetVersion.find(opPackageName);
2290 if (entry != sPackageTargetVersion.end()) {
2291 targetSdkVersion = entry->second;
2292 } else {
2293 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2294 if (binder != nullptr) {
2295 sp<content::pm::IPackageManagerNative> packageManager =
2296 interface_cast<content::pm::IPackageManagerNative>(binder);
2297 if (packageManager != nullptr) {
2298 binder::Status status = packageManager->getTargetSdkVersionForPackage(
2299 opPackageName, &targetSdkVersion);
2300 if (!status.isOk()) {
2301 targetSdkVersion = -1;
2302 }
2303 }
Svetoslavb412f6e2015-04-29 16:50:41 -07002304 }
Brian Stack793f4642019-04-18 17:21:34 -07002305 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07002306 }
Brian Stack793f4642019-04-18 17:21:34 -07002307 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00002308}
2309
Brian Duddie0d4ac562022-05-23 17:47:50 -07002310void SensorService::resetTargetSdkVersionCache(const String16& opPackageName) {
2311 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2312 auto iter = sPackageTargetVersion.find(opPackageName);
2313 if (iter != sPackageTargetVersion.end()) {
2314 sPackageTargetVersion.erase(iter);
2315 }
2316}
2317
Anthony Stangec1608152023-01-06 21:14:46 +00002318bool SensorService::getTargetOperatingMode(const std::string &inputString, Mode *targetModeOut) {
2319 if (inputString == std::string("restrict")) {
2320 *targetModeOut = RESTRICTED;
2321 return true;
2322 }
2323 if (inputString == std::string("enable")) {
2324 *targetModeOut = NORMAL;
2325 return true;
2326 }
2327 if (inputString == std::string("data_injection")) {
2328 *targetModeOut = DATA_INJECTION;
2329 return true;
2330 }
2331 if (inputString == std::string("replay_data_injection")) {
2332 *targetModeOut = REPLAY_DATA_INJECTION;
2333 return true;
2334 }
2335 return false;
2336}
2337
2338status_t SensorService::changeOperatingMode(const Vector<String16>& args,
2339 Mode targetOperatingMode) {
2340 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2341 SensorDevice& dev(SensorDevice::getInstance());
2342 if (mCurrentOperatingMode == targetOperatingMode) {
2343 return NO_ERROR;
2344 }
2345 if (targetOperatingMode != NORMAL && args.size() < 2) {
2346 return INVALID_OPERATION;
2347 }
2348 switch (targetOperatingMode) {
2349 case NORMAL:
2350 // If currently in restricted mode, reset back to NORMAL mode else ignore.
2351 if (mCurrentOperatingMode == RESTRICTED) {
2352 mCurrentOperatingMode = NORMAL;
2353 // enable sensors and recover all sensor direct report
2354 enableAllSensorsLocked(&connLock);
2355 }
2356 if (mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
2357 dev.disableAllSensors();
2358 }
2359 if (mCurrentOperatingMode == DATA_INJECTION ||
2360 mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
2361 resetToNormalModeLocked();
2362 }
2363 mAllowListedPackage.clear();
2364 return status_t(NO_ERROR);
2365 case RESTRICTED:
2366 // If in any mode other than normal, ignore.
2367 if (mCurrentOperatingMode != NORMAL) {
2368 return INVALID_OPERATION;
2369 }
2370
2371 mCurrentOperatingMode = RESTRICTED;
2372 // temporarily stop all sensor direct report and disable sensors
2373 disableAllSensorsLocked(&connLock);
2374 mAllowListedPackage.setTo(String8(args[1]));
2375 return status_t(NO_ERROR);
2376 case REPLAY_DATA_INJECTION:
2377 if (SensorServiceUtil::isUserBuild()) {
2378 return INVALID_OPERATION;
2379 }
2380 FALLTHROUGH_INTENDED;
2381 case DATA_INJECTION:
2382 if (mCurrentOperatingMode == NORMAL) {
2383 dev.disableAllSensors();
2384 // Always use DATA_INJECTION here since this value goes to the HAL and the HAL
2385 // doesn't have an understanding of replay vs. normal data injection.
2386 status_t err = dev.setMode(DATA_INJECTION);
2387 if (err == NO_ERROR) {
2388 mCurrentOperatingMode = targetOperatingMode;
2389 }
2390 if (err != NO_ERROR || targetOperatingMode == REPLAY_DATA_INJECTION) {
2391 // Re-enable sensors.
2392 dev.enableAllSensors();
2393 }
2394 mAllowListedPackage.setTo(String8(args[1]));
2395 return NO_ERROR;
2396 } else {
2397 // Transition to data injection mode supported only from NORMAL mode.
2398 return INVALID_OPERATION;
2399 }
2400 break;
2401 default:
2402 break;
2403 }
2404 return NO_ERROR;
2405}
2406
Aravind Akella9a844cf2014-02-11 18:58:52 -08002407void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07002408 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2409 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08002410}
2411
Brian Duddie967ce172019-06-10 11:08:27 -07002412void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002413 if (!mWakeLockAcquired) {
2414 return;
2415 }
2416 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07002417 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
2418 if (connection->needsWakeLock()) {
2419 releaseLock = false;
2420 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08002421 }
2422 }
2423 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07002424 setWakeLockAcquiredLocked(false);
2425 }
2426}
2427
2428void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
2429 Mutex::Autolock _l(mLock);
2430 connection->writeToSocketFromCache();
2431 if (connection->needsWakeLock()) {
2432 setWakeLockAcquiredLocked(true);
2433 }
2434}
2435
Anthony Stangecd01ec12023-01-06 18:35:13 +00002436bool SensorService::isAllowListedPackage(const String8& packageName) {
2437 return (packageName.contains(mAllowListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08002438}
2439
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002440bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08002441 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07002442 String8 package(opPackageName);
Anthony Stangecd01ec12023-01-06 18:35:13 +00002443 return !isAllowListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07002444 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002445 return false;
Peng Xue36e3472016-11-03 11:57:10 -07002446}
2447
Svet Ganove752a5c2018-01-15 17:14:20 -08002448void SensorService::UidPolicy::registerSelf() {
2449 ActivityManager am;
2450 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
2451 | ActivityManager::UID_OBSERVER_IDLE
2452 | ActivityManager::UID_OBSERVER_ACTIVE,
2453 ActivityManager::PROCESS_STATE_UNKNOWN,
2454 String16("android"));
2455}
2456
2457void SensorService::UidPolicy::unregisterSelf() {
2458 ActivityManager am;
2459 am.unregisterUidObserver(this);
2460}
2461
2462void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
2463 onUidIdle(uid, disabled);
2464}
2465
2466void SensorService::UidPolicy::onUidActive(uid_t uid) {
2467 {
2468 Mutex::Autolock _l(mUidLock);
2469 mActiveUids.insert(uid);
2470 }
2471 sp<SensorService> service = mService.promote();
2472 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002473 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002474 }
2475}
2476
2477void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
2478 bool deleted = false;
2479 {
2480 Mutex::Autolock _l(mUidLock);
2481 if (mActiveUids.erase(uid) > 0) {
2482 deleted = true;
2483 }
2484 }
2485 if (deleted) {
2486 sp<SensorService> service = mService.promote();
2487 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002488 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002489 }
2490 }
2491}
2492
2493void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
2494 updateOverrideUid(uid, active, true);
2495}
2496
2497void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
2498 updateOverrideUid(uid, false, false);
2499}
2500
2501void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
2502 bool wasActive = false;
2503 bool isActive = false;
2504 {
2505 Mutex::Autolock _l(mUidLock);
2506 wasActive = isUidActiveLocked(uid);
2507 mOverrideUids.erase(uid);
2508 if (insert) {
2509 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2510 }
2511 isActive = isUidActiveLocked(uid);
2512 }
2513 if (wasActive != isActive) {
2514 sp<SensorService> service = mService.promote();
2515 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002516 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002517 }
2518 }
2519}
2520
2521bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2522 // Non-app UIDs are considered always active
2523 if (uid < FIRST_APPLICATION_UID) {
2524 return true;
2525 }
2526 Mutex::Autolock _l(mUidLock);
2527 return isUidActiveLocked(uid);
2528}
2529
2530bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2531 // Non-app UIDs are considered always active
2532 if (uid < FIRST_APPLICATION_UID) {
2533 return true;
2534 }
2535 auto it = mOverrideUids.find(uid);
2536 if (it != mOverrideUids.end()) {
2537 return it->second;
2538 }
2539 return mActiveUids.find(uid) != mActiveUids.end();
2540}
2541
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002542bool SensorService::isUidActive(uid_t uid) {
2543 return mUidPolicy->isUidActive(uid);
2544}
2545
Anh Phamaf91a912021-02-10 14:10:53 +01002546bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2547 int targetSdk = getTargetSdkVersion(opPackageName);
Anh Phama5538232021-06-23 08:41:11 +02002548 bool hasSamplingRatePermission = checkPermission(sAccessHighSensorSamplingRatePermission,
2549 IPCThreadState::self()->getCallingPid(),
matthuang65794462022-03-24 16:02:57 +08002550 IPCThreadState::self()->getCallingUid(),
2551 /*logPermissionFailure=*/ false);
Anh Phamaf91a912021-02-10 14:10:53 +01002552 if (targetSdk < __ANDROID_API_S__ ||
2553 (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2554 return false;
2555 }
2556 return true;
2557}
2558
Anh Pham3dae77f2021-06-11 16:24:37 +02002559/**
2560 * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS
2561 * permission.
2562 *
2563 * This needs to be kept in sync with the list defined on the Java side
2564 * in frameworks/base/core/java/android/hardware/SystemSensorManager.java
2565 */
Anh Phamaf91a912021-02-10 14:10:53 +01002566bool SensorService::isSensorInCappedSet(int sensorType) {
2567 return (sensorType == SENSOR_TYPE_ACCELEROMETER
2568 || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2569 || sensorType == SENSOR_TYPE_GYROSCOPE
2570 || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2571 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2572 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2573}
2574
2575status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2576 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002577 if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2578 return OK;
2579 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002580 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002581 if (shouldCapBasedOnPermission) {
2582 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2583 if (isPackageDebuggable(opPackageName)) {
2584 return PERMISSION_DENIED;
2585 }
2586 return OK;
2587 }
Evan Severson4c197852022-01-27 10:44:27 -08002588 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002589 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2590 return OK;
2591 }
Anh Phamaf91a912021-02-10 14:10:53 +01002592 return OK;
2593}
2594
2595status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2596 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002597 if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2598 return OK;
2599 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002600 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002601 if (shouldCapBasedOnPermission) {
2602 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2603 if (isPackageDebuggable(opPackageName)) {
2604 return PERMISSION_DENIED;
2605 }
2606 return OK;
2607 }
Evan Severson4c197852022-01-27 10:44:27 -08002608 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002609 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2610 return OK;
2611 }
Anh Phamaf91a912021-02-10 14:10:53 +01002612 return OK;
2613}
2614
Michael Groover5e1f60b2018-12-04 22:34:29 -08002615void SensorService::SensorPrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002616 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002617 SensorPrivacyManager spm;
2618 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2619 spm.addSensorPrivacyListener(this);
2620}
2621
2622void SensorService::SensorPrivacyPolicy::unregisterSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002623 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002624 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002625 spm.removeSensorPrivacyListener(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -08002626}
2627
2628bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2629 return mSensorPrivacyEnabled;
2630}
2631
Evan Severson4c197852022-01-27 10:44:27 -08002632binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2633 int sensor __unused, bool enabled) {
Michael Groover5e1f60b2018-12-04 22:34:29 -08002634 mSensorPrivacyEnabled = enabled;
2635 sp<SensorService> service = mService.promote();
Anh Pham5198c992021-02-10 14:15:30 +01002636
Michael Groover5e1f60b2018-12-04 22:34:29 -08002637 if (service != nullptr) {
Evan Severson4c197852022-01-27 10:44:27 -08002638 if (enabled) {
2639 service->disableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002640 } else {
Evan Severson4c197852022-01-27 10:44:27 -08002641 service->enableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002642 }
2643 }
2644 return binder::Status::ok();
2645}
Brian Duddie967ce172019-06-10 11:08:27 -07002646
Evan Severson4c197852022-01-27 10:44:27 -08002647void SensorService::MicrophonePrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002648 AutoCallerClear acc;
Anh Pham5198c992021-02-10 14:15:30 +01002649 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002650 mSensorPrivacyEnabled =
2651 spm.isToggleSensorPrivacyEnabled(
2652 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
2653 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE)
2654 || spm.isToggleSensorPrivacyEnabled(
2655 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE,
2656 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE);
2657 spm.addToggleSensorPrivacyListener(this);
Anh Pham5198c992021-02-10 14:15:30 +01002658}
2659
Evan Severson4c197852022-01-27 10:44:27 -08002660void SensorService::MicrophonePrivacyPolicy::unregisterSelf() {
2661 AutoCallerClear acc;
2662 SensorPrivacyManager spm;
2663 spm.removeToggleSensorPrivacyListener(this);
2664}
2665
2666binder::Status SensorService::MicrophonePrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2667 int sensor, bool enabled) {
2668 if (sensor != SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE) {
2669 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002670 }
Evan Severson4c197852022-01-27 10:44:27 -08002671 mSensorPrivacyEnabled = enabled;
2672 sp<SensorService> service = mService.promote();
2673
2674 if (service != nullptr) {
2675 if (enabled) {
2676 service->capRates();
2677 } else {
2678 service->uncapRates();
2679 }
2680 }
2681 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002682}
2683
Brian Duddie967ce172019-06-10 11:08:27 -07002684SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2685 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2686 : mConnectionHolder(holder), mAutolock(mutex) {}
2687
2688template<typename ConnectionType>
2689const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2690 const SortedVector<wp<ConnectionType>>& connectionList,
2691 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2692 referenceHolder->emplace_back();
2693 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2694 for (const wp<ConnectionType>& weakConnection : connectionList){
2695 sp<ConnectionType> connection = weakConnection.promote();
2696 if (connection != nullptr) {
2697 connections.push_back(std::move(connection));
2698 }
2699 }
2700 return connections;
2701}
2702
2703const std::vector<sp<SensorService::SensorEventConnection>>&
2704 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2705 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2706 &mReferencedActiveConnections);
2707}
2708
2709const std::vector<sp<SensorService::SensorDirectConnection>>&
2710 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2711 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2712 &mReferencedDirectConnections);
2713}
2714
2715void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2716 const sp<SensorService::SensorEventConnection>& connection) {
2717 if (mActiveConnections.indexOf(connection) < 0) {
2718 mActiveConnections.add(connection);
2719 }
2720}
2721
2722void SensorService::SensorConnectionHolder::removeEventConnection(
2723 const wp<SensorService::SensorEventConnection>& connection) {
2724 mActiveConnections.remove(connection);
2725}
2726
2727void SensorService::SensorConnectionHolder::addDirectConnection(
2728 const sp<SensorService::SensorDirectConnection>& connection) {
2729 mDirectConnections.add(connection);
2730}
2731
2732void SensorService::SensorConnectionHolder::removeDirectConnection(
2733 const wp<SensorService::SensorDirectConnection>& connection) {
2734 mDirectConnections.remove(connection);
2735}
2736
2737SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2738 return ConnectionSafeAutolock(*this, mutex);
2739}
2740
Anh Phamaf91a912021-02-10 14:10:53 +01002741bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2742 bool debugMode = false;
2743 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2744 if (binder != nullptr) {
2745 sp<content::pm::IPackageManagerNative> packageManager =
2746 interface_cast<content::pm::IPackageManagerNative>(binder);
2747 if (packageManager != nullptr) {
2748 binder::Status status = packageManager->isPackageDebuggable(
2749 opPackageName, &debugMode);
2750 }
2751 }
2752 return debugMode;
2753}
Brian Duddie967ce172019-06-10 11:08:27 -07002754} // namespace android