blob: 3a0329cd098dc3d358cf277deb6c2327be9e8917 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Vladimir Komsiyski29d2afd2022-12-06 13:24:10 +010016#include <aidl/android/hardware/sensors/ISensors.h>
Anh Phamaf91a912021-02-10 14:10:53 +010017#include <android-base/strings.h>
Brian Stack793f4642019-04-18 17:21:34 -070018#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080019#include <android/util/ProtoOutputStream.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080020#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070021#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070022#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070023#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080024#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070025#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080026#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070027#include <cutils/properties.h>
Brian Duddie0a4cebb2022-08-25 19:20:18 +000028#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070029#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070030#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080031#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070032#include <openssl/digest.h>
33#include <openssl/hmac.h>
34#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070035#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080036#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070037#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070038
Mathias Agopian787ac1b2012-09-18 18:49:18 -070039#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070040#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080041#include "GravitySensor.h"
Tyler Trephanc7b92632021-07-21 10:39:38 -070042#include "LimitedAxesImuSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080043#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070044#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080045#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070047#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048
Mathias Agopian984826c2011-05-17 22:54:42 -070049#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070050#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080051#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080052#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080053#include "SensorRecord.h"
54#include "SensorRegistrationInfo.h"
Anthony Stange9bb16702023-01-03 22:42:31 +000055#include "SensorServiceUtils.h"
Peng Xueb4d6282015-12-10 18:02:41 -080056
57#include <inttypes.h>
58#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070059#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080060#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080061#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070062#include <sys/stat.h>
63#include <sys/types.h>
64#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070065
Andrew Lehmer3a602572021-03-25 15:19:56 -070066#include <ctime>
67#include <future>
Anthony Stangec1608152023-01-06 21:14:46 +000068#include <string>
Andrew Lehmer3a602572021-03-25 15:19:56 -070069
Svet Ganove752a5c2018-01-15 17:14:20 -080070#include <private/android_filesystem_config.h>
71
Andrew Lehmer3a602572021-03-25 15:19:56 -070072using namespace std::chrono_literals;
73
Mathias Agopianfc328812010-07-14 23:41:37 -070074namespace android {
75// ---------------------------------------------------------------------------
76
Mathias Agopian33015422011-05-27 18:18:13 -070077/*
78 * Notes:
79 *
80 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070081 * - run mag sensor from time to time to force calibration
82 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
83 *
84 */
85
Aravind Akella8ef3c892015-07-10 11:24:28 -070086const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070087uint8_t SensorService::sHmacGlobalKey[128] = {};
88bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070089std::map<String16, int> SensorService::sPackageTargetVersion;
90Mutex SensorService::sPackageTargetVersionLock;
Anthony Stange07eb4212020-08-28 14:50:28 -040091String16 SensorService::sSensorInterfaceDescriptorPrefix =
92 String16("android.frameworks.sensorservice@");
Brian Stack793f4642019-04-18 17:21:34 -070093AppOpsManager SensorService::sAppOpsManager;
Andrew Lehmer3a602572021-03-25 15:19:56 -070094std::atomic_uint64_t SensorService::curProxCallbackSeq(0);
95std::atomic_uint64_t SensorService::completedCallbackSeq(0);
Greg Kaiser53ca2e02016-06-21 16:11:14 -070096
97#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
98#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070099#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700100
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700101// Permissions.
Anh Phamaf91a912021-02-10 14:10:53 +0100102static const String16 sAccessHighSensorSamplingRatePermission(
103 "android.permission.HIGH_SAMPLING_RATE_SENSORS");
Peng Xudd5c5cb2017-03-16 17:39:43 -0700104static const String16 sDumpPermission("android.permission.DUMP");
105static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -0800106static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700107
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200108namespace {
109
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200110int32_t nextRuntimeSensorHandle() {
Vladimir Komsiyski29d2afd2022-12-06 13:24:10 +0100111 using ::aidl::android::hardware::sensors::ISensors;
112 static int32_t nextHandle = ISensors::RUNTIME_SENSORS_HANDLE_BASE;
113 if (nextHandle == ISensors::RUNTIME_SENSORS_HANDLE_END) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200114 return -1;
115 }
116 return nextHandle++;
117}
118
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100119class RuntimeSensorCallbackProxy : public RuntimeSensor::SensorCallback {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200120 public:
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100121 RuntimeSensorCallbackProxy(sp<SensorService::RuntimeSensorCallback> callback)
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200122 : mCallback(std::move(callback)) {}
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100123 status_t onConfigurationChanged(int handle, bool enabled, int64_t samplingPeriodNs,
124 int64_t batchReportLatencyNs) override {
125 return mCallback->onConfigurationChanged(handle, enabled, samplingPeriodNs,
126 batchReportLatencyNs);
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200127 }
128 private:
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100129 sp<SensorService::RuntimeSensorCallback> mCallback;
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200130};
131
132} // namespace
133
Tyler Trephanc7b92632021-07-21 10:39:38 -0700134static bool isAutomotive() {
135 sp<IServiceManager> serviceManager = defaultServiceManager();
136 if (serviceManager.get() == nullptr) {
137 ALOGE("%s: unable to access native ServiceManager", __func__);
138 return false;
139 }
140
141 sp<content::pm::IPackageManagerNative> packageManager;
142 sp<IBinder> binder = serviceManager->waitForService(String16("package_native"));
143 packageManager = interface_cast<content::pm::IPackageManagerNative>(binder);
144 if (packageManager == nullptr) {
145 ALOGE("%s: unable to access native PackageManager", __func__);
146 return false;
147 }
148
149 bool isAutomotive = false;
150 binder::Status status =
151 packageManager->hasSystemFeature(String16("android.hardware.type.automotive"), 0,
152 &isAutomotive);
153 if (!status.isOk()) {
154 ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str());
155 return false;
156 }
157
158 return isAutomotive;
159}
160
Mathias Agopianfc328812010-07-14 23:41:37 -0700161SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -0700162 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700163 mWakeLockAcquired(false), mLastReportedProxIsActive(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +0900164 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800165 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Evan Severson4c197852022-01-27 10:44:27 -0800166 mMicSensorPrivacyPolicy = new MicrophonePrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700167}
168
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200169int SensorService::registerRuntimeSensor(
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100170 const sensor_t& sensor, int deviceId, sp<RuntimeSensorCallback> callback) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200171 int handle = 0;
172 while (handle == 0 || !mSensors.isNewHandle(handle)) {
173 handle = nextRuntimeSensorHandle();
174 if (handle < 0) {
175 // Ran out of the dedicated range for runtime sensors.
176 return handle;
177 }
178 }
179
180 ALOGI("Registering runtime sensor handle 0x%x, type %d, name %s",
181 handle, sensor.type, sensor.name);
182
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100183 sp<RuntimeSensor::SensorCallback> runtimeSensorCallback(
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200184 new RuntimeSensorCallbackProxy(std::move(callback)));
185 sensor_t runtimeSensor = sensor;
186 // force the handle to be consistent
187 runtimeSensor.handle = handle;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100188 auto si = std::make_shared<RuntimeSensor>(runtimeSensor, std::move(runtimeSensorCallback));
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200189
190 Mutex::Autolock _l(mLock);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100191 if (!registerSensor(std::move(si), /* isDebug= */ false, /* isVirtual= */ false, deviceId)) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200192 // The registration was unsuccessful.
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100193 return mSensors.getNonSensor().getHandle();
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200194 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100195
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200196 return handle;
197}
198
199status_t SensorService::unregisterRuntimeSensor(int handle) {
200 ALOGI("Unregistering runtime sensor handle 0x%x disconnected", handle);
201 {
202 Mutex::Autolock _l(mLock);
203 if (!unregisterDynamicSensorLocked(handle)) {
204 ALOGE("Runtime sensor release error.");
205 return UNKNOWN_ERROR;
206 }
207 }
208
209 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
210 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
211 connection->removeSensor(handle);
212 }
213 return OK;
214}
215
216status_t SensorService::sendRuntimeSensorEvent(const sensors_event_t& event) {
217 Mutex::Autolock _l(mLock);
218 mRuntimeSensorEventQueue.push(event);
219 return OK;
220}
221
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700222bool SensorService::initializeHmacKey() {
223 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
224 if (fd != -1) {
225 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
226 close(fd);
227 if (result == sizeof(sHmacGlobalKey)) {
228 return true;
229 }
230 ALOGW("Unable to read HMAC key; generating new one.");
231 }
232
233 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
234 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
235 return false;
236 }
237
238 // We need to make sure this is only readable to us.
239 bool wroteKey = false;
240 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
241 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
242 S_IRUSR|S_IWUSR);
243 if (fd != -1) {
244 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
245 close(fd);
246 wroteKey = (result == sizeof(sHmacGlobalKey));
247 }
248 if (wroteKey) {
249 ALOGI("Generated new HMAC key.");
250 } else {
251 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
252 "after reboot.");
253 }
254 // Even if we failed to write the key we return true, because we did
255 // initialize the HMAC key.
256 return true;
257}
258
Peng Xu98d30f62016-08-01 18:12:11 -0700259// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
260void SensorService::enableSchedFifoMode() {
261 struct sched_param param = {0};
262 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
263 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
264 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
265 }
266}
267
Peng Xu47e96012016-03-28 17:55:56 -0700268void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000269 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800270 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700271
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700272 sHmacGlobalKeyIsValid = initializeHmacKey();
273
Mathias Agopianf001c922010-11-11 17:58:51 -0800274 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800275 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700276 ssize_t count = dev.getSensorList(&list);
277 if (count > 0) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700278 bool hasGyro = false, hasAccel = false, hasMag = false;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700279 bool hasGyroUncalibrated = false;
280 bool hasAccelUncalibrated = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700281 uint32_t virtualSensorsNeeds =
282 (1<<SENSOR_TYPE_GRAVITY) |
283 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700284 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
285 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
286 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700287
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700288 for (ssize_t i=0 ; i<count ; i++) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700289 bool useThisSensor = true;
Peng Xuf66684a2015-07-23 11:41:53 -0700290
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700291 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700292 case SENSOR_TYPE_ACCELEROMETER:
293 hasAccel = true;
294 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700295 case SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED:
296 hasAccelUncalibrated = true;
297 break;
Aravind Akellaf5047892015-07-20 17:29:33 -0700298 case SENSOR_TYPE_MAGNETIC_FIELD:
299 hasMag = true;
300 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700301 case SENSOR_TYPE_GYROSCOPE:
302 hasGyro = true;
303 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700304 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
305 hasGyroUncalibrated = true;
306 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700307 case SENSOR_TYPE_GRAVITY:
308 case SENSOR_TYPE_LINEAR_ACCELERATION:
309 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700310 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
311 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
312 if (IGNORE_HARDWARE_FUSION) {
313 useThisSensor = false;
314 } else {
315 virtualSensorsNeeds &= ~(1<<list[i].type);
316 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700317 break;
Arthur Ishiguro2fd90a72021-11-12 17:24:41 +0000318 default:
319 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700320 }
Peng Xuf66684a2015-07-23 11:41:53 -0700321 if (useThisSensor) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700322 if (list[i].type == SENSOR_TYPE_PROXIMITY) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100323 auto s = std::make_shared<ProximitySensor>(list[i], *this);
324 const int handle = s->getSensor().getHandle();
325 if (registerSensor(std::move(s))) {
326 mProxSensorHandles.push_back(handle);
327 }
Andrew Lehmer3a602572021-03-25 15:19:56 -0700328 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100329 registerSensor(std::make_shared<HardwareSensor>(list[i]));
Andrew Lehmer3a602572021-03-25 15:19:56 -0700330 }
Peng Xuf66684a2015-07-23 11:41:53 -0700331 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700332 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700333
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700334 // it's safe to instantiate the SensorFusion object here
335 // (it wants to be instantiated after h/w sensors have been
336 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700337 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700338
Tyler Trephanc7b92632021-07-21 10:39:38 -0700339 if ((hasGyro || hasGyroUncalibrated) && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700340 // Add Android virtual sensors if they're not already
341 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700342 bool needRotationVector =
343 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100344 registerVirtualSensor(std::make_shared<RotationVectorSensor>(),
345 /* isDebug= */ !needRotationVector);
346 registerVirtualSensor(std::make_shared<OrientationSensor>(),
347 /* isDebug= */ !needRotationVector);
Mathias Agopian03193062013-05-10 19:32:39 -0700348
Peng Xu0cc8f802016-04-05 23:46:03 -0700349 // virtual debugging sensors are not for user
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100350 registerVirtualSensor(std::make_shared<CorrectedGyroSensor>(list, count),
351 /* isDebug= */ true);
352 registerVirtualSensor(std::make_shared<GyroDriftSensor>(), /* isDebug= */ true);
Mathias Agopian33264862012-06-28 19:46:54 -0700353 }
354
Tyler Trephanc7b92632021-07-21 10:39:38 -0700355 if (hasAccel && (hasGyro || hasGyroUncalibrated)) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700356 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100357 registerVirtualSensor(std::make_shared<GravitySensor>(list, count),
358 /* isDebug= */ !needGravitySensor);
Peng Xuf66684a2015-07-23 11:41:53 -0700359
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800360 bool needLinearAcceleration =
361 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100362 registerVirtualSensor(std::make_shared<LinearAccelerationSensor>(list, count),
363 /* isDebug= */ !needLinearAcceleration);
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800364
Peng Xu0cc8f802016-04-05 23:46:03 -0700365 bool needGameRotationVector =
366 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100367 registerVirtualSensor(std::make_shared<GameRotationVectorSensor>(),
368 /* isDebug= */ !needGameRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700369 }
370
371 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700372 bool needGeoMagRotationVector =
373 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100374 registerVirtualSensor(std::make_shared<GeoMagRotationVectorSensor>(),
375 /* isDebug= */ !needGeoMagRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700376 }
377
Tyler Trephanc7b92632021-07-21 10:39:38 -0700378 if (isAutomotive()) {
379 if (hasAccel) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100380 registerVirtualSensor(
381 std::make_shared<LimitedAxesImuSensor>(
382 list, count, SENSOR_TYPE_ACCELEROMETER));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700383 }
384
385 if (hasGyro) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100386 registerVirtualSensor(
387 std::make_shared<LimitedAxesImuSensor>(
388 list, count, SENSOR_TYPE_GYROSCOPE));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700389 }
390
391 if (hasAccelUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100392 registerVirtualSensor(
393 std::make_shared<LimitedAxesImuSensor>(
394 list, count, SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700395 }
396
397 if (hasGyroUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100398 registerVirtualSensor(
399 std::make_shared<LimitedAxesImuSensor>(
400 list, count, SENSOR_TYPE_GYROSCOPE_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700401 }
402 }
403
Aravind Akella5466c3d2014-08-22 16:11:10 -0700404 // Check if the device really supports batching by looking at the FIFO event
405 // counts for each sensor.
406 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700407 mSensors.forEachSensor(
408 [&batchingSupported] (const Sensor& s) -> bool {
409 if (s.getFifoMaxEventCount() > 0) {
410 batchingSupported = true;
411 }
412 return !batchingSupported;
413 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700414
415 if (batchingSupported) {
416 // Increase socket buffer size to a max of 100 KB for batching capabilities.
417 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
418 } else {
419 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
420 }
421
422 // Compare the socketBufferSize value against the system limits and limit
423 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700424 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
425 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700426 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700427 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700428 size_t maxSystemSocketBufferSize;
429 sscanf(line, "%zu", &maxSystemSocketBufferSize);
430 if (mSocketBufferSize > maxSystemSocketBufferSize) {
431 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700432 }
433 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700434 if (fp) {
435 fclose(fp);
436 }
437
Aravind Akella9a844cf2014-02-11 18:58:52 -0800438 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700439 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700440 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
441 mSensorEventBuffer = new sensors_event_t[minBufferSize];
442 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700443 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700444 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700445
Aravind Akella18d6d512015-06-18 14:18:28 -0700446 mNextSensorRegIndex = 0;
447 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
448 mLastNSensorRegistrations.push();
449 }
450
451 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700452 mAckReceiver = new SensorEventAckReceiver(this);
453 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700454 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700455
456 // priority can only be changed after run
457 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800458
459 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800460 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800461
462 // Start watching sensor privacy changes
463 mSensorPrivacyPolicy->registerSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800464
465 // Start watching mic sensor privacy changes
466 mMicSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800467 }
468 }
469}
470
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700471void SensorService::onUidStateChanged(uid_t uid, UidState state) {
472 SensorDevice& dev(SensorDevice::getInstance());
473
Brian Duddie967ce172019-06-10 11:08:27 -0700474 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700475 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700476 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700477 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700478 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700479 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700480
481 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
482 if (conn->getUid() == uid) {
483 // Update sensor subscriptions if needed
484 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
485 conn->onSensorAccessChanged(hasAccess);
486 }
487 }
Chris Kuiper587ef9b2021-10-12 16:36:43 -0700488 checkAndReportProxStateChangeLocked();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700489}
490
491bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
492 Mutex::Autolock _l(mLock);
493 return hasSensorAccessLocked(uid, opPackageName);
494}
495
496bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
497 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
498 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700499}
500
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100501bool SensorService::registerSensor(std::shared_ptr<SensorInterface> s, bool isDebug, bool isVirtual,
502 int deviceId) {
503 const int handle = s->getSensor().getHandle();
504 const int type = s->getSensor().getType();
505 if (mSensors.add(handle, std::move(s), isDebug, isVirtual, deviceId)) {
Brian Stack4baa5be2018-09-18 14:03:13 -0700506 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100507 return true;
Peng Xu0cc8f802016-04-05 23:46:03 -0700508 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100509 LOG_FATAL("Failed to register sensor with handle %d", handle);
510 return false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700511 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800512}
513
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100514bool SensorService::registerDynamicSensorLocked(std::shared_ptr<SensorInterface> s, bool isDebug) {
515 return registerSensor(std::move(s), isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800516}
517
Peng Xu6a2d3a02015-12-21 12:00:23 -0800518bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700519 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800520
521 const auto i = mRecentEvent.find(handle);
522 if (i != mRecentEvent.end()) {
523 delete i->second;
524 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800525 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700526 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800527}
528
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100529bool SensorService::registerVirtualSensor(std::shared_ptr<SensorInterface> s, bool isDebug) {
530 return registerSensor(std::move(s), isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700531}
532
Peng Xu47e96012016-03-28 17:55:56 -0700533SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800534 for (auto && entry : mRecentEvent) {
535 delete entry.second;
536 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800537 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800538 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800539 mMicSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700540}
541
542status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700543 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700544 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800545 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700546 IPCThreadState::self()->getCallingPid(),
547 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700548 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700549 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700550 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800551 return INVALID_OPERATION;
552 }
Anthony Stangec1608152023-01-06 21:14:46 +0000553 if (args.size() > 0) {
554 Mode targetOperatingMode = NORMAL;
555 std::string inputStringMode = String8(args[0]).string();
556 if (getTargetOperatingMode(inputStringMode, &targetOperatingMode)) {
557 status_t error = changeOperatingMode(args, targetOperatingMode);
558 // Dump the latest state only if no error was encountered.
559 if (error != NO_ERROR) {
560 return error;
561 }
Aravind Akella444f2672015-05-07 12:40:52 -0700562 }
Anthony Stangec1608152023-01-06 21:14:46 +0000563 }
Peng Xue36e3472016-11-03 11:57:10 -0700564
Anthony Stangec1608152023-01-06 21:14:46 +0000565 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
566 // Run the following logic if a transition isn't requested above based on the input
567 // argument parsing.
568 if (args.size() == 1 && args[0] == String16("--proto")) {
Mike Ma24743862020-01-29 00:36:55 -0800569 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700570 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700571 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700572 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700573 } else {
574 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700575 //
Brian Stack51498e62018-10-03 10:52:21 -0700576 timespec curTime;
577 clock_gettime(CLOCK_REALTIME, &curTime);
578 struct tm* timeinfo = localtime(&(curTime.tv_sec));
579 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
580 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800581 result.append("Sensor Device:\n");
582 result.append(SensorDevice::getInstance().dump().c_str());
583
584 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700585 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700586
Peng Xu6a2d3a02015-12-21 12:00:23 -0800587 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700588 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700589
Peng Xu0cc8f802016-04-05 23:46:03 -0700590 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800591 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100592 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
593 if (!i.second->isEmpty() && s != nullptr) {
Peng Xufba3c112016-09-08 12:36:59 -0700594 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
595 i.second->setFormat("normal");
596 } else {
597 i.second->setFormat("mask_data");
598 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800599 // if there is events and sensor does not need special permission.
600 result.appendFormat("%s: ", s->getSensor().getName().string());
601 result.append(i.second->dump().c_str());
602 }
603 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700604
Aravind Akella444f2672015-05-07 12:40:52 -0700605 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700606 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700607 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
608 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700609 if (dev.isSensorActive(handle)) {
610 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
611 getSensorName(handle).string(),
612 handle,
613 mActiveSensors.valueAt(i)->getNumConnections());
614 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700615 }
616
Andreas Gamped4036b62015-07-28 13:49:04 -0700617 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700618 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700619 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
620 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700621 result.appendFormat("Mode :");
622 switch(mCurrentOperatingMode) {
623 case NORMAL:
624 result.appendFormat(" NORMAL\n");
625 break;
626 case RESTRICTED:
Anthony Stangecd01ec12023-01-06 18:35:13 +0000627 result.appendFormat(" RESTRICTED : %s\n", mAllowListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700628 break;
629 case DATA_INJECTION:
Anthony Stangecd01ec12023-01-06 18:35:13 +0000630 result.appendFormat(" DATA_INJECTION : %s\n", mAllowListedPackage.string());
Anthony Stange9bb16702023-01-03 22:42:31 +0000631 break;
632 case REPLAY_DATA_INJECTION:
633 result.appendFormat(" REPLAY_DATA_INJECTION : %s\n",
Anthony Stangecd01ec12023-01-06 18:35:13 +0000634 mAllowListedPackage.string());
Anthony Stange9bb16702023-01-03 22:42:31 +0000635 break;
636 default:
637 result.appendFormat(" UNKNOWN\n");
638 break;
Mathias Agopianba02cd22013-07-03 16:20:57 -0700639 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800640 result.appendFormat("Sensor Privacy: %s\n",
641 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700642
Brian Duddie967ce172019-06-10 11:08:27 -0700643 const auto& activeConnections = connLock.getActiveConnections();
644 result.appendFormat("%zd active connections\n", activeConnections.size());
645 for (size_t i=0 ; i < activeConnections.size() ; i++) {
646 result.appendFormat("Connection Number: %zu \n", i);
647 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700648 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700649
Brian Duddie967ce172019-06-10 11:08:27 -0700650 const auto& directConnections = connLock.getDirectConnections();
651 result.appendFormat("%zd direct connections\n", directConnections.size());
652 for (size_t i = 0 ; i < directConnections.size() ; i++) {
653 result.appendFormat("Direct connection %zu:\n", i);
654 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700655 }
656
Aravind Akella18d6d512015-06-18 14:18:28 -0700657 result.appendFormat("Previous Registrations:\n");
658 // Log in the reverse chronological order.
659 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
660 SENSOR_REGISTRATIONS_BUF_SIZE;
661 const int startIndex = currentIndex;
662 do {
663 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
664 if (SensorRegistrationInfo::isSentinel(reg_info)) {
665 // Ignore sentinel, proceed to next item.
666 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
667 SENSOR_REGISTRATIONS_BUF_SIZE;
668 continue;
669 }
Peng Xu51224682017-03-10 16:57:27 -0800670 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700671 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
672 SENSOR_REGISTRATIONS_BUF_SIZE;
673 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700674 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700675 }
676 write(fd, result.string(), result.size());
677 return NO_ERROR;
678}
679
Mike Ma24743862020-01-29 00:36:55 -0800680/**
681 * Dump debugging information as android.service.SensorServiceProto protobuf message using
682 * ProtoOutputStream.
683 *
684 * See proto definition and some notes about ProtoOutputStream in
685 * frameworks/base/core/proto/android/service/sensor_service.proto
686 */
687status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
688 using namespace service::SensorServiceProto;
689 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800690 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
691 if (!mSensors.hasAnySensor()) {
692 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
693 }
Mike Ma24743862020-01-29 00:36:55 -0800694 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
695
696 timespec curTime;
697 clock_gettime(CLOCK_REALTIME, &curTime);
698 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
699
700 // Write SensorDeviceProto
701 uint64_t token = proto.start(SENSOR_DEVICE);
702 SensorDevice::getInstance().dump(&proto);
703 proto.end(token);
704
705 // Write SensorListProto
706 token = proto.start(SENSORS);
707 mSensors.dump(&proto);
708 proto.end(token);
709
710 // Write SensorFusionProto
711 token = proto.start(FUSION_STATE);
712 SensorFusion::getInstance().dump(&proto);
713 proto.end(token);
714
715 // Write SensorEventsProto
716 token = proto.start(SENSOR_EVENTS);
717 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100718 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
719 if (!i.second->isEmpty() && s != nullptr) {
Mike Ma24743862020-01-29 00:36:55 -0800720 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
721 "normal" : "mask_data");
722 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
723 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
724 std::string(s->getSensor().getName().string()));
725 i.second->dump(&proto);
726 proto.end(mToken);
727 }
728 }
729 proto.end(token);
730
731 // Write ActiveSensorProto
732 SensorDevice& dev = SensorDevice::getInstance();
733 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
734 int handle = mActiveSensors.keyAt(i);
735 if (dev.isSensorActive(handle)) {
736 token = proto.start(ACTIVE_SENSORS);
737 proto.write(service::ActiveSensorProto::NAME,
738 std::string(getSensorName(handle).string()));
739 proto.write(service::ActiveSensorProto::HANDLE, handle);
740 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
741 int(mActiveSensors.valueAt(i)->getNumConnections()));
742 proto.end(token);
743 }
744 }
745
746 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
747 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
748 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
749
750 switch(mCurrentOperatingMode) {
751 case NORMAL:
752 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
753 break;
754 case RESTRICTED:
755 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
Anthony Stangecd01ec12023-01-06 18:35:13 +0000756 proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.string()));
Mike Ma24743862020-01-29 00:36:55 -0800757 break;
758 case DATA_INJECTION:
759 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
Anthony Stangecd01ec12023-01-06 18:35:13 +0000760 proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.string()));
Mike Ma24743862020-01-29 00:36:55 -0800761 break;
762 default:
763 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
764 }
765 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
766
767 // Write repeated SensorEventConnectionProto
768 const auto& activeConnections = connLock->getActiveConnections();
769 for (size_t i = 0; i < activeConnections.size(); i++) {
770 token = proto.start(ACTIVE_CONNECTIONS);
771 activeConnections[i]->dump(&proto);
772 proto.end(token);
773 }
774
775 // Write repeated SensorDirectConnectionProto
776 const auto& directConnections = connLock->getDirectConnections();
777 for (size_t i = 0 ; i < directConnections.size() ; i++) {
778 token = proto.start(DIRECT_CONNECTIONS);
779 directConnections[i]->dump(&proto);
780 proto.end(token);
781 }
782
783 // Write repeated SensorRegistrationInfoProto
784 const int startIndex = mNextSensorRegIndex;
785 int curr = startIndex;
786 do {
787 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
788 if (SensorRegistrationInfo::isSentinel(reg_info)) {
789 // Ignore sentinel, proceed to next item.
790 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
791 continue;
792 }
793 token = proto.start(PREVIOUS_REGISTRATIONS);
794 reg_info.dump(&proto);
795 proto.end(token);
796 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
797 } while (startIndex != curr);
798
799 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
800}
801
Michael Groover5e1f60b2018-12-04 22:34:29 -0800802void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700803 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
804 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800805}
806
Brian Duddie967ce172019-06-10 11:08:27 -0700807void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800808 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700809 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
810 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
811 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800812 }
813 dev.disableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700814 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800815 // Clear all pending flush connections for all active sensors. If one of the active
816 // connections has called flush() and the underlying sensor has been disabled before a
817 // flush complete event is returned, we need to remove the connection from this queue.
818 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
819 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
820 }
821}
822
823void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700824 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
825 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800826}
827
Brian Duddie967ce172019-06-10 11:08:27 -0700828void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800829 // sensors should only be enabled if the operating state is not restricted and sensor
830 // privacy is not enabled.
831 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
832 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
833 mCurrentOperatingMode,
834 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
835 return;
836 }
837 SensorDevice& dev(SensorDevice::getInstance());
838 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700839 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
840 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
841 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800842 }
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700843 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800844}
845
Evan Severson4c197852022-01-27 10:44:27 -0800846void SensorService::capRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100847 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
848 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800849 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100850 }
851
852 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800853 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100854 }
855}
856
Evan Severson4c197852022-01-27 10:44:27 -0800857void SensorService::uncapRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100858 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
859 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800860 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100861 }
862
863 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800864 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100865 }
866}
Brian Duddie967ce172019-06-10 11:08:27 -0700867
Svet Ganove752a5c2018-01-15 17:14:20 -0800868// NOTE: This is a remote API - make sure all args are validated
869status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
870 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
871 return PERMISSION_DENIED;
872 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700873 if (args.size() == 0) {
874 return BAD_INDEX;
875 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800876 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
877 return BAD_VALUE;
878 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700879 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800880 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700881 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800882 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700883 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800884 return handleGetUidState(args, out, err);
Brian Duddie4a4d0462022-05-09 16:49:49 -0700885 } else if (args[0] == String16("unrestrict-ht")) {
886 mHtRestricted = false;
887 return NO_ERROR;
888 } else if (args[0] == String16("restrict-ht")) {
889 mHtRestricted = true;
890 return NO_ERROR;
Svet Ganove752a5c2018-01-15 17:14:20 -0800891 } else if (args.size() == 1 && args[0] == String16("help")) {
892 printHelp(out);
893 return NO_ERROR;
894 }
895 printHelp(err);
896 return BAD_VALUE;
897}
898
Tanmay Patild33a1822019-04-11 18:38:55 -0700899static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800900 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700901 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800902 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700903 ALOGE("Unknown package: '%s'", String8(packageName).string());
904 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800905 return BAD_VALUE;
906 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700907
908 if (userId < 0) {
909 ALOGE("Invalid user: %d", userId);
910 dprintf(err, "Invalid user: %d\n", userId);
911 return BAD_VALUE;
912 }
913
914 uid = multiuser_get_uid(userId, uid);
915 return NO_ERROR;
916}
917
918status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
919 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
920 if (!(args.size() == 3 || args.size() == 5)) {
921 printHelp(err);
922 return BAD_VALUE;
923 }
924
Svet Ganove752a5c2018-01-15 17:14:20 -0800925 bool active = false;
926 if (args[2] == String16("active")) {
927 active = true;
928 } else if ((args[2] != String16("idle"))) {
929 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
930 return BAD_VALUE;
931 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700932
933 int userId = 0;
934 if (args.size() == 5 && args[3] == String16("--user")) {
935 userId = atoi(String8(args[4]));
936 }
937
938 uid_t uid;
939 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
940 return BAD_VALUE;
941 }
942
Svet Ganove752a5c2018-01-15 17:14:20 -0800943 mUidPolicy->addOverrideUid(uid, active);
944 return NO_ERROR;
945}
946
947status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700948 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
949 if (!(args.size() == 2 || args.size() == 4)) {
950 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800951 return BAD_VALUE;
952 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700953
954 int userId = 0;
955 if (args.size() == 4 && args[2] == String16("--user")) {
956 userId = atoi(String8(args[3]));
957 }
958
959 uid_t uid;
960 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
961 return BAD_VALUE;
962 }
963
Svet Ganove752a5c2018-01-15 17:14:20 -0800964 mUidPolicy->removeOverrideUid(uid);
965 return NO_ERROR;
966}
967
968status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700969 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
970 if (!(args.size() == 2 || args.size() == 4)) {
971 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800972 return BAD_VALUE;
973 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700974
975 int userId = 0;
976 if (args.size() == 4 && args[2] == String16("--user")) {
977 userId = atoi(String8(args[3]));
978 }
979
980 uid_t uid;
981 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
982 return BAD_VALUE;
983 }
984
Svet Ganove752a5c2018-01-15 17:14:20 -0800985 if (mUidPolicy->isUidActive(uid)) {
986 return dprintf(out, "active\n");
987 } else {
988 return dprintf(out, "idle\n");
989 }
990}
991
992status_t SensorService::printHelp(int out) {
993 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700994 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
995 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
996 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800997 " help print this message\n");
998}
999
Peng Xu0cc8f802016-04-05 23:46:03 -07001000//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -08001001void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001002 sensors_event_t const* buffer, const int count) {
1003 for (int i=0 ; i<count ; i++) {
1004 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -07001005 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1006 handle = buffer[i].meta_data.sensor;
1007 }
Aravind Akella0e025c52014-06-03 19:19:57 -07001008 if (connection->hasSensor(handle)) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001009 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -07001010 // If this buffer has an event from a one_shot sensor and this connection is registered
1011 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -07001012 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -07001013 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1014 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001015 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001016 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001017
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001018 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001019 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001020}
1021
Peng Xu47e96012016-03-28 17:55:56 -07001022bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +00001023 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -07001024
Peng Xueb4d6282015-12-10 18:02:41 -08001025 // each virtual sensor could generate an event per "real" event, that's why we need to size
1026 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
1027 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -07001028 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001029 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -07001030 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001031
Mathias Agopianf001c922010-11-11 17:58:51 -08001032 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -07001033
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001034 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -07001035 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001036 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
1037 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -07001038 if(count == DEAD_OBJECT && device.isReconnecting()) {
1039 device.reconnect();
1040 continue;
1041 } else {
1042 ALOGE("sensor poll failed (%s)", strerror(-count));
1043 break;
1044 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001045 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001046
1047 // Reset sensors_event_t.flags to zero for all events in the buffer.
1048 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001049 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001050 }
Brian Duddie967ce172019-06-10 11:08:27 -07001051 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -07001052
Aravind Akella9a844cf2014-02-11 18:58:52 -08001053 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
1054 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
1055 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
1056 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
1057 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001058 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001059 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001060 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001061 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001062 }
1063 }
1064
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001065 if (wakeEvents > 0) {
1066 if (!mWakeLockAcquired) {
1067 setWakeLockAcquiredLocked(true);
1068 }
1069 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001070 }
Aravind Akella8493b792014-09-08 15:45:47 -07001071 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -08001072
Mathias Agopianf001c922010-11-11 17:58:51 -08001073 // handle virtual sensors
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001074 bool bufferNeedsSorting = false;
Mathias Agopianf001c922010-11-11 17:58:51 -08001075 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -07001076 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -07001077 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001078 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -07001079 SensorFusion& fusion(SensorFusion::getInstance());
1080 if (fusion.isEnabled()) {
1081 for (size_t i=0 ; i<size_t(count) ; i++) {
1082 fusion.process(event[i]);
1083 }
1084 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001085 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -07001086 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001087 if (count + k >= minBufferSize) {
1088 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -07001089 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001090 count, k, minBufferSize);
1091 break;
1092 }
Mathias Agopianf001c922010-11-11 17:58:51 -08001093 sensors_event_t out;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001094 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001095 if (si == nullptr) {
1096 ALOGE("handle %d is not an valid virtual sensor", handle);
1097 continue;
1098 }
1099
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001100 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -07001101 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -08001102 k++;
1103 }
1104 }
1105 }
1106 if (k) {
1107 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -07001108 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -08001109 count += k;
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001110 bufferNeedsSorting = true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001111 }
1112 }
1113 }
1114
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001115 // handle runtime sensors
1116 {
1117 size_t k = 0;
1118 while (!mRuntimeSensorEventQueue.empty()) {
1119 if (count + k >= minBufferSize) {
1120 ALOGE("buffer too small to hold all events: count=%zd, k=%zu, size=%zu",
1121 count, k, minBufferSize);
1122 break;
1123 }
1124 mSensorEventBuffer[count + k] = mRuntimeSensorEventQueue.front();
1125 mRuntimeSensorEventQueue.pop();
1126 k++;
1127 }
1128 if (k) {
1129 // record the last synthesized values
1130 recordLastValueLocked(&mSensorEventBuffer[count], k);
1131 count += k;
1132 bufferNeedsSorting = true;
1133 }
1134 }
1135
1136 if (bufferNeedsSorting) {
1137 // sort the buffer by time-stamps
1138 sortEventBuffer(mSensorEventBuffer, count);
1139 }
1140
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001141 // handle backward compatibility for RotationVector sensor
1142 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
1143 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001144 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001145 // All the 4 components of the quaternion should be available
1146 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -07001147 mSensorEventBuffer[i].data[4] = -1;
1148 }
1149 }
1150 }
1151
Brian Duddie967ce172019-06-10 11:08:27 -07001152 // Cache the list of active connections, since we use it in multiple places below but won't
1153 // modify it here
1154 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
1155
Aravind Akella8493b792014-09-08 15:45:47 -07001156 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -07001157 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
1158 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
1159 // SensorEventConnection mapped to the corresponding flush_complete_event in
1160 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -07001161 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -07001162 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
1163 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
1164 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001165 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -07001166 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
1167 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001168 }
1169 }
Peng Xu2576cb62016-01-20 00:22:09 -08001170
1171 // handle dynamic sensor meta events, process registration and unregistration of dynamic
1172 // sensor based on content of event.
1173 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
1174 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
1175 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1176 const sensor_t& dynamicSensor =
1177 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
1178 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
1179 handle, dynamicSensor.type, dynamicSensor.name);
1180
Peng Xu0cc8f802016-04-05 23:46:03 -07001181 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -08001182 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -07001183 sensor_t s = dynamicSensor;
1184 // make sure the dynamic sensor flag is set
1185 s.flags |= DYNAMIC_SENSOR_MASK;
1186 // force the handle to be consistent
1187 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -08001188
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001189 auto si = std::make_shared<HardwareSensor>(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -08001190
Peng Xu0cc8f802016-04-05 23:46:03 -07001191 // This will release hold on dynamic sensor meta, so it should be called
1192 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -07001193 device.handleDynamicSensorConnection(handle, true /*connected*/);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001194 registerDynamicSensorLocked(std::move(si));
Peng Xu47e96012016-03-28 17:55:56 -07001195 } else {
1196 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
1197 }
Peng Xu2576cb62016-01-20 00:22:09 -08001198 } else {
1199 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1200 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1201
1202 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001203 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -08001204 ALOGE("Dynamic sensor release error.");
1205 }
1206
Brian Duddie967ce172019-06-10 11:08:27 -07001207 for (const sp<SensorEventConnection>& connection : activeConnections) {
1208 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001209 }
1210 }
1211 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001212 }
1213
Aravind Akella9a844cf2014-02-11 18:58:52 -08001214 // Send our events to clients. Check the state of wake lock for each client and release the
1215 // lock if none of the clients need it.
1216 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001217 for (const sp<SensorEventConnection>& connection : activeConnections) {
1218 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1219 mMapFlushEventsToConnections);
1220 needsWakeLock |= connection->needsWakeLock();
1221 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1222 // Early check for one-shot sensors.
1223 if (connection->hasOneShotSensors()) {
1224 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001225 }
1226 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001227
Aravind Akella9a844cf2014-02-11 18:58:52 -08001228 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001229 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001230 }
Aravind Akella8493b792014-09-08 15:45:47 -07001231 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001232
Steve Block3c20fbe2012-01-05 23:22:43 +00001233 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001234 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001235 return false;
1236}
1237
Aravind Akella56ae4262014-07-10 16:01:10 -07001238sp<Looper> SensorService::getLooper() const {
1239 return mLooper;
1240}
1241
Aravind Akellab4373ac2014-10-29 17:55:20 -07001242void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001243 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1244 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1245 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001246 }
Brian Duddie967ce172019-06-10 11:08:27 -07001247 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001248}
1249
1250void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1251 if (acquire) {
1252 if (!mWakeLockAcquired) {
1253 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1254 mWakeLockAcquired = true;
1255 }
1256 mLooper->wake();
1257 } else {
1258 if (mWakeLockAcquired) {
1259 release_wake_lock(WAKE_LOCK_NAME);
1260 mWakeLockAcquired = false;
1261 }
1262 }
1263}
1264
Aravind Akellab4373ac2014-10-29 17:55:20 -07001265bool SensorService::isWakeLockAcquired() {
1266 Mutex::Autolock _l(mLock);
1267 return mWakeLockAcquired;
1268}
1269
Aravind Akella56ae4262014-07-10 16:01:10 -07001270bool SensorService::SensorEventAckReceiver::threadLoop() {
1271 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001272 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001273 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001274 bool wakeLockAcquired = mService->isWakeLockAcquired();
1275 int timeout = -1;
1276 if (wakeLockAcquired) timeout = 5000;
1277 int ret = looper->pollOnce(timeout);
1278 if (ret == ALOOPER_POLL_TIMEOUT) {
1279 mService->resetAllWakeLockRefCounts();
1280 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001281 } while(!Thread::exitPending());
1282 return false;
1283}
1284
Aravind Akella9a844cf2014-02-11 18:58:52 -08001285void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001286 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001287 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001288 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1289 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001290 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001291 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001292 }
Peng Xu2576cb62016-01-20 00:22:09 -08001293
Peng Xu6a2d3a02015-12-21 12:00:23 -08001294 auto logger = mRecentEvent.find(buffer[i].sensor);
1295 if (logger != mRecentEvent.end()) {
1296 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001297 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001298 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001299}
1300
Peng Xu47e96012016-03-28 17:55:56 -07001301void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001302 struct compar {
1303 static int cmp(void const* lhs, void const* rhs) {
1304 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1305 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001306 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001307 }
1308 };
1309 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1310}
1311
Mathias Agopian5d270722010-07-19 15:20:39 -07001312String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001313 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001314}
1315
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001316String8 SensorService::getSensorStringType(int handle) const {
1317 return mSensors.getStringType(handle);
1318}
1319
Aravind Akellab4099e72013-10-15 15:43:10 -07001320bool SensorService::isVirtualSensor(int handle) const {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001321 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001322 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001323}
1324
Aravind Akella9a844cf2014-02-11 18:58:52 -08001325bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001326 int handle = event.sensor;
1327 if (event.type == SENSOR_TYPE_META_DATA) {
1328 handle = event.meta_data.sensor;
1329 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001330 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001331 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001332}
1333
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001334int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1335 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1336 // UUID is not supported for this device.
1337 return 0;
1338 }
1339 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1340 // This sensor can be uniquely identified in the system by
1341 // the combination of its type and name.
1342 return -1;
1343 }
1344
1345 // We have a dynamic sensor.
1346
1347 if (!sHmacGlobalKeyIsValid) {
lifr3ab0a1b2021-08-06 00:14:26 +08001348 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001349 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1350 return 0;
1351 }
1352
1353 // We want each app author/publisher to get a different ID, so that the
1354 // same dynamic sensor cannot be tracked across apps by multiple
1355 // authors/publishers. So we use both our UUID and our User ID.
1356 // Note potential confusion:
1357 // UUID => Universally Unique Identifier.
1358 // UID => User Identifier.
1359 // We refrain from using "uid" except as needed by API to try to
1360 // keep this distinction clear.
1361
1362 auto appUserId = IPCThreadState::self()->getCallingUid();
1363 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1364 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1365 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1366
1367 // Now we use our key on our UUID/app combo to get the hash.
1368 uint8_t hash[EVP_MAX_MD_SIZE];
1369 unsigned int hashLen;
1370 if (HMAC(EVP_sha256(),
1371 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1372 uuidAndApp, sizeof(uuidAndApp),
1373 hash, &hashLen) == nullptr) {
lifr3ab0a1b2021-08-06 00:14:26 +08001374 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001375 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1376 return 0;
1377 }
1378
1379 int32_t id = 0;
1380 if (hashLen < sizeof(id)) {
1381 // We never expect this case, but out of paranoia, we handle it.
1382 // Our 'id' length is already quite small, we don't want the
1383 // effective length of it to be even smaller.
1384 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1385 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1386 return 0;
1387 }
1388
1389 // This is almost certainly less than all of 'hash', but it's as secure
1390 // as we can be with our current 'id' length.
1391 memcpy(&id, hash, sizeof(id));
1392
1393 // Note at the beginning of the function that we return the values of
1394 // 0 and -1 to represent special cases. As a result, we can't return
1395 // those as dynamic sensor IDs. If we happened to hash to one of those
1396 // values, we change 'id' so we report as a dynamic sensor, and not as
1397 // one of those special cases.
1398 if (id == -1) {
1399 id = -2;
1400 } else if (id == 0) {
1401 id = 1;
1402 }
1403 return id;
1404}
1405
1406void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1407 for (auto &sensor : sensorList) {
1408 int32_t id = getIdFromUuid(sensor.getUuid());
1409 sensor.setId(id);
Eric Laurente3f27df2022-01-05 19:20:32 +01001410 // The sensor UUID must always be anonymized here for non privileged clients.
1411 // There is no other checks after this point before returning to client process.
1412 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1413 sensor.anonymizeUuid();
1414 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001415 }
1416}
1417
Anh Pham4e291332021-02-10 14:17:56 +01001418Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -07001419 char value[PROPERTY_VALUE_MAX];
1420 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001421 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001422 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001423 Vector<Sensor> accessibleSensorList;
Anh Pham4e291332021-02-10 14:17:56 +01001424
Brian Duddie0d4ac562022-05-23 17:47:50 -07001425 resetTargetSdkVersionCache(opPackageName);
Anh Pham4e291332021-02-10 14:17:56 +01001426 bool isCapped = isRateCappedBasedOnPermission(opPackageName);
Aravind Akella70018042014-04-07 22:52:37 +00001427 for (size_t i = 0; i < initialSensorList.size(); i++) {
1428 Sensor sensor = initialSensorList[i];
Anh Pham4e291332021-02-10 14:17:56 +01001429 if (isCapped && isSensorInCappedSet(sensor.getType())) {
1430 sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
1431 sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
1432 }
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001433 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001434 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001435 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001436 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001437}
1438
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001439void SensorService::addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
1440 Vector<Sensor>& accessibleSensorList) {
1441 if (canAccessSensor(sensor, "can't see", opPackageName)) {
1442 accessibleSensorList.add(sensor);
1443 } else if (sensor.getType() != SENSOR_TYPE_HEAD_TRACKER) {
1444 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1445 sensor.getName().string(), sensor.getRequiredPermission().string(),
1446 sensor.getRequiredAppOp());
1447 }
1448}
1449
Peng Xu47e96012016-03-28 17:55:56 -07001450Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001451 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001452 mSensors.forEachSensor(
Brian Duddie4a4d0462022-05-09 16:49:49 -07001453 [this, &opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001454 if (sensor.isDynamicSensor()) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001455 addSensorIfAccessible(opPackageName, sensor, accessibleSensorList);
1456 }
1457 return true;
1458 });
1459 makeUuidsIntoIdsForSensorList(accessibleSensorList);
1460 return accessibleSensorList;
1461}
1462
1463Vector<Sensor> SensorService::getRuntimeSensorList(const String16& opPackageName, int deviceId) {
1464 Vector<Sensor> accessibleSensorList;
1465 mSensors.forEachEntry(
1466 [this, &opPackageName, deviceId, &accessibleSensorList] (
1467 const SensorServiceUtil::SensorList::Entry& e) -> bool {
1468 if (e.deviceId == deviceId) {
1469 addSensorIfAccessible(opPackageName, e.si->getSensor(), accessibleSensorList);
Peng Xu0cc8f802016-04-05 23:46:03 -07001470 }
1471 return true;
1472 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001473 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001474 return accessibleSensorList;
1475}
1476
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001477sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001478 int requestedMode, const String16& opPackageName, const String16& attributionTag) {
Anthony Stange9bb16702023-01-03 22:42:31 +00001479 // Only 3 modes supported for a SensorEventConnection ... NORMAL, DATA_INJECTION and
1480 // REPLAY_DATA_INJECTION.
1481 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION &&
1482 requestedMode != REPLAY_DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001483 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001484 }
Brian Duddie0d4ac562022-05-23 17:47:50 -07001485 resetTargetSdkVersionCache(opPackageName);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001486
1487 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001488 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1489 // operating in DI mode.
1490 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001491 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
Anthony Stangecd01ec12023-01-06 18:35:13 +00001492 if (!isAllowListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001493 }
1494
Mathias Agopian5307d172012-09-18 17:02:43 -07001495 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001496 pid_t pid = IPCThreadState::self()->getCallingPid();
1497
1498 String8 connPackageName =
1499 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1500 String16 connOpPackageName =
1501 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1502 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Anthony Stange9bb16702023-01-03 22:42:31 +00001503 requestedMode == DATA_INJECTION || requestedMode == REPLAY_DATA_INJECTION,
1504 connOpPackageName, attributionTag));
1505 if (requestedMode == DATA_INJECTION || requestedMode == REPLAY_DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001506 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001507 // Add the associated file descriptor to the Looper for polling whenever there is data to
1508 // be injected.
1509 result->updateLooperRegistration(mLooper);
1510 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001511 return result;
1512}
1513
Aravind Akella841a5922015-06-29 12:37:48 -07001514int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001515 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001516 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001517}
1518
Peng Xue36e3472016-11-03 11:57:10 -07001519sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1520 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1521 const native_handle *resource) {
Brian Duddie0d4ac562022-05-23 17:47:50 -07001522 resetTargetSdkVersionCache(opPackageName);
Brian Duddie967ce172019-06-10 11:08:27 -07001523 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001524
Michael Groover5e1f60b2018-12-04 22:34:29 -08001525 // No new direct connections are allowed when sensor privacy is enabled
1526 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1527 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1528 return nullptr;
1529 }
1530
Peng Xue36e3472016-11-03 11:57:10 -07001531 struct sensors_direct_mem_t mem = {
1532 .type = type,
1533 .format = format,
1534 .size = size,
1535 .handle = resource,
1536 };
1537 uid_t uid = IPCThreadState::self()->getCallingUid();
1538
1539 if (mem.handle == nullptr) {
1540 ALOGE("Failed to clone resource handle");
1541 return nullptr;
1542 }
1543
1544 // check format
1545 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1546 ALOGE("Direct channel format %d is unsupported!", format);
1547 return nullptr;
1548 }
1549
1550 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001551 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1552 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001553 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001554 return nullptr;
1555 }
1556 }
1557
1558 // check specific to memory type
1559 switch(type) {
1560 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001561 if (resource->numFds < 1) {
1562 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1563 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1564 return nullptr;
1565 }
Peng Xue36e3472016-11-03 11:57:10 -07001566 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001567 if (!ashmem_valid(fd)) {
1568 ALOGE("Supplied Ashmem memory region is invalid");
1569 return nullptr;
1570 }
1571
Peng Xue36e3472016-11-03 11:57:10 -07001572 int size2 = ashmem_get_size_region(fd);
1573 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001574 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001575 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1576 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001577 return nullptr;
1578 }
1579 break;
1580 }
1581 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001582 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001583 break;
1584 default:
1585 ALOGE("Unknown direct connection memory type %d", type);
1586 return nullptr;
1587 }
1588
1589 native_handle_t *clone = native_handle_clone(resource);
1590 if (!clone) {
1591 return nullptr;
1592 }
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001593 native_handle_set_fdsan_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001594
Brian Duddie967ce172019-06-10 11:08:27 -07001595 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001596 SensorDevice& dev(SensorDevice::getInstance());
1597 int channelHandle = dev.registerDirectChannel(&mem);
1598
1599 if (channelHandle <= 0) {
1600 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1601 } else {
1602 mem.handle = clone;
1603 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1604 }
1605
1606 if (conn == nullptr) {
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001607 native_handle_close_with_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001608 native_handle_delete(clone);
1609 } else {
1610 // add to list of direct connections
1611 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001612 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001613 }
1614 return conn;
1615}
1616
Peng Xudd5c5cb2017-03-16 17:39:43 -07001617int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001618 int32_t handle, int32_t type,
1619 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001620 Mutex::Autolock _l(mLock);
1621
Alexey Polyudov88711e82017-05-23 19:54:04 -07001622 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001623 return PERMISSION_DENIED;
1624 }
1625
1626 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001627 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001628 size_t expectSize = INT32_MAX;
1629 switch (type) {
1630 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1631 isFloat = true;
1632 expectSize = 3;
1633 break;
1634 case AINFO_LOCAL_GRAVITY:
1635 isFloat = true;
1636 expectSize = 1;
1637 break;
1638 case AINFO_DOCK_STATE:
1639 case AINFO_HIGH_PERFORMANCE_MODE:
1640 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1641 isFloat = false;
1642 expectSize = 1;
1643 break;
1644 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001645 // CUSTOM events must only contain float data; it may have variable size
1646 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1647 ints.size() ||
1648 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1649 handle < 0) {
1650 return BAD_VALUE;
1651 }
1652 isFloat = true;
1653 isCustom = true;
1654 expectSize = floats.size();
1655 break;
1656 }
1657
1658 if (!isCustom && handle != -1) {
1659 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001660 }
1661
1662 // three events: first one is begin tag, last one is end tag, the one in the middle
1663 // is the payload.
1664 sensors_event_t event[3];
1665 int64_t timestamp = elapsedRealtimeNano();
1666 for (sensors_event_t* i = event; i < event + 3; i++) {
1667 *i = (sensors_event_t) {
1668 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001669 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001670 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1671 .timestamp = timestamp++,
1672 .additional_info = (additional_info_event_t) {
1673 .serial = 0
1674 }
1675 };
1676 }
1677
1678 event[0].additional_info.type = AINFO_BEGIN;
1679 event[1].additional_info.type = type;
1680 event[2].additional_info.type = AINFO_END;
1681
1682 if (isFloat) {
1683 if (floats.size() != expectSize) {
1684 return BAD_VALUE;
1685 }
1686 for (size_t i = 0; i < expectSize; ++i) {
1687 event[1].additional_info.data_float[i] = floats[i];
1688 }
1689 } else {
1690 if (ints.size() != expectSize) {
1691 return BAD_VALUE;
1692 }
1693 for (size_t i = 0; i < expectSize; ++i) {
1694 event[1].additional_info.data_int32[i] = ints[i];
1695 }
1696 }
1697
1698 SensorDevice& dev(SensorDevice::getInstance());
1699 for (sensors_event_t* i = event; i < event + 3; i++) {
1700 int ret = dev.injectSensorData(i);
1701 if (ret != NO_ERROR) {
1702 return ret;
1703 }
1704 }
1705 return NO_ERROR;
1706}
1707
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001708status_t SensorService::resetToNormalMode() {
1709 Mutex::Autolock _l(mLock);
1710 return resetToNormalModeLocked();
1711}
1712
1713status_t SensorService::resetToNormalModeLocked() {
1714 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001715 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301716 if (err == NO_ERROR) {
1717 mCurrentOperatingMode = NORMAL;
1718 dev.enableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001719 checkAndReportProxStateChangeLocked();
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301720 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001721 return err;
1722}
1723
Peng Xu47e96012016-03-28 17:55:56 -07001724void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001725 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001726 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001727 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001728 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001729 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001730 int handle = mActiveSensors.keyAt(i);
1731 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001732 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001733 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001734 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001735 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001736 } else {
1737 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001738 }
Brian Duddie7be85572021-12-21 10:44:55 -08001739 if (c->removeSensor(handle)) {
1740 BatteryService::disableSensor(c->getUid(), handle);
1741 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001742 }
1743 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001744 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001745 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001746 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001747 c, i, handle);
1748
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001749 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001750 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001751 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001752 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001753 delete rec;
1754 size--;
1755 } else {
1756 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001757 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001758 }
Aravind Akella8a969552014-09-28 17:52:41 -07001759 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001760 mConnectionHolder.removeEventConnection(connection);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001761 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001762 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001763 }
Peng Xu4f707f82016-09-26 11:28:32 -07001764
1765 SensorDevice& dev(SensorDevice::getInstance());
1766 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001767}
1768
Peng Xue36e3472016-11-03 11:57:10 -07001769void SensorService::cleanupConnection(SensorDirectConnection* c) {
1770 Mutex::Autolock _l(mLock);
1771
1772 SensorDevice& dev(SensorDevice::getInstance());
1773 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001774 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001775}
1776
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001777void SensorService::checkAndReportProxStateChangeLocked() {
1778 if (mProxSensorHandles.empty()) return;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001779
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001780 SensorDevice& dev(SensorDevice::getInstance());
1781 bool isActive = false;
1782 for (auto& sensor : mProxSensorHandles) {
1783 if (dev.isSensorActive(sensor)) {
1784 isActive = true;
1785 break;
1786 }
1787 }
1788 if (isActive != mLastReportedProxIsActive) {
1789 notifyProximityStateLocked(isActive, mProximityActiveListeners);
1790 mLastReportedProxIsActive = isActive;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001791 }
1792}
1793
1794void SensorService::notifyProximityStateLocked(
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001795 const bool isActive,
Santos Cordon7ea287a2021-06-14 13:45:29 +01001796 const std::vector<sp<ProximityActiveListener>>& listeners) {
Santos Cordon7ea287a2021-06-14 13:45:29 +01001797 const uint64_t mySeq = ++curProxCallbackSeq;
1798 std::thread t([isActive, mySeq, listenersCopy = listeners]() {
1799 while (completedCallbackSeq.load() != mySeq - 1)
1800 std::this_thread::sleep_for(1ms);
1801 for (auto& listener : listenersCopy)
1802 listener->onProximityActive(isActive);
1803 completedCallbackSeq++;
1804 });
1805 t.detach();
Andrew Lehmer3a602572021-03-25 15:19:56 -07001806}
1807
1808status_t SensorService::addProximityActiveListener(const sp<ProximityActiveListener>& callback) {
1809 if (callback == nullptr) {
1810 return BAD_VALUE;
1811 }
1812
1813 Mutex::Autolock _l(mLock);
1814
1815 // Check if the callback was already added.
1816 for (const auto& cb : mProximityActiveListeners) {
1817 if (cb == callback) {
1818 return ALREADY_EXISTS;
1819 }
1820 }
1821
1822 mProximityActiveListeners.push_back(callback);
1823 std::vector<sp<ProximityActiveListener>> listener(1, callback);
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001824 notifyProximityStateLocked(mLastReportedProxIsActive, listener);
Andrew Lehmer3a602572021-03-25 15:19:56 -07001825 return OK;
1826}
1827
1828status_t SensorService::removeProximityActiveListener(
1829 const sp<ProximityActiveListener>& callback) {
1830 if (callback == nullptr) {
1831 return BAD_VALUE;
1832 }
1833
1834 Mutex::Autolock _l(mLock);
1835
1836 for (auto iter = mProximityActiveListeners.begin();
1837 iter != mProximityActiveListeners.end();
1838 ++iter) {
1839 if (*iter == callback) {
1840 mProximityActiveListeners.erase(iter);
1841 return OK;
1842 }
1843 }
1844 return NAME_NOT_FOUND;
1845}
1846
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001847std::shared_ptr<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001848 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001849}
1850
Mathias Agopianfc328812010-07-14 23:41:37 -07001851status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001852 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001853 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001854 if (mInitCheck != NO_ERROR)
1855 return mInitCheck;
1856
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001857 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001858 if (sensor == nullptr ||
1859 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001860 return BAD_VALUE;
1861 }
1862
Brian Duddie967ce172019-06-10 11:08:27 -07001863 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Anthony Stange9bb16702023-01-03 22:42:31 +00001864 if (mCurrentOperatingMode != NORMAL && mCurrentOperatingMode != REPLAY_DATA_INJECTION &&
Anthony Stangecd01ec12023-01-06 18:35:13 +00001865 !isAllowListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001866 return INVALID_OPERATION;
1867 }
1868
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001869 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001870 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001871 rec = new SensorRecord(connection);
1872 mActiveSensors.add(handle, rec);
1873 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001874 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001875 }
Brian Stack26029ee2019-04-22 17:25:49 -07001876
1877 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1878 // the recent event as stale to ensure that the previous event is not sent to a client. This
1879 // ensures on-change events that were generated during a previous sensor activation are not
1880 // erroneously sent to newly connected clients, especially if a second client registers for
1881 // an on-change sensor before the first client receives the updated event. Once an updated
1882 // event is received, the recent events will be marked as current, and any new clients will
1883 // immediately receive the most recent event.
1884 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1885 auto logger = mRecentEvent.find(handle);
1886 if (logger != mRecentEvent.end()) {
1887 logger->second->setLastEventStale();
1888 }
1889 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001890 } else {
1891 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001892 // this sensor is already activated, but we are adding a connection that uses it.
1893 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001894 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001895 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001896 // NOTE: The wake_up flag of this event may get set to
1897 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001898
1899 auto logger = mRecentEvent.find(handle);
1900 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001901 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001902 // Verify that the last sensor event was generated from the current activation
1903 // of the sensor. If not, it is possible for an on-change sensor to receive a
1904 // sensor event that is stale if two clients re-activate the sensor
1905 // simultaneously.
1906 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001907 event.sensor = handle;
1908 if (event.version == sizeof(sensors_event_t)) {
1909 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1910 setWakeLockAcquiredLocked(true);
1911 }
Yi Kong8f313e32018-07-17 14:13:29 -07001912 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001913 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001914 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001915 }
1916 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001917 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001918 }
1919 }
1920 }
1921 }
1922
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001923 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001924 BatteryService::enableSensor(connection->getUid(), handle);
1925 // the sensor was added (which means it wasn't already there)
1926 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001927 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001928 } else {
1929 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1930 handle, connection.get());
1931 }
1932
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301933 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001934 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301935 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1936 samplingPeriodNs = maxDelayNs;
1937 }
1938
Aravind Akella724d91d2013-06-27 12:04:23 -07001939 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1940 if (samplingPeriodNs < minDelayNs) {
1941 samplingPeriodNs = minDelayNs;
1942 }
1943
Aravind Akella6c2664a2014-08-13 12:24:50 -07001944 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1945 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001946 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1947
Aravind Akella4949c502015-02-11 15:54:35 -08001948 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001949 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001950
Peng Xu20483c42015-10-26 15:14:43 -07001951 // Call flush() before calling activate() on the sensor. Wait for a first
1952 // flush complete event before sending events on this connection. Ignore
1953 // one-shot sensors which don't support flush(). Ignore on-change sensors
1954 // to maintain the on-change logic (any on-change events except the initial
1955 // one should be trigger by a change in value). Also if this sensor isn't
1956 // already active, don't call flush().
1957 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001958 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001959 rec->getNumConnections() > 1) {
1960 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001961 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001962 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001963 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001964 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001965 } else {
1966 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001967 }
1968 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001969
1970 if (err == NO_ERROR) {
1971 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1972 err = sensor->activate(connection.get(), true);
1973 }
1974
Aravind Akella8a969552014-09-28 17:52:41 -07001975 if (err == NO_ERROR) {
1976 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001977
Brian Stack240d1d62019-05-17 09:49:39 -07001978 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1979 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001980 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1981 }
1982
Peng Xu51224682017-03-10 16:57:27 -08001983 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1984 SensorRegistrationInfo(handle, connection->getPackageName(),
1985 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001986 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001987 }
1988
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001989 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001990 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001991 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001992 }
1993 return err;
1994}
1995
Peng Xu47e96012016-03-28 17:55:56 -07001996status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001997 if (mInitCheck != NO_ERROR)
1998 return mInitCheck;
1999
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002000 Mutex::Autolock _l(mLock);
2001 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002002 if (err == NO_ERROR) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002003 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002004 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07002005
2006 }
2007 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08002008 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2009 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07002010 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002011 }
2012 return err;
2013}
2014
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002015status_t SensorService::cleanupWithoutDisable(
2016 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002017 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002018 return cleanupWithoutDisableLocked(connection, handle);
2019}
2020
2021status_t SensorService::cleanupWithoutDisableLocked(
2022 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002023 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002024 if (rec) {
2025 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07002026 if (connection->removeSensor(handle)) {
2027 BatteryService::disableSensor(connection->getUid(), handle);
2028 }
Mathias Agopianfc328812010-07-14 23:41:37 -07002029 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07002030 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07002031 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07002032 }
2033 // see if this sensor becomes inactive
2034 if (rec->removeConnection(connection)) {
2035 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002036 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002037 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07002038 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002039 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002040 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002041 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07002042}
2043
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002044status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07002045 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002046 if (mInitCheck != NO_ERROR)
2047 return mInitCheck;
2048
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002049 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002050 if (sensor == nullptr ||
2051 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00002052 return BAD_VALUE;
2053 }
2054
Mathias Agopian1cd70002010-07-21 15:59:50 -07002055 if (ns < 0)
2056 return BAD_VALUE;
2057
Mathias Agopian62569ec2011-11-07 21:21:47 -08002058 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2059 if (ns < minDelayNs) {
2060 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07002061 }
2062
Mathias Agopianf001c922010-11-11 17:58:51 -08002063 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07002064}
2065
Svetoslavb412f6e2015-04-29 16:50:41 -07002066status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
2067 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00002068 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002069 SensorDevice& dev(SensorDevice::getInstance());
2070 const int halVersion = dev.getHalDeviceVersion();
2071 status_t err(NO_ERROR);
2072 Mutex::Autolock _l(mLock);
2073 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07002074 for (int handle : connection->getActiveSensorHandles()) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002075 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002076 if (sensor == nullptr) {
2077 continue;
2078 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002079 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
2080 ALOGE("flush called on a one-shot sensor");
2081 err = INVALID_OPERATION;
2082 continue;
2083 }
Aravind Akella8493b792014-09-08 15:45:47 -07002084 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002085 // For older devices just increment pending flush count which will send a trivial
2086 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07002087 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
2088 ALOGE("flush called on an inaccessible sensor");
2089 err = INVALID_OPERATION;
2090 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002091 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002092 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
2093 err = INVALID_OPERATION;
2094 continue;
2095 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002096 status_t err_flush = sensor->flush(connection.get(), handle);
2097 if (err_flush == NO_ERROR) {
2098 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07002099 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002100 }
2101 err = (err_flush != NO_ERROR) ? err_flush : err;
2102 }
Aravind Akella70018042014-04-07 22:52:37 +00002103 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07002104 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07002105}
Aravind Akella70018042014-04-07 22:52:37 +00002106
Svetoslavb412f6e2015-04-29 16:50:41 -07002107bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
2108 const String16& opPackageName) {
Brian Duddie4a4d0462022-05-09 16:49:49 -07002109 // Special case for Head Tracker sensor type: currently restricted to system usage only, unless
2110 // the restriction is specially lifted for testing
2111 if (sensor.getType() == SENSOR_TYPE_HEAD_TRACKER &&
2112 !isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
2113 if (!mHtRestricted) {
2114 ALOGI("Permitting access to HT sensor type outside system (%s)",
2115 String8(opPackageName).string());
2116 } else {
2117 ALOGW("%s %s a sensor (%s) as a non-system client", String8(opPackageName).string(),
2118 operation, sensor.getName().string());
2119 return false;
2120 }
2121 }
2122
Brian Stack793f4642019-04-18 17:21:34 -07002123 // Check if a permission is required for this sensor
2124 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00002125 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07002126 }
2127
Brian Stack793f4642019-04-18 17:21:34 -07002128 const int32_t opCode = sensor.getRequiredAppOp();
Brian Duddie457e6392020-06-19 11:38:29 -07002129 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07002130
Brian Stack793f4642019-04-18 17:21:34 -07002131 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07002132 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
2133 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
2134 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
2135 // Allow access to step sensors if the application targets pre-Q, which is before the
2136 // requirement to hold the AR permission to access Step Counter and Step Detector events
2137 // was introduced.
2138 canAccess = true;
2139 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07002140 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002141 if (opCode >= 0) {
2142 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
2143 IPCThreadState::self()->getCallingUid(), opPackageName);
2144 canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
2145 } else {
Brian Stack793f4642019-04-18 17:21:34 -07002146 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07002147 }
Brian Stack793f4642019-04-18 17:21:34 -07002148 }
2149
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002150 if (!canAccess) {
Brian Duddie457e6392020-06-19 11:38:29 -07002151 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
2152 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07002153 }
2154
2155 return canAccess;
2156}
2157
2158bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07002159 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07002160 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07002161
2162 // Runtime permissions can't use the cache as they may change.
2163 if (sensor.isRequiredPermissionRuntime()) {
2164 hasPermission = checkPermission(String16(requiredPermission),
matthuang65794462022-03-24 16:02:57 +08002165 IPCThreadState::self()->getCallingPid(),
2166 IPCThreadState::self()->getCallingUid(),
2167 /*logPermissionFailure=*/ false);
Aravind Akella70018042014-04-07 22:52:37 +00002168 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002169 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
2170 }
Brian Stack793f4642019-04-18 17:21:34 -07002171 return hasPermission;
2172}
Svetoslavb412f6e2015-04-29 16:50:41 -07002173
Brian Stack793f4642019-04-18 17:21:34 -07002174int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Anthony Stange07eb4212020-08-28 14:50:28 -04002175 // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
2176 // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
2177 // give it elevated privileges.
2178 if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
2179 return -1;
2180 }
2181
Brian Stack793f4642019-04-18 17:21:34 -07002182 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2183 int targetSdkVersion = -1;
2184 auto entry = sPackageTargetVersion.find(opPackageName);
2185 if (entry != sPackageTargetVersion.end()) {
2186 targetSdkVersion = entry->second;
2187 } else {
2188 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2189 if (binder != nullptr) {
2190 sp<content::pm::IPackageManagerNative> packageManager =
2191 interface_cast<content::pm::IPackageManagerNative>(binder);
2192 if (packageManager != nullptr) {
2193 binder::Status status = packageManager->getTargetSdkVersionForPackage(
2194 opPackageName, &targetSdkVersion);
2195 if (!status.isOk()) {
2196 targetSdkVersion = -1;
2197 }
2198 }
Svetoslavb412f6e2015-04-29 16:50:41 -07002199 }
Brian Stack793f4642019-04-18 17:21:34 -07002200 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07002201 }
Brian Stack793f4642019-04-18 17:21:34 -07002202 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00002203}
2204
Brian Duddie0d4ac562022-05-23 17:47:50 -07002205void SensorService::resetTargetSdkVersionCache(const String16& opPackageName) {
2206 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2207 auto iter = sPackageTargetVersion.find(opPackageName);
2208 if (iter != sPackageTargetVersion.end()) {
2209 sPackageTargetVersion.erase(iter);
2210 }
2211}
2212
Anthony Stangec1608152023-01-06 21:14:46 +00002213bool SensorService::getTargetOperatingMode(const std::string &inputString, Mode *targetModeOut) {
2214 if (inputString == std::string("restrict")) {
2215 *targetModeOut = RESTRICTED;
2216 return true;
2217 }
2218 if (inputString == std::string("enable")) {
2219 *targetModeOut = NORMAL;
2220 return true;
2221 }
2222 if (inputString == std::string("data_injection")) {
2223 *targetModeOut = DATA_INJECTION;
2224 return true;
2225 }
2226 if (inputString == std::string("replay_data_injection")) {
2227 *targetModeOut = REPLAY_DATA_INJECTION;
2228 return true;
2229 }
2230 return false;
2231}
2232
2233status_t SensorService::changeOperatingMode(const Vector<String16>& args,
2234 Mode targetOperatingMode) {
2235 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2236 SensorDevice& dev(SensorDevice::getInstance());
2237 if (mCurrentOperatingMode == targetOperatingMode) {
2238 return NO_ERROR;
2239 }
2240 if (targetOperatingMode != NORMAL && args.size() < 2) {
2241 return INVALID_OPERATION;
2242 }
2243 switch (targetOperatingMode) {
2244 case NORMAL:
2245 // If currently in restricted mode, reset back to NORMAL mode else ignore.
2246 if (mCurrentOperatingMode == RESTRICTED) {
2247 mCurrentOperatingMode = NORMAL;
2248 // enable sensors and recover all sensor direct report
2249 enableAllSensorsLocked(&connLock);
2250 }
2251 if (mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
2252 dev.disableAllSensors();
2253 }
2254 if (mCurrentOperatingMode == DATA_INJECTION ||
2255 mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
2256 resetToNormalModeLocked();
2257 }
2258 mAllowListedPackage.clear();
2259 return status_t(NO_ERROR);
2260 case RESTRICTED:
2261 // If in any mode other than normal, ignore.
2262 if (mCurrentOperatingMode != NORMAL) {
2263 return INVALID_OPERATION;
2264 }
2265
2266 mCurrentOperatingMode = RESTRICTED;
2267 // temporarily stop all sensor direct report and disable sensors
2268 disableAllSensorsLocked(&connLock);
2269 mAllowListedPackage.setTo(String8(args[1]));
2270 return status_t(NO_ERROR);
2271 case REPLAY_DATA_INJECTION:
2272 if (SensorServiceUtil::isUserBuild()) {
2273 return INVALID_OPERATION;
2274 }
2275 FALLTHROUGH_INTENDED;
2276 case DATA_INJECTION:
2277 if (mCurrentOperatingMode == NORMAL) {
2278 dev.disableAllSensors();
2279 // Always use DATA_INJECTION here since this value goes to the HAL and the HAL
2280 // doesn't have an understanding of replay vs. normal data injection.
2281 status_t err = dev.setMode(DATA_INJECTION);
2282 if (err == NO_ERROR) {
2283 mCurrentOperatingMode = targetOperatingMode;
2284 }
2285 if (err != NO_ERROR || targetOperatingMode == REPLAY_DATA_INJECTION) {
2286 // Re-enable sensors.
2287 dev.enableAllSensors();
2288 }
2289 mAllowListedPackage.setTo(String8(args[1]));
2290 return NO_ERROR;
2291 } else {
2292 // Transition to data injection mode supported only from NORMAL mode.
2293 return INVALID_OPERATION;
2294 }
2295 break;
2296 default:
2297 break;
2298 }
2299 return NO_ERROR;
2300}
2301
Aravind Akella9a844cf2014-02-11 18:58:52 -08002302void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07002303 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2304 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08002305}
2306
Brian Duddie967ce172019-06-10 11:08:27 -07002307void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002308 if (!mWakeLockAcquired) {
2309 return;
2310 }
2311 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07002312 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
2313 if (connection->needsWakeLock()) {
2314 releaseLock = false;
2315 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08002316 }
2317 }
2318 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07002319 setWakeLockAcquiredLocked(false);
2320 }
2321}
2322
2323void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
2324 Mutex::Autolock _l(mLock);
2325 connection->writeToSocketFromCache();
2326 if (connection->needsWakeLock()) {
2327 setWakeLockAcquiredLocked(true);
2328 }
2329}
2330
Anthony Stangecd01ec12023-01-06 18:35:13 +00002331bool SensorService::isAllowListedPackage(const String8& packageName) {
2332 return (packageName.contains(mAllowListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08002333}
2334
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002335bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08002336 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07002337 String8 package(opPackageName);
Anthony Stangecd01ec12023-01-06 18:35:13 +00002338 return !isAllowListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07002339 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002340 return false;
Peng Xue36e3472016-11-03 11:57:10 -07002341}
2342
Svet Ganove752a5c2018-01-15 17:14:20 -08002343void SensorService::UidPolicy::registerSelf() {
2344 ActivityManager am;
2345 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
2346 | ActivityManager::UID_OBSERVER_IDLE
2347 | ActivityManager::UID_OBSERVER_ACTIVE,
2348 ActivityManager::PROCESS_STATE_UNKNOWN,
2349 String16("android"));
2350}
2351
2352void SensorService::UidPolicy::unregisterSelf() {
2353 ActivityManager am;
2354 am.unregisterUidObserver(this);
2355}
2356
2357void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
2358 onUidIdle(uid, disabled);
2359}
2360
2361void SensorService::UidPolicy::onUidActive(uid_t uid) {
2362 {
2363 Mutex::Autolock _l(mUidLock);
2364 mActiveUids.insert(uid);
2365 }
2366 sp<SensorService> service = mService.promote();
2367 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002368 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002369 }
2370}
2371
2372void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
2373 bool deleted = false;
2374 {
2375 Mutex::Autolock _l(mUidLock);
2376 if (mActiveUids.erase(uid) > 0) {
2377 deleted = true;
2378 }
2379 }
2380 if (deleted) {
2381 sp<SensorService> service = mService.promote();
2382 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002383 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002384 }
2385 }
2386}
2387
2388void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
2389 updateOverrideUid(uid, active, true);
2390}
2391
2392void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
2393 updateOverrideUid(uid, false, false);
2394}
2395
2396void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
2397 bool wasActive = false;
2398 bool isActive = false;
2399 {
2400 Mutex::Autolock _l(mUidLock);
2401 wasActive = isUidActiveLocked(uid);
2402 mOverrideUids.erase(uid);
2403 if (insert) {
2404 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2405 }
2406 isActive = isUidActiveLocked(uid);
2407 }
2408 if (wasActive != isActive) {
2409 sp<SensorService> service = mService.promote();
2410 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002411 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002412 }
2413 }
2414}
2415
2416bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2417 // Non-app UIDs are considered always active
2418 if (uid < FIRST_APPLICATION_UID) {
2419 return true;
2420 }
2421 Mutex::Autolock _l(mUidLock);
2422 return isUidActiveLocked(uid);
2423}
2424
2425bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2426 // Non-app UIDs are considered always active
2427 if (uid < FIRST_APPLICATION_UID) {
2428 return true;
2429 }
2430 auto it = mOverrideUids.find(uid);
2431 if (it != mOverrideUids.end()) {
2432 return it->second;
2433 }
2434 return mActiveUids.find(uid) != mActiveUids.end();
2435}
2436
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002437bool SensorService::isUidActive(uid_t uid) {
2438 return mUidPolicy->isUidActive(uid);
2439}
2440
Anh Phamaf91a912021-02-10 14:10:53 +01002441bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2442 int targetSdk = getTargetSdkVersion(opPackageName);
Anh Phama5538232021-06-23 08:41:11 +02002443 bool hasSamplingRatePermission = checkPermission(sAccessHighSensorSamplingRatePermission,
2444 IPCThreadState::self()->getCallingPid(),
matthuang65794462022-03-24 16:02:57 +08002445 IPCThreadState::self()->getCallingUid(),
2446 /*logPermissionFailure=*/ false);
Anh Phamaf91a912021-02-10 14:10:53 +01002447 if (targetSdk < __ANDROID_API_S__ ||
2448 (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2449 return false;
2450 }
2451 return true;
2452}
2453
Anh Pham3dae77f2021-06-11 16:24:37 +02002454/**
2455 * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS
2456 * permission.
2457 *
2458 * This needs to be kept in sync with the list defined on the Java side
2459 * in frameworks/base/core/java/android/hardware/SystemSensorManager.java
2460 */
Anh Phamaf91a912021-02-10 14:10:53 +01002461bool SensorService::isSensorInCappedSet(int sensorType) {
2462 return (sensorType == SENSOR_TYPE_ACCELEROMETER
2463 || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2464 || sensorType == SENSOR_TYPE_GYROSCOPE
2465 || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2466 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2467 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2468}
2469
2470status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2471 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002472 if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2473 return OK;
2474 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002475 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002476 if (shouldCapBasedOnPermission) {
2477 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2478 if (isPackageDebuggable(opPackageName)) {
2479 return PERMISSION_DENIED;
2480 }
2481 return OK;
2482 }
Evan Severson4c197852022-01-27 10:44:27 -08002483 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002484 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2485 return OK;
2486 }
Anh Phamaf91a912021-02-10 14:10:53 +01002487 return OK;
2488}
2489
2490status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2491 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002492 if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2493 return OK;
2494 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002495 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002496 if (shouldCapBasedOnPermission) {
2497 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2498 if (isPackageDebuggable(opPackageName)) {
2499 return PERMISSION_DENIED;
2500 }
2501 return OK;
2502 }
Evan Severson4c197852022-01-27 10:44:27 -08002503 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002504 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2505 return OK;
2506 }
Anh Phamaf91a912021-02-10 14:10:53 +01002507 return OK;
2508}
2509
Michael Groover5e1f60b2018-12-04 22:34:29 -08002510void SensorService::SensorPrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002511 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002512 SensorPrivacyManager spm;
2513 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2514 spm.addSensorPrivacyListener(this);
2515}
2516
2517void SensorService::SensorPrivacyPolicy::unregisterSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002518 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002519 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002520 spm.removeSensorPrivacyListener(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -08002521}
2522
2523bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2524 return mSensorPrivacyEnabled;
2525}
2526
Evan Severson4c197852022-01-27 10:44:27 -08002527binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2528 int sensor __unused, bool enabled) {
Michael Groover5e1f60b2018-12-04 22:34:29 -08002529 mSensorPrivacyEnabled = enabled;
2530 sp<SensorService> service = mService.promote();
Anh Pham5198c992021-02-10 14:15:30 +01002531
Michael Groover5e1f60b2018-12-04 22:34:29 -08002532 if (service != nullptr) {
Evan Severson4c197852022-01-27 10:44:27 -08002533 if (enabled) {
2534 service->disableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002535 } else {
Evan Severson4c197852022-01-27 10:44:27 -08002536 service->enableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002537 }
2538 }
2539 return binder::Status::ok();
2540}
Brian Duddie967ce172019-06-10 11:08:27 -07002541
Evan Severson4c197852022-01-27 10:44:27 -08002542void SensorService::MicrophonePrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002543 AutoCallerClear acc;
Anh Pham5198c992021-02-10 14:15:30 +01002544 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002545 mSensorPrivacyEnabled =
2546 spm.isToggleSensorPrivacyEnabled(
2547 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
2548 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE)
2549 || spm.isToggleSensorPrivacyEnabled(
2550 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE,
2551 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE);
2552 spm.addToggleSensorPrivacyListener(this);
Anh Pham5198c992021-02-10 14:15:30 +01002553}
2554
Evan Severson4c197852022-01-27 10:44:27 -08002555void SensorService::MicrophonePrivacyPolicy::unregisterSelf() {
2556 AutoCallerClear acc;
2557 SensorPrivacyManager spm;
2558 spm.removeToggleSensorPrivacyListener(this);
2559}
2560
2561binder::Status SensorService::MicrophonePrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2562 int sensor, bool enabled) {
2563 if (sensor != SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE) {
2564 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002565 }
Evan Severson4c197852022-01-27 10:44:27 -08002566 mSensorPrivacyEnabled = enabled;
2567 sp<SensorService> service = mService.promote();
2568
2569 if (service != nullptr) {
2570 if (enabled) {
2571 service->capRates();
2572 } else {
2573 service->uncapRates();
2574 }
2575 }
2576 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002577}
2578
Brian Duddie967ce172019-06-10 11:08:27 -07002579SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2580 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2581 : mConnectionHolder(holder), mAutolock(mutex) {}
2582
2583template<typename ConnectionType>
2584const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2585 const SortedVector<wp<ConnectionType>>& connectionList,
2586 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2587 referenceHolder->emplace_back();
2588 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2589 for (const wp<ConnectionType>& weakConnection : connectionList){
2590 sp<ConnectionType> connection = weakConnection.promote();
2591 if (connection != nullptr) {
2592 connections.push_back(std::move(connection));
2593 }
2594 }
2595 return connections;
2596}
2597
2598const std::vector<sp<SensorService::SensorEventConnection>>&
2599 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2600 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2601 &mReferencedActiveConnections);
2602}
2603
2604const std::vector<sp<SensorService::SensorDirectConnection>>&
2605 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2606 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2607 &mReferencedDirectConnections);
2608}
2609
2610void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2611 const sp<SensorService::SensorEventConnection>& connection) {
2612 if (mActiveConnections.indexOf(connection) < 0) {
2613 mActiveConnections.add(connection);
2614 }
2615}
2616
2617void SensorService::SensorConnectionHolder::removeEventConnection(
2618 const wp<SensorService::SensorEventConnection>& connection) {
2619 mActiveConnections.remove(connection);
2620}
2621
2622void SensorService::SensorConnectionHolder::addDirectConnection(
2623 const sp<SensorService::SensorDirectConnection>& connection) {
2624 mDirectConnections.add(connection);
2625}
2626
2627void SensorService::SensorConnectionHolder::removeDirectConnection(
2628 const wp<SensorService::SensorDirectConnection>& connection) {
2629 mDirectConnections.remove(connection);
2630}
2631
2632SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2633 return ConnectionSafeAutolock(*this, mutex);
2634}
2635
Anh Phamaf91a912021-02-10 14:10:53 +01002636bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2637 bool debugMode = false;
2638 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2639 if (binder != nullptr) {
2640 sp<content::pm::IPackageManagerNative> packageManager =
2641 interface_cast<content::pm::IPackageManagerNative>(binder);
2642 if (packageManager != nullptr) {
2643 binder::Status status = packageManager->isPackageDebuggable(
2644 opPackageName, &debugMode);
2645 }
2646 }
2647 return debugMode;
2648}
Brian Duddie967ce172019-06-10 11:08:27 -07002649} // namespace android