blob: 7124d35bde7a1e85fd1909e0b65f0f6609cb6f09 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Anh Phamaf91a912021-02-10 14:10:53 +010016#include <android-base/strings.h>
Brian Stack793f4642019-04-18 17:21:34 -070017#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080018#include <android/util/ProtoOutputStream.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080019#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070021#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070022#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080023#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070024#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080025#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070026#include <cutils/properties.h>
Brian Duddie0a4cebb2022-08-25 19:20:18 +000027#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070028#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070029#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080030#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070031#include <openssl/digest.h>
32#include <openssl/hmac.h>
33#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070034#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080035#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070036#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070037
Mathias Agopian787ac1b2012-09-18 18:49:18 -070038#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070039#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080040#include "GravitySensor.h"
Tyler Trephanc7b92632021-07-21 10:39:38 -070041#include "LimitedAxesImuSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080042#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070043#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080044#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070045#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070046#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080047
Mathias Agopian984826c2011-05-17 22:54:42 -070048#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070049#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080050#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080051#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080052#include "SensorRecord.h"
53#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080054
55#include <inttypes.h>
56#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070057#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080058#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080059#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070060#include <sys/stat.h>
61#include <sys/types.h>
62#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070063
Andrew Lehmer3a602572021-03-25 15:19:56 -070064#include <ctime>
65#include <future>
66
Svet Ganove752a5c2018-01-15 17:14:20 -080067#include <private/android_filesystem_config.h>
68
Andrew Lehmer3a602572021-03-25 15:19:56 -070069using namespace std::chrono_literals;
70
Mathias Agopianfc328812010-07-14 23:41:37 -070071namespace android {
72// ---------------------------------------------------------------------------
73
Mathias Agopian33015422011-05-27 18:18:13 -070074/*
75 * Notes:
76 *
77 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070078 * - run mag sensor from time to time to force calibration
79 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
80 *
81 */
82
Aravind Akella8ef3c892015-07-10 11:24:28 -070083const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070084uint8_t SensorService::sHmacGlobalKey[128] = {};
85bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070086std::map<String16, int> SensorService::sPackageTargetVersion;
87Mutex SensorService::sPackageTargetVersionLock;
Anthony Stange07eb4212020-08-28 14:50:28 -040088String16 SensorService::sSensorInterfaceDescriptorPrefix =
89 String16("android.frameworks.sensorservice@");
Brian Stack793f4642019-04-18 17:21:34 -070090AppOpsManager SensorService::sAppOpsManager;
Andrew Lehmer3a602572021-03-25 15:19:56 -070091std::atomic_uint64_t SensorService::curProxCallbackSeq(0);
92std::atomic_uint64_t SensorService::completedCallbackSeq(0);
Greg Kaiser53ca2e02016-06-21 16:11:14 -070093
94#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
95#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070096#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070097
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070098// Permissions.
Anh Phamaf91a912021-02-10 14:10:53 +010099static const String16 sAccessHighSensorSamplingRatePermission(
100 "android.permission.HIGH_SAMPLING_RATE_SENSORS");
Peng Xudd5c5cb2017-03-16 17:39:43 -0700101static const String16 sDumpPermission("android.permission.DUMP");
102static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -0800103static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700104
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200105namespace {
106
107// TODO(b/259227294): Move the sensor ranges to the HAL.
108int32_t nextRuntimeSensorHandle() {
109 static constexpr int32_t kRuntimeHandleBase = 0x5F000000;
110 static constexpr int32_t kRuntimeHandleEnd = 0x5FFFFFFF;
111 static int32_t nextHandle = kRuntimeHandleBase;
112 if (nextHandle == kRuntimeHandleEnd) {
113 return -1;
114 }
115 return nextHandle++;
116}
117
118class RuntimeSensorCallbackProxy : public RuntimeSensor::StateChangeCallback {
119 public:
120 RuntimeSensorCallbackProxy(sp<SensorService::RuntimeSensorStateChangeCallback> callback)
121 : mCallback(std::move(callback)) {}
122 void onStateChanged(bool enabled, int64_t samplingPeriodNs,
123 int64_t batchReportLatencyNs) override {
124 mCallback->onStateChanged(enabled, samplingPeriodNs, batchReportLatencyNs);
125 }
126 private:
127 sp<SensorService::RuntimeSensorStateChangeCallback> mCallback;
128};
129
130} // namespace
131
Tyler Trephanc7b92632021-07-21 10:39:38 -0700132static bool isAutomotive() {
133 sp<IServiceManager> serviceManager = defaultServiceManager();
134 if (serviceManager.get() == nullptr) {
135 ALOGE("%s: unable to access native ServiceManager", __func__);
136 return false;
137 }
138
139 sp<content::pm::IPackageManagerNative> packageManager;
140 sp<IBinder> binder = serviceManager->waitForService(String16("package_native"));
141 packageManager = interface_cast<content::pm::IPackageManagerNative>(binder);
142 if (packageManager == nullptr) {
143 ALOGE("%s: unable to access native PackageManager", __func__);
144 return false;
145 }
146
147 bool isAutomotive = false;
148 binder::Status status =
149 packageManager->hasSystemFeature(String16("android.hardware.type.automotive"), 0,
150 &isAutomotive);
151 if (!status.isOk()) {
152 ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str());
153 return false;
154 }
155
156 return isAutomotive;
157}
158
Mathias Agopianfc328812010-07-14 23:41:37 -0700159SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -0700160 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700161 mWakeLockAcquired(false), mLastReportedProxIsActive(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +0900162 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800163 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Evan Severson4c197852022-01-27 10:44:27 -0800164 mMicSensorPrivacyPolicy = new MicrophonePrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700165}
166
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200167int SensorService::registerRuntimeSensor(
168 const sensor_t& sensor, int deviceId, sp<RuntimeSensorStateChangeCallback> callback) {
169 int handle = 0;
170 while (handle == 0 || !mSensors.isNewHandle(handle)) {
171 handle = nextRuntimeSensorHandle();
172 if (handle < 0) {
173 // Ran out of the dedicated range for runtime sensors.
174 return handle;
175 }
176 }
177
178 ALOGI("Registering runtime sensor handle 0x%x, type %d, name %s",
179 handle, sensor.type, sensor.name);
180
181 sp<RuntimeSensor::StateChangeCallback> runtimeSensorCallback(
182 new RuntimeSensorCallbackProxy(std::move(callback)));
183 sensor_t runtimeSensor = sensor;
184 // force the handle to be consistent
185 runtimeSensor.handle = handle;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100186 auto si = std::make_shared<RuntimeSensor>(runtimeSensor, std::move(runtimeSensorCallback));
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200187
188 Mutex::Autolock _l(mLock);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100189 if (!registerSensor(std::move(si), /* isDebug= */ false, /* isVirtual= */ false, deviceId)) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200190 // The registration was unsuccessful.
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100191 return mSensors.getNonSensor().getHandle();
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200192 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100193
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200194 return handle;
195}
196
197status_t SensorService::unregisterRuntimeSensor(int handle) {
198 ALOGI("Unregistering runtime sensor handle 0x%x disconnected", handle);
199 {
200 Mutex::Autolock _l(mLock);
201 if (!unregisterDynamicSensorLocked(handle)) {
202 ALOGE("Runtime sensor release error.");
203 return UNKNOWN_ERROR;
204 }
205 }
206
207 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
208 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
209 connection->removeSensor(handle);
210 }
211 return OK;
212}
213
214status_t SensorService::sendRuntimeSensorEvent(const sensors_event_t& event) {
215 Mutex::Autolock _l(mLock);
216 mRuntimeSensorEventQueue.push(event);
217 return OK;
218}
219
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700220bool SensorService::initializeHmacKey() {
221 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
222 if (fd != -1) {
223 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
224 close(fd);
225 if (result == sizeof(sHmacGlobalKey)) {
226 return true;
227 }
228 ALOGW("Unable to read HMAC key; generating new one.");
229 }
230
231 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
232 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
233 return false;
234 }
235
236 // We need to make sure this is only readable to us.
237 bool wroteKey = false;
238 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
239 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
240 S_IRUSR|S_IWUSR);
241 if (fd != -1) {
242 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
243 close(fd);
244 wroteKey = (result == sizeof(sHmacGlobalKey));
245 }
246 if (wroteKey) {
247 ALOGI("Generated new HMAC key.");
248 } else {
249 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
250 "after reboot.");
251 }
252 // Even if we failed to write the key we return true, because we did
253 // initialize the HMAC key.
254 return true;
255}
256
Peng Xu98d30f62016-08-01 18:12:11 -0700257// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
258void SensorService::enableSchedFifoMode() {
259 struct sched_param param = {0};
260 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
261 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
262 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
263 }
264}
265
Peng Xu47e96012016-03-28 17:55:56 -0700266void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000267 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800268 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700269
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700270 sHmacGlobalKeyIsValid = initializeHmacKey();
271
Mathias Agopianf001c922010-11-11 17:58:51 -0800272 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800273 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700274 ssize_t count = dev.getSensorList(&list);
275 if (count > 0) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700276 bool hasGyro = false, hasAccel = false, hasMag = false;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700277 bool hasGyroUncalibrated = false;
278 bool hasAccelUncalibrated = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700279 uint32_t virtualSensorsNeeds =
280 (1<<SENSOR_TYPE_GRAVITY) |
281 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700282 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
283 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
284 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700285
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700286 for (ssize_t i=0 ; i<count ; i++) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700287 bool useThisSensor = true;
Peng Xuf66684a2015-07-23 11:41:53 -0700288
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700289 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700290 case SENSOR_TYPE_ACCELEROMETER:
291 hasAccel = true;
292 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700293 case SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED:
294 hasAccelUncalibrated = true;
295 break;
Aravind Akellaf5047892015-07-20 17:29:33 -0700296 case SENSOR_TYPE_MAGNETIC_FIELD:
297 hasMag = true;
298 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700299 case SENSOR_TYPE_GYROSCOPE:
300 hasGyro = true;
301 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700302 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
303 hasGyroUncalibrated = true;
304 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700305 case SENSOR_TYPE_GRAVITY:
306 case SENSOR_TYPE_LINEAR_ACCELERATION:
307 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700308 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
309 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
310 if (IGNORE_HARDWARE_FUSION) {
311 useThisSensor = false;
312 } else {
313 virtualSensorsNeeds &= ~(1<<list[i].type);
314 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700315 break;
Arthur Ishiguro2fd90a72021-11-12 17:24:41 +0000316 default:
317 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700318 }
Peng Xuf66684a2015-07-23 11:41:53 -0700319 if (useThisSensor) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700320 if (list[i].type == SENSOR_TYPE_PROXIMITY) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100321 auto s = std::make_shared<ProximitySensor>(list[i], *this);
322 const int handle = s->getSensor().getHandle();
323 if (registerSensor(std::move(s))) {
324 mProxSensorHandles.push_back(handle);
325 }
Andrew Lehmer3a602572021-03-25 15:19:56 -0700326 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100327 registerSensor(std::make_shared<HardwareSensor>(list[i]));
Andrew Lehmer3a602572021-03-25 15:19:56 -0700328 }
Peng Xuf66684a2015-07-23 11:41:53 -0700329 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700330 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700331
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700332 // it's safe to instantiate the SensorFusion object here
333 // (it wants to be instantiated after h/w sensors have been
334 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700335 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700336
Tyler Trephanc7b92632021-07-21 10:39:38 -0700337 if ((hasGyro || hasGyroUncalibrated) && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700338 // Add Android virtual sensors if they're not already
339 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700340 bool needRotationVector =
341 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100342 registerVirtualSensor(std::make_shared<RotationVectorSensor>(),
343 /* isDebug= */ !needRotationVector);
344 registerVirtualSensor(std::make_shared<OrientationSensor>(),
345 /* isDebug= */ !needRotationVector);
Mathias Agopian03193062013-05-10 19:32:39 -0700346
Peng Xu0cc8f802016-04-05 23:46:03 -0700347 // virtual debugging sensors are not for user
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100348 registerVirtualSensor(std::make_shared<CorrectedGyroSensor>(list, count),
349 /* isDebug= */ true);
350 registerVirtualSensor(std::make_shared<GyroDriftSensor>(), /* isDebug= */ true);
Mathias Agopian33264862012-06-28 19:46:54 -0700351 }
352
Tyler Trephanc7b92632021-07-21 10:39:38 -0700353 if (hasAccel && (hasGyro || hasGyroUncalibrated)) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700354 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100355 registerVirtualSensor(std::make_shared<GravitySensor>(list, count),
356 /* isDebug= */ !needGravitySensor);
Peng Xuf66684a2015-07-23 11:41:53 -0700357
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800358 bool needLinearAcceleration =
359 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100360 registerVirtualSensor(std::make_shared<LinearAccelerationSensor>(list, count),
361 /* isDebug= */ !needLinearAcceleration);
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800362
Peng Xu0cc8f802016-04-05 23:46:03 -0700363 bool needGameRotationVector =
364 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100365 registerVirtualSensor(std::make_shared<GameRotationVectorSensor>(),
366 /* isDebug= */ !needGameRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700367 }
368
369 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700370 bool needGeoMagRotationVector =
371 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100372 registerVirtualSensor(std::make_shared<GeoMagRotationVectorSensor>(),
373 /* isDebug= */ !needGeoMagRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700374 }
375
Tyler Trephanc7b92632021-07-21 10:39:38 -0700376 if (isAutomotive()) {
377 if (hasAccel) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100378 registerVirtualSensor(
379 std::make_shared<LimitedAxesImuSensor>(
380 list, count, SENSOR_TYPE_ACCELEROMETER));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700381 }
382
383 if (hasGyro) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100384 registerVirtualSensor(
385 std::make_shared<LimitedAxesImuSensor>(
386 list, count, SENSOR_TYPE_GYROSCOPE));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700387 }
388
389 if (hasAccelUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100390 registerVirtualSensor(
391 std::make_shared<LimitedAxesImuSensor>(
392 list, count, SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700393 }
394
395 if (hasGyroUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100396 registerVirtualSensor(
397 std::make_shared<LimitedAxesImuSensor>(
398 list, count, SENSOR_TYPE_GYROSCOPE_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700399 }
400 }
401
Aravind Akella5466c3d2014-08-22 16:11:10 -0700402 // Check if the device really supports batching by looking at the FIFO event
403 // counts for each sensor.
404 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700405 mSensors.forEachSensor(
406 [&batchingSupported] (const Sensor& s) -> bool {
407 if (s.getFifoMaxEventCount() > 0) {
408 batchingSupported = true;
409 }
410 return !batchingSupported;
411 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700412
413 if (batchingSupported) {
414 // Increase socket buffer size to a max of 100 KB for batching capabilities.
415 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
416 } else {
417 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
418 }
419
420 // Compare the socketBufferSize value against the system limits and limit
421 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700422 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
423 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700424 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700425 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700426 size_t maxSystemSocketBufferSize;
427 sscanf(line, "%zu", &maxSystemSocketBufferSize);
428 if (mSocketBufferSize > maxSystemSocketBufferSize) {
429 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700430 }
431 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700432 if (fp) {
433 fclose(fp);
434 }
435
Aravind Akella9a844cf2014-02-11 18:58:52 -0800436 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700437 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700438 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
439 mSensorEventBuffer = new sensors_event_t[minBufferSize];
440 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700441 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700442 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700443
Aravind Akella18d6d512015-06-18 14:18:28 -0700444 mNextSensorRegIndex = 0;
445 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
446 mLastNSensorRegistrations.push();
447 }
448
449 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700450 mAckReceiver = new SensorEventAckReceiver(this);
451 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700452 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700453
454 // priority can only be changed after run
455 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800456
457 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800458 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800459
460 // Start watching sensor privacy changes
461 mSensorPrivacyPolicy->registerSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800462
463 // Start watching mic sensor privacy changes
464 mMicSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800465 }
466 }
467}
468
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700469void SensorService::onUidStateChanged(uid_t uid, UidState state) {
470 SensorDevice& dev(SensorDevice::getInstance());
471
Brian Duddie967ce172019-06-10 11:08:27 -0700472 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700473 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700474 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700475 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700476 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700477 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700478
479 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
480 if (conn->getUid() == uid) {
481 // Update sensor subscriptions if needed
482 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
483 conn->onSensorAccessChanged(hasAccess);
484 }
485 }
Chris Kuiper587ef9b2021-10-12 16:36:43 -0700486 checkAndReportProxStateChangeLocked();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700487}
488
489bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
490 Mutex::Autolock _l(mLock);
491 return hasSensorAccessLocked(uid, opPackageName);
492}
493
494bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
495 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
496 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700497}
498
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100499bool SensorService::registerSensor(std::shared_ptr<SensorInterface> s, bool isDebug, bool isVirtual,
500 int deviceId) {
501 const int handle = s->getSensor().getHandle();
502 const int type = s->getSensor().getType();
503 if (mSensors.add(handle, std::move(s), isDebug, isVirtual, deviceId)) {
Brian Stack4baa5be2018-09-18 14:03:13 -0700504 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100505 return true;
Peng Xu0cc8f802016-04-05 23:46:03 -0700506 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100507 LOG_FATAL("Failed to register sensor with handle %d", handle);
508 return false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700509 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800510}
511
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100512bool SensorService::registerDynamicSensorLocked(std::shared_ptr<SensorInterface> s, bool isDebug) {
513 return registerSensor(std::move(s), isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800514}
515
Peng Xu6a2d3a02015-12-21 12:00:23 -0800516bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700517 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800518
519 const auto i = mRecentEvent.find(handle);
520 if (i != mRecentEvent.end()) {
521 delete i->second;
522 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800523 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700524 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800525}
526
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100527bool SensorService::registerVirtualSensor(std::shared_ptr<SensorInterface> s, bool isDebug) {
528 return registerSensor(std::move(s), isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700529}
530
Peng Xu47e96012016-03-28 17:55:56 -0700531SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800532 for (auto && entry : mRecentEvent) {
533 delete entry.second;
534 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800535 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800536 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800537 mMicSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700538}
539
540status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700541 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700542 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800543 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700544 IPCThreadState::self()->getCallingPid(),
545 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700546 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700547 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700548 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800549 return INVALID_OPERATION;
550 }
Brian Duddie967ce172019-06-10 11:08:27 -0700551 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800552 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700553 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700554 // If already in restricted mode. Ignore.
555 if (mCurrentOperatingMode == RESTRICTED) {
556 return status_t(NO_ERROR);
557 }
558 // If in any mode other than normal, ignore.
559 if (mCurrentOperatingMode != NORMAL) {
560 return INVALID_OPERATION;
561 }
Peng Xue36e3472016-11-03 11:57:10 -0700562
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700563 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800564 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700565 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700566 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700567 return status_t(NO_ERROR);
568 } else if (args.size() == 1 && args[0] == String16("enable")) {
569 // If currently in restricted mode, reset back to NORMAL mode else ignore.
570 if (mCurrentOperatingMode == RESTRICTED) {
571 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800572 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700573 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700574 }
Aravind Akella841a5922015-06-29 12:37:48 -0700575 if (mCurrentOperatingMode == DATA_INJECTION) {
576 resetToNormalModeLocked();
577 }
578 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700579 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700580 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
581 if (mCurrentOperatingMode == NORMAL) {
582 dev.disableAllSensors();
583 status_t err = dev.setMode(DATA_INJECTION);
584 if (err == NO_ERROR) {
585 mCurrentOperatingMode = DATA_INJECTION;
586 } else {
587 // Re-enable sensors.
588 dev.enableAllSensors();
589 }
590 mWhiteListedPackage.setTo(String8(args[1]));
591 return NO_ERROR;
592 } else if (mCurrentOperatingMode == DATA_INJECTION) {
593 // Already in DATA_INJECTION mode. Treat this as a no_op.
594 return NO_ERROR;
595 } else {
596 // Transition to data injection mode supported only from NORMAL mode.
597 return INVALID_OPERATION;
598 }
Mike Ma24743862020-01-29 00:36:55 -0800599 } else if (args.size() == 1 && args[0] == String16("--proto")) {
600 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700601 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700602 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700603 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700604 } else {
605 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700606 //
Brian Stack51498e62018-10-03 10:52:21 -0700607 timespec curTime;
608 clock_gettime(CLOCK_REALTIME, &curTime);
609 struct tm* timeinfo = localtime(&(curTime.tv_sec));
610 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
611 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800612 result.append("Sensor Device:\n");
613 result.append(SensorDevice::getInstance().dump().c_str());
614
615 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700616 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700617
Peng Xu6a2d3a02015-12-21 12:00:23 -0800618 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700619 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700620
Peng Xu0cc8f802016-04-05 23:46:03 -0700621 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800622 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100623 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
624 if (!i.second->isEmpty() && s != nullptr) {
Peng Xufba3c112016-09-08 12:36:59 -0700625 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
626 i.second->setFormat("normal");
627 } else {
628 i.second->setFormat("mask_data");
629 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800630 // if there is events and sensor does not need special permission.
631 result.appendFormat("%s: ", s->getSensor().getName().string());
632 result.append(i.second->dump().c_str());
633 }
634 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700635
Aravind Akella444f2672015-05-07 12:40:52 -0700636 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700637 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700638 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
639 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700640 if (dev.isSensorActive(handle)) {
641 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
642 getSensorName(handle).string(),
643 handle,
644 mActiveSensors.valueAt(i)->getNumConnections());
645 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700646 }
647
Andreas Gamped4036b62015-07-28 13:49:04 -0700648 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700649 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700650 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
651 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700652 result.appendFormat("Mode :");
653 switch(mCurrentOperatingMode) {
654 case NORMAL:
655 result.appendFormat(" NORMAL\n");
656 break;
657 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700658 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700659 break;
660 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700661 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700662 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800663 result.appendFormat("Sensor Privacy: %s\n",
664 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700665
Brian Duddie967ce172019-06-10 11:08:27 -0700666 const auto& activeConnections = connLock.getActiveConnections();
667 result.appendFormat("%zd active connections\n", activeConnections.size());
668 for (size_t i=0 ; i < activeConnections.size() ; i++) {
669 result.appendFormat("Connection Number: %zu \n", i);
670 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700671 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700672
Brian Duddie967ce172019-06-10 11:08:27 -0700673 const auto& directConnections = connLock.getDirectConnections();
674 result.appendFormat("%zd direct connections\n", directConnections.size());
675 for (size_t i = 0 ; i < directConnections.size() ; i++) {
676 result.appendFormat("Direct connection %zu:\n", i);
677 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700678 }
679
Aravind Akella18d6d512015-06-18 14:18:28 -0700680 result.appendFormat("Previous Registrations:\n");
681 // Log in the reverse chronological order.
682 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
683 SENSOR_REGISTRATIONS_BUF_SIZE;
684 const int startIndex = currentIndex;
685 do {
686 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
687 if (SensorRegistrationInfo::isSentinel(reg_info)) {
688 // Ignore sentinel, proceed to next item.
689 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
690 SENSOR_REGISTRATIONS_BUF_SIZE;
691 continue;
692 }
Peng Xu51224682017-03-10 16:57:27 -0800693 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700694 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
695 SENSOR_REGISTRATIONS_BUF_SIZE;
696 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700697 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700698 }
699 write(fd, result.string(), result.size());
700 return NO_ERROR;
701}
702
Mike Ma24743862020-01-29 00:36:55 -0800703/**
704 * Dump debugging information as android.service.SensorServiceProto protobuf message using
705 * ProtoOutputStream.
706 *
707 * See proto definition and some notes about ProtoOutputStream in
708 * frameworks/base/core/proto/android/service/sensor_service.proto
709 */
710status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
711 using namespace service::SensorServiceProto;
712 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800713 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
714 if (!mSensors.hasAnySensor()) {
715 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
716 }
Mike Ma24743862020-01-29 00:36:55 -0800717 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
718
719 timespec curTime;
720 clock_gettime(CLOCK_REALTIME, &curTime);
721 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
722
723 // Write SensorDeviceProto
724 uint64_t token = proto.start(SENSOR_DEVICE);
725 SensorDevice::getInstance().dump(&proto);
726 proto.end(token);
727
728 // Write SensorListProto
729 token = proto.start(SENSORS);
730 mSensors.dump(&proto);
731 proto.end(token);
732
733 // Write SensorFusionProto
734 token = proto.start(FUSION_STATE);
735 SensorFusion::getInstance().dump(&proto);
736 proto.end(token);
737
738 // Write SensorEventsProto
739 token = proto.start(SENSOR_EVENTS);
740 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100741 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
742 if (!i.second->isEmpty() && s != nullptr) {
Mike Ma24743862020-01-29 00:36:55 -0800743 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
744 "normal" : "mask_data");
745 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
746 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
747 std::string(s->getSensor().getName().string()));
748 i.second->dump(&proto);
749 proto.end(mToken);
750 }
751 }
752 proto.end(token);
753
754 // Write ActiveSensorProto
755 SensorDevice& dev = SensorDevice::getInstance();
756 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
757 int handle = mActiveSensors.keyAt(i);
758 if (dev.isSensorActive(handle)) {
759 token = proto.start(ACTIVE_SENSORS);
760 proto.write(service::ActiveSensorProto::NAME,
761 std::string(getSensorName(handle).string()));
762 proto.write(service::ActiveSensorProto::HANDLE, handle);
763 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
764 int(mActiveSensors.valueAt(i)->getNumConnections()));
765 proto.end(token);
766 }
767 }
768
769 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
770 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
771 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
772
773 switch(mCurrentOperatingMode) {
774 case NORMAL:
775 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
776 break;
777 case RESTRICTED:
778 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
779 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
780 break;
781 case DATA_INJECTION:
782 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
783 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
784 break;
785 default:
786 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
787 }
788 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
789
790 // Write repeated SensorEventConnectionProto
791 const auto& activeConnections = connLock->getActiveConnections();
792 for (size_t i = 0; i < activeConnections.size(); i++) {
793 token = proto.start(ACTIVE_CONNECTIONS);
794 activeConnections[i]->dump(&proto);
795 proto.end(token);
796 }
797
798 // Write repeated SensorDirectConnectionProto
799 const auto& directConnections = connLock->getDirectConnections();
800 for (size_t i = 0 ; i < directConnections.size() ; i++) {
801 token = proto.start(DIRECT_CONNECTIONS);
802 directConnections[i]->dump(&proto);
803 proto.end(token);
804 }
805
806 // Write repeated SensorRegistrationInfoProto
807 const int startIndex = mNextSensorRegIndex;
808 int curr = startIndex;
809 do {
810 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
811 if (SensorRegistrationInfo::isSentinel(reg_info)) {
812 // Ignore sentinel, proceed to next item.
813 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
814 continue;
815 }
816 token = proto.start(PREVIOUS_REGISTRATIONS);
817 reg_info.dump(&proto);
818 proto.end(token);
819 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
820 } while (startIndex != curr);
821
822 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
823}
824
Michael Groover5e1f60b2018-12-04 22:34:29 -0800825void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700826 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
827 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800828}
829
Brian Duddie967ce172019-06-10 11:08:27 -0700830void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800831 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700832 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
833 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
834 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800835 }
836 dev.disableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700837 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800838 // Clear all pending flush connections for all active sensors. If one of the active
839 // connections has called flush() and the underlying sensor has been disabled before a
840 // flush complete event is returned, we need to remove the connection from this queue.
841 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
842 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
843 }
844}
845
846void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700847 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
848 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800849}
850
Brian Duddie967ce172019-06-10 11:08:27 -0700851void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800852 // sensors should only be enabled if the operating state is not restricted and sensor
853 // privacy is not enabled.
854 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
855 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
856 mCurrentOperatingMode,
857 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
858 return;
859 }
860 SensorDevice& dev(SensorDevice::getInstance());
861 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700862 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
863 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
864 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800865 }
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700866 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800867}
868
Evan Severson4c197852022-01-27 10:44:27 -0800869void SensorService::capRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100870 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
871 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800872 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100873 }
874
875 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800876 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100877 }
878}
879
Evan Severson4c197852022-01-27 10:44:27 -0800880void SensorService::uncapRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100881 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
882 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800883 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100884 }
885
886 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800887 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100888 }
889}
Brian Duddie967ce172019-06-10 11:08:27 -0700890
Svet Ganove752a5c2018-01-15 17:14:20 -0800891// NOTE: This is a remote API - make sure all args are validated
892status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
893 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
894 return PERMISSION_DENIED;
895 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700896 if (args.size() == 0) {
897 return BAD_INDEX;
898 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800899 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
900 return BAD_VALUE;
901 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700902 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800903 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700904 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800905 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700906 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800907 return handleGetUidState(args, out, err);
Brian Duddie4a4d0462022-05-09 16:49:49 -0700908 } else if (args[0] == String16("unrestrict-ht")) {
909 mHtRestricted = false;
910 return NO_ERROR;
911 } else if (args[0] == String16("restrict-ht")) {
912 mHtRestricted = true;
913 return NO_ERROR;
Svet Ganove752a5c2018-01-15 17:14:20 -0800914 } else if (args.size() == 1 && args[0] == String16("help")) {
915 printHelp(out);
916 return NO_ERROR;
917 }
918 printHelp(err);
919 return BAD_VALUE;
920}
921
Tanmay Patild33a1822019-04-11 18:38:55 -0700922static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800923 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700924 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800925 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700926 ALOGE("Unknown package: '%s'", String8(packageName).string());
927 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800928 return BAD_VALUE;
929 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700930
931 if (userId < 0) {
932 ALOGE("Invalid user: %d", userId);
933 dprintf(err, "Invalid user: %d\n", userId);
934 return BAD_VALUE;
935 }
936
937 uid = multiuser_get_uid(userId, uid);
938 return NO_ERROR;
939}
940
941status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
942 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
943 if (!(args.size() == 3 || args.size() == 5)) {
944 printHelp(err);
945 return BAD_VALUE;
946 }
947
Svet Ganove752a5c2018-01-15 17:14:20 -0800948 bool active = false;
949 if (args[2] == String16("active")) {
950 active = true;
951 } else if ((args[2] != String16("idle"))) {
952 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
953 return BAD_VALUE;
954 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700955
956 int userId = 0;
957 if (args.size() == 5 && args[3] == String16("--user")) {
958 userId = atoi(String8(args[4]));
959 }
960
961 uid_t uid;
962 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
963 return BAD_VALUE;
964 }
965
Svet Ganove752a5c2018-01-15 17:14:20 -0800966 mUidPolicy->addOverrideUid(uid, active);
967 return NO_ERROR;
968}
969
970status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700971 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
972 if (!(args.size() == 2 || args.size() == 4)) {
973 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800974 return BAD_VALUE;
975 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700976
977 int userId = 0;
978 if (args.size() == 4 && args[2] == String16("--user")) {
979 userId = atoi(String8(args[3]));
980 }
981
982 uid_t uid;
983 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
984 return BAD_VALUE;
985 }
986
Svet Ganove752a5c2018-01-15 17:14:20 -0800987 mUidPolicy->removeOverrideUid(uid);
988 return NO_ERROR;
989}
990
991status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700992 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
993 if (!(args.size() == 2 || args.size() == 4)) {
994 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800995 return BAD_VALUE;
996 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700997
998 int userId = 0;
999 if (args.size() == 4 && args[2] == String16("--user")) {
1000 userId = atoi(String8(args[3]));
1001 }
1002
1003 uid_t uid;
1004 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1005 return BAD_VALUE;
1006 }
1007
Svet Ganove752a5c2018-01-15 17:14:20 -08001008 if (mUidPolicy->isUidActive(uid)) {
1009 return dprintf(out, "active\n");
1010 } else {
1011 return dprintf(out, "idle\n");
1012 }
1013}
1014
1015status_t SensorService::printHelp(int out) {
1016 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -07001017 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1018 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1019 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -08001020 " help print this message\n");
1021}
1022
Peng Xu0cc8f802016-04-05 23:46:03 -07001023//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -08001024void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001025 sensors_event_t const* buffer, const int count) {
1026 for (int i=0 ; i<count ; i++) {
1027 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -07001028 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1029 handle = buffer[i].meta_data.sensor;
1030 }
Aravind Akella0e025c52014-06-03 19:19:57 -07001031 if (connection->hasSensor(handle)) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001032 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -07001033 // If this buffer has an event from a one_shot sensor and this connection is registered
1034 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -07001035 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -07001036 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1037 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001038 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001039 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001040
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001041 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001042 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001043}
1044
Peng Xu47e96012016-03-28 17:55:56 -07001045bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +00001046 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -07001047
Peng Xueb4d6282015-12-10 18:02:41 -08001048 // each virtual sensor could generate an event per "real" event, that's why we need to size
1049 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
1050 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -07001051 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001052 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -07001053 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001054
Mathias Agopianf001c922010-11-11 17:58:51 -08001055 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -07001056
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001057 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -07001058 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001059 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
1060 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -07001061 if(count == DEAD_OBJECT && device.isReconnecting()) {
1062 device.reconnect();
1063 continue;
1064 } else {
1065 ALOGE("sensor poll failed (%s)", strerror(-count));
1066 break;
1067 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001068 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001069
1070 // Reset sensors_event_t.flags to zero for all events in the buffer.
1071 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001072 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001073 }
Brian Duddie967ce172019-06-10 11:08:27 -07001074 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -07001075
Aravind Akella9a844cf2014-02-11 18:58:52 -08001076 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
1077 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
1078 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
1079 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
1080 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001081 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001082 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001083 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001084 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001085 }
1086 }
1087
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001088 if (wakeEvents > 0) {
1089 if (!mWakeLockAcquired) {
1090 setWakeLockAcquiredLocked(true);
1091 }
1092 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001093 }
Aravind Akella8493b792014-09-08 15:45:47 -07001094 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -08001095
Mathias Agopianf001c922010-11-11 17:58:51 -08001096 // handle virtual sensors
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001097 bool bufferNeedsSorting = false;
Mathias Agopianf001c922010-11-11 17:58:51 -08001098 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -07001099 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -07001100 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001101 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -07001102 SensorFusion& fusion(SensorFusion::getInstance());
1103 if (fusion.isEnabled()) {
1104 for (size_t i=0 ; i<size_t(count) ; i++) {
1105 fusion.process(event[i]);
1106 }
1107 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001108 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -07001109 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001110 if (count + k >= minBufferSize) {
1111 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -07001112 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001113 count, k, minBufferSize);
1114 break;
1115 }
Mathias Agopianf001c922010-11-11 17:58:51 -08001116 sensors_event_t out;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001117 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001118 if (si == nullptr) {
1119 ALOGE("handle %d is not an valid virtual sensor", handle);
1120 continue;
1121 }
1122
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001123 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -07001124 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -08001125 k++;
1126 }
1127 }
1128 }
1129 if (k) {
1130 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -07001131 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -08001132 count += k;
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001133 bufferNeedsSorting = true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001134 }
1135 }
1136 }
1137
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001138 // handle runtime sensors
1139 {
1140 size_t k = 0;
1141 while (!mRuntimeSensorEventQueue.empty()) {
1142 if (count + k >= minBufferSize) {
1143 ALOGE("buffer too small to hold all events: count=%zd, k=%zu, size=%zu",
1144 count, k, minBufferSize);
1145 break;
1146 }
1147 mSensorEventBuffer[count + k] = mRuntimeSensorEventQueue.front();
1148 mRuntimeSensorEventQueue.pop();
1149 k++;
1150 }
1151 if (k) {
1152 // record the last synthesized values
1153 recordLastValueLocked(&mSensorEventBuffer[count], k);
1154 count += k;
1155 bufferNeedsSorting = true;
1156 }
1157 }
1158
1159 if (bufferNeedsSorting) {
1160 // sort the buffer by time-stamps
1161 sortEventBuffer(mSensorEventBuffer, count);
1162 }
1163
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001164 // handle backward compatibility for RotationVector sensor
1165 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
1166 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001167 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001168 // All the 4 components of the quaternion should be available
1169 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -07001170 mSensorEventBuffer[i].data[4] = -1;
1171 }
1172 }
1173 }
1174
Brian Duddie967ce172019-06-10 11:08:27 -07001175 // Cache the list of active connections, since we use it in multiple places below but won't
1176 // modify it here
1177 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
1178
Aravind Akella8493b792014-09-08 15:45:47 -07001179 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -07001180 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
1181 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
1182 // SensorEventConnection mapped to the corresponding flush_complete_event in
1183 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -07001184 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -07001185 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
1186 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
1187 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001188 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -07001189 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
1190 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001191 }
1192 }
Peng Xu2576cb62016-01-20 00:22:09 -08001193
1194 // handle dynamic sensor meta events, process registration and unregistration of dynamic
1195 // sensor based on content of event.
1196 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
1197 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
1198 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1199 const sensor_t& dynamicSensor =
1200 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
1201 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
1202 handle, dynamicSensor.type, dynamicSensor.name);
1203
Peng Xu0cc8f802016-04-05 23:46:03 -07001204 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -08001205 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -07001206 sensor_t s = dynamicSensor;
1207 // make sure the dynamic sensor flag is set
1208 s.flags |= DYNAMIC_SENSOR_MASK;
1209 // force the handle to be consistent
1210 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -08001211
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001212 auto si = std::make_shared<HardwareSensor>(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -08001213
Peng Xu0cc8f802016-04-05 23:46:03 -07001214 // This will release hold on dynamic sensor meta, so it should be called
1215 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -07001216 device.handleDynamicSensorConnection(handle, true /*connected*/);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001217 registerDynamicSensorLocked(std::move(si));
Peng Xu47e96012016-03-28 17:55:56 -07001218 } else {
1219 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
1220 }
Peng Xu2576cb62016-01-20 00:22:09 -08001221 } else {
1222 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1223 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1224
1225 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001226 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -08001227 ALOGE("Dynamic sensor release error.");
1228 }
1229
Brian Duddie967ce172019-06-10 11:08:27 -07001230 for (const sp<SensorEventConnection>& connection : activeConnections) {
1231 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001232 }
1233 }
1234 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001235 }
1236
Aravind Akella9a844cf2014-02-11 18:58:52 -08001237 // Send our events to clients. Check the state of wake lock for each client and release the
1238 // lock if none of the clients need it.
1239 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001240 for (const sp<SensorEventConnection>& connection : activeConnections) {
1241 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1242 mMapFlushEventsToConnections);
1243 needsWakeLock |= connection->needsWakeLock();
1244 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1245 // Early check for one-shot sensors.
1246 if (connection->hasOneShotSensors()) {
1247 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001248 }
1249 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001250
Aravind Akella9a844cf2014-02-11 18:58:52 -08001251 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001252 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001253 }
Aravind Akella8493b792014-09-08 15:45:47 -07001254 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001255
Steve Block3c20fbe2012-01-05 23:22:43 +00001256 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001257 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001258 return false;
1259}
1260
Aravind Akella56ae4262014-07-10 16:01:10 -07001261sp<Looper> SensorService::getLooper() const {
1262 return mLooper;
1263}
1264
Aravind Akellab4373ac2014-10-29 17:55:20 -07001265void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001266 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1267 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1268 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001269 }
Brian Duddie967ce172019-06-10 11:08:27 -07001270 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001271}
1272
1273void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1274 if (acquire) {
1275 if (!mWakeLockAcquired) {
1276 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1277 mWakeLockAcquired = true;
1278 }
1279 mLooper->wake();
1280 } else {
1281 if (mWakeLockAcquired) {
1282 release_wake_lock(WAKE_LOCK_NAME);
1283 mWakeLockAcquired = false;
1284 }
1285 }
1286}
1287
Aravind Akellab4373ac2014-10-29 17:55:20 -07001288bool SensorService::isWakeLockAcquired() {
1289 Mutex::Autolock _l(mLock);
1290 return mWakeLockAcquired;
1291}
1292
Aravind Akella56ae4262014-07-10 16:01:10 -07001293bool SensorService::SensorEventAckReceiver::threadLoop() {
1294 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001295 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001296 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001297 bool wakeLockAcquired = mService->isWakeLockAcquired();
1298 int timeout = -1;
1299 if (wakeLockAcquired) timeout = 5000;
1300 int ret = looper->pollOnce(timeout);
1301 if (ret == ALOOPER_POLL_TIMEOUT) {
1302 mService->resetAllWakeLockRefCounts();
1303 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001304 } while(!Thread::exitPending());
1305 return false;
1306}
1307
Aravind Akella9a844cf2014-02-11 18:58:52 -08001308void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001309 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001310 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001311 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1312 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001313 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001314 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001315 }
Peng Xu2576cb62016-01-20 00:22:09 -08001316
Peng Xu6a2d3a02015-12-21 12:00:23 -08001317 auto logger = mRecentEvent.find(buffer[i].sensor);
1318 if (logger != mRecentEvent.end()) {
1319 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001320 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001321 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001322}
1323
Peng Xu47e96012016-03-28 17:55:56 -07001324void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001325 struct compar {
1326 static int cmp(void const* lhs, void const* rhs) {
1327 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1328 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001329 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001330 }
1331 };
1332 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1333}
1334
Mathias Agopian5d270722010-07-19 15:20:39 -07001335String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001336 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001337}
1338
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001339String8 SensorService::getSensorStringType(int handle) const {
1340 return mSensors.getStringType(handle);
1341}
1342
Aravind Akellab4099e72013-10-15 15:43:10 -07001343bool SensorService::isVirtualSensor(int handle) const {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001344 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001345 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001346}
1347
Aravind Akella9a844cf2014-02-11 18:58:52 -08001348bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001349 int handle = event.sensor;
1350 if (event.type == SENSOR_TYPE_META_DATA) {
1351 handle = event.meta_data.sensor;
1352 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001353 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001354 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001355}
1356
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001357int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1358 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1359 // UUID is not supported for this device.
1360 return 0;
1361 }
1362 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1363 // This sensor can be uniquely identified in the system by
1364 // the combination of its type and name.
1365 return -1;
1366 }
1367
1368 // We have a dynamic sensor.
1369
1370 if (!sHmacGlobalKeyIsValid) {
lifr3ab0a1b2021-08-06 00:14:26 +08001371 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001372 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1373 return 0;
1374 }
1375
1376 // We want each app author/publisher to get a different ID, so that the
1377 // same dynamic sensor cannot be tracked across apps by multiple
1378 // authors/publishers. So we use both our UUID and our User ID.
1379 // Note potential confusion:
1380 // UUID => Universally Unique Identifier.
1381 // UID => User Identifier.
1382 // We refrain from using "uid" except as needed by API to try to
1383 // keep this distinction clear.
1384
1385 auto appUserId = IPCThreadState::self()->getCallingUid();
1386 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1387 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1388 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1389
1390 // Now we use our key on our UUID/app combo to get the hash.
1391 uint8_t hash[EVP_MAX_MD_SIZE];
1392 unsigned int hashLen;
1393 if (HMAC(EVP_sha256(),
1394 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1395 uuidAndApp, sizeof(uuidAndApp),
1396 hash, &hashLen) == nullptr) {
lifr3ab0a1b2021-08-06 00:14:26 +08001397 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001398 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1399 return 0;
1400 }
1401
1402 int32_t id = 0;
1403 if (hashLen < sizeof(id)) {
1404 // We never expect this case, but out of paranoia, we handle it.
1405 // Our 'id' length is already quite small, we don't want the
1406 // effective length of it to be even smaller.
1407 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1408 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1409 return 0;
1410 }
1411
1412 // This is almost certainly less than all of 'hash', but it's as secure
1413 // as we can be with our current 'id' length.
1414 memcpy(&id, hash, sizeof(id));
1415
1416 // Note at the beginning of the function that we return the values of
1417 // 0 and -1 to represent special cases. As a result, we can't return
1418 // those as dynamic sensor IDs. If we happened to hash to one of those
1419 // values, we change 'id' so we report as a dynamic sensor, and not as
1420 // one of those special cases.
1421 if (id == -1) {
1422 id = -2;
1423 } else if (id == 0) {
1424 id = 1;
1425 }
1426 return id;
1427}
1428
1429void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1430 for (auto &sensor : sensorList) {
1431 int32_t id = getIdFromUuid(sensor.getUuid());
1432 sensor.setId(id);
Eric Laurente3f27df2022-01-05 19:20:32 +01001433 // The sensor UUID must always be anonymized here for non privileged clients.
1434 // There is no other checks after this point before returning to client process.
1435 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1436 sensor.anonymizeUuid();
1437 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001438 }
1439}
1440
Anh Pham4e291332021-02-10 14:17:56 +01001441Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -07001442 char value[PROPERTY_VALUE_MAX];
1443 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001444 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001445 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001446 Vector<Sensor> accessibleSensorList;
Anh Pham4e291332021-02-10 14:17:56 +01001447
Brian Duddie0d4ac562022-05-23 17:47:50 -07001448 resetTargetSdkVersionCache(opPackageName);
Anh Pham4e291332021-02-10 14:17:56 +01001449 bool isCapped = isRateCappedBasedOnPermission(opPackageName);
Aravind Akella70018042014-04-07 22:52:37 +00001450 for (size_t i = 0; i < initialSensorList.size(); i++) {
1451 Sensor sensor = initialSensorList[i];
Anh Pham4e291332021-02-10 14:17:56 +01001452 if (isCapped && isSensorInCappedSet(sensor.getType())) {
1453 sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
1454 sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
1455 }
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001456 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001457 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001458 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001459 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001460}
1461
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001462void SensorService::addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
1463 Vector<Sensor>& accessibleSensorList) {
1464 if (canAccessSensor(sensor, "can't see", opPackageName)) {
1465 accessibleSensorList.add(sensor);
1466 } else if (sensor.getType() != SENSOR_TYPE_HEAD_TRACKER) {
1467 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1468 sensor.getName().string(), sensor.getRequiredPermission().string(),
1469 sensor.getRequiredAppOp());
1470 }
1471}
1472
Peng Xu47e96012016-03-28 17:55:56 -07001473Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001474 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001475 mSensors.forEachSensor(
Brian Duddie4a4d0462022-05-09 16:49:49 -07001476 [this, &opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001477 if (sensor.isDynamicSensor()) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001478 addSensorIfAccessible(opPackageName, sensor, accessibleSensorList);
1479 }
1480 return true;
1481 });
1482 makeUuidsIntoIdsForSensorList(accessibleSensorList);
1483 return accessibleSensorList;
1484}
1485
1486Vector<Sensor> SensorService::getRuntimeSensorList(const String16& opPackageName, int deviceId) {
1487 Vector<Sensor> accessibleSensorList;
1488 mSensors.forEachEntry(
1489 [this, &opPackageName, deviceId, &accessibleSensorList] (
1490 const SensorServiceUtil::SensorList::Entry& e) -> bool {
1491 if (e.deviceId == deviceId) {
1492 addSensorIfAccessible(opPackageName, e.si->getSensor(), accessibleSensorList);
Peng Xu0cc8f802016-04-05 23:46:03 -07001493 }
1494 return true;
1495 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001496 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001497 return accessibleSensorList;
1498}
1499
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001500sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001501 int requestedMode, const String16& opPackageName, const String16& attributionTag) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001502 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1503 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001504 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001505 }
Brian Duddie0d4ac562022-05-23 17:47:50 -07001506 resetTargetSdkVersionCache(opPackageName);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001507
1508 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001509 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1510 // operating in DI mode.
1511 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001512 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1513 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001514 }
1515
Mathias Agopian5307d172012-09-18 17:02:43 -07001516 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001517 pid_t pid = IPCThreadState::self()->getCallingPid();
1518
1519 String8 connPackageName =
1520 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1521 String16 connOpPackageName =
1522 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1523 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001524 requestedMode == DATA_INJECTION, connOpPackageName, attributionTag));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001525 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001526 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001527 // Add the associated file descriptor to the Looper for polling whenever there is data to
1528 // be injected.
1529 result->updateLooperRegistration(mLooper);
1530 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001531 return result;
1532}
1533
Aravind Akella841a5922015-06-29 12:37:48 -07001534int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001535 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001536 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001537}
1538
Peng Xue36e3472016-11-03 11:57:10 -07001539sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1540 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1541 const native_handle *resource) {
Brian Duddie0d4ac562022-05-23 17:47:50 -07001542 resetTargetSdkVersionCache(opPackageName);
Brian Duddie967ce172019-06-10 11:08:27 -07001543 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001544
Michael Groover5e1f60b2018-12-04 22:34:29 -08001545 // No new direct connections are allowed when sensor privacy is enabled
1546 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1547 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1548 return nullptr;
1549 }
1550
Peng Xue36e3472016-11-03 11:57:10 -07001551 struct sensors_direct_mem_t mem = {
1552 .type = type,
1553 .format = format,
1554 .size = size,
1555 .handle = resource,
1556 };
1557 uid_t uid = IPCThreadState::self()->getCallingUid();
1558
1559 if (mem.handle == nullptr) {
1560 ALOGE("Failed to clone resource handle");
1561 return nullptr;
1562 }
1563
1564 // check format
1565 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1566 ALOGE("Direct channel format %d is unsupported!", format);
1567 return nullptr;
1568 }
1569
1570 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001571 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1572 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001573 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001574 return nullptr;
1575 }
1576 }
1577
1578 // check specific to memory type
1579 switch(type) {
1580 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001581 if (resource->numFds < 1) {
1582 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1583 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1584 return nullptr;
1585 }
Peng Xue36e3472016-11-03 11:57:10 -07001586 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001587 if (!ashmem_valid(fd)) {
1588 ALOGE("Supplied Ashmem memory region is invalid");
1589 return nullptr;
1590 }
1591
Peng Xue36e3472016-11-03 11:57:10 -07001592 int size2 = ashmem_get_size_region(fd);
1593 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001594 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001595 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1596 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001597 return nullptr;
1598 }
1599 break;
1600 }
1601 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001602 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001603 break;
1604 default:
1605 ALOGE("Unknown direct connection memory type %d", type);
1606 return nullptr;
1607 }
1608
1609 native_handle_t *clone = native_handle_clone(resource);
1610 if (!clone) {
1611 return nullptr;
1612 }
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001613 native_handle_set_fdsan_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001614
Brian Duddie967ce172019-06-10 11:08:27 -07001615 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001616 SensorDevice& dev(SensorDevice::getInstance());
1617 int channelHandle = dev.registerDirectChannel(&mem);
1618
1619 if (channelHandle <= 0) {
1620 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1621 } else {
1622 mem.handle = clone;
1623 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1624 }
1625
1626 if (conn == nullptr) {
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001627 native_handle_close_with_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001628 native_handle_delete(clone);
1629 } else {
1630 // add to list of direct connections
1631 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001632 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001633 }
1634 return conn;
1635}
1636
Peng Xudd5c5cb2017-03-16 17:39:43 -07001637int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001638 int32_t handle, int32_t type,
1639 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001640 Mutex::Autolock _l(mLock);
1641
Alexey Polyudov88711e82017-05-23 19:54:04 -07001642 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001643 return PERMISSION_DENIED;
1644 }
1645
1646 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001647 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001648 size_t expectSize = INT32_MAX;
1649 switch (type) {
1650 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1651 isFloat = true;
1652 expectSize = 3;
1653 break;
1654 case AINFO_LOCAL_GRAVITY:
1655 isFloat = true;
1656 expectSize = 1;
1657 break;
1658 case AINFO_DOCK_STATE:
1659 case AINFO_HIGH_PERFORMANCE_MODE:
1660 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1661 isFloat = false;
1662 expectSize = 1;
1663 break;
1664 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001665 // CUSTOM events must only contain float data; it may have variable size
1666 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1667 ints.size() ||
1668 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1669 handle < 0) {
1670 return BAD_VALUE;
1671 }
1672 isFloat = true;
1673 isCustom = true;
1674 expectSize = floats.size();
1675 break;
1676 }
1677
1678 if (!isCustom && handle != -1) {
1679 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001680 }
1681
1682 // three events: first one is begin tag, last one is end tag, the one in the middle
1683 // is the payload.
1684 sensors_event_t event[3];
1685 int64_t timestamp = elapsedRealtimeNano();
1686 for (sensors_event_t* i = event; i < event + 3; i++) {
1687 *i = (sensors_event_t) {
1688 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001689 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001690 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1691 .timestamp = timestamp++,
1692 .additional_info = (additional_info_event_t) {
1693 .serial = 0
1694 }
1695 };
1696 }
1697
1698 event[0].additional_info.type = AINFO_BEGIN;
1699 event[1].additional_info.type = type;
1700 event[2].additional_info.type = AINFO_END;
1701
1702 if (isFloat) {
1703 if (floats.size() != expectSize) {
1704 return BAD_VALUE;
1705 }
1706 for (size_t i = 0; i < expectSize; ++i) {
1707 event[1].additional_info.data_float[i] = floats[i];
1708 }
1709 } else {
1710 if (ints.size() != expectSize) {
1711 return BAD_VALUE;
1712 }
1713 for (size_t i = 0; i < expectSize; ++i) {
1714 event[1].additional_info.data_int32[i] = ints[i];
1715 }
1716 }
1717
1718 SensorDevice& dev(SensorDevice::getInstance());
1719 for (sensors_event_t* i = event; i < event + 3; i++) {
1720 int ret = dev.injectSensorData(i);
1721 if (ret != NO_ERROR) {
1722 return ret;
1723 }
1724 }
1725 return NO_ERROR;
1726}
1727
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001728status_t SensorService::resetToNormalMode() {
1729 Mutex::Autolock _l(mLock);
1730 return resetToNormalModeLocked();
1731}
1732
1733status_t SensorService::resetToNormalModeLocked() {
1734 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001735 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301736 if (err == NO_ERROR) {
1737 mCurrentOperatingMode = NORMAL;
1738 dev.enableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001739 checkAndReportProxStateChangeLocked();
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301740 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001741 return err;
1742}
1743
Peng Xu47e96012016-03-28 17:55:56 -07001744void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001745 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001746 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001747 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001748 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001749 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001750 int handle = mActiveSensors.keyAt(i);
1751 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001752 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001753 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001754 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001755 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001756 } else {
1757 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001758 }
Brian Duddie7be85572021-12-21 10:44:55 -08001759 if (c->removeSensor(handle)) {
1760 BatteryService::disableSensor(c->getUid(), handle);
1761 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001762 }
1763 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001764 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001765 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001766 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001767 c, i, handle);
1768
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001769 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001770 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001771 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001772 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001773 delete rec;
1774 size--;
1775 } else {
1776 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001777 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001778 }
Aravind Akella8a969552014-09-28 17:52:41 -07001779 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001780 mConnectionHolder.removeEventConnection(connection);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001781 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001782 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001783 }
Peng Xu4f707f82016-09-26 11:28:32 -07001784
1785 SensorDevice& dev(SensorDevice::getInstance());
1786 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001787}
1788
Peng Xue36e3472016-11-03 11:57:10 -07001789void SensorService::cleanupConnection(SensorDirectConnection* c) {
1790 Mutex::Autolock _l(mLock);
1791
1792 SensorDevice& dev(SensorDevice::getInstance());
1793 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001794 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001795}
1796
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001797void SensorService::checkAndReportProxStateChangeLocked() {
1798 if (mProxSensorHandles.empty()) return;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001799
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001800 SensorDevice& dev(SensorDevice::getInstance());
1801 bool isActive = false;
1802 for (auto& sensor : mProxSensorHandles) {
1803 if (dev.isSensorActive(sensor)) {
1804 isActive = true;
1805 break;
1806 }
1807 }
1808 if (isActive != mLastReportedProxIsActive) {
1809 notifyProximityStateLocked(isActive, mProximityActiveListeners);
1810 mLastReportedProxIsActive = isActive;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001811 }
1812}
1813
1814void SensorService::notifyProximityStateLocked(
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001815 const bool isActive,
Santos Cordon7ea287a2021-06-14 13:45:29 +01001816 const std::vector<sp<ProximityActiveListener>>& listeners) {
Santos Cordon7ea287a2021-06-14 13:45:29 +01001817 const uint64_t mySeq = ++curProxCallbackSeq;
1818 std::thread t([isActive, mySeq, listenersCopy = listeners]() {
1819 while (completedCallbackSeq.load() != mySeq - 1)
1820 std::this_thread::sleep_for(1ms);
1821 for (auto& listener : listenersCopy)
1822 listener->onProximityActive(isActive);
1823 completedCallbackSeq++;
1824 });
1825 t.detach();
Andrew Lehmer3a602572021-03-25 15:19:56 -07001826}
1827
1828status_t SensorService::addProximityActiveListener(const sp<ProximityActiveListener>& callback) {
1829 if (callback == nullptr) {
1830 return BAD_VALUE;
1831 }
1832
1833 Mutex::Autolock _l(mLock);
1834
1835 // Check if the callback was already added.
1836 for (const auto& cb : mProximityActiveListeners) {
1837 if (cb == callback) {
1838 return ALREADY_EXISTS;
1839 }
1840 }
1841
1842 mProximityActiveListeners.push_back(callback);
1843 std::vector<sp<ProximityActiveListener>> listener(1, callback);
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001844 notifyProximityStateLocked(mLastReportedProxIsActive, listener);
Andrew Lehmer3a602572021-03-25 15:19:56 -07001845 return OK;
1846}
1847
1848status_t SensorService::removeProximityActiveListener(
1849 const sp<ProximityActiveListener>& callback) {
1850 if (callback == nullptr) {
1851 return BAD_VALUE;
1852 }
1853
1854 Mutex::Autolock _l(mLock);
1855
1856 for (auto iter = mProximityActiveListeners.begin();
1857 iter != mProximityActiveListeners.end();
1858 ++iter) {
1859 if (*iter == callback) {
1860 mProximityActiveListeners.erase(iter);
1861 return OK;
1862 }
1863 }
1864 return NAME_NOT_FOUND;
1865}
1866
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001867std::shared_ptr<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001868 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001869}
1870
Mathias Agopianfc328812010-07-14 23:41:37 -07001871status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001872 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001873 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001874 if (mInitCheck != NO_ERROR)
1875 return mInitCheck;
1876
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001877 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001878 if (sensor == nullptr ||
1879 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001880 return BAD_VALUE;
1881 }
1882
Brian Duddie967ce172019-06-10 11:08:27 -07001883 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001884 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001885 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001886 return INVALID_OPERATION;
1887 }
1888
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001889 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001890 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001891 rec = new SensorRecord(connection);
1892 mActiveSensors.add(handle, rec);
1893 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001894 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001895 }
Brian Stack26029ee2019-04-22 17:25:49 -07001896
1897 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1898 // the recent event as stale to ensure that the previous event is not sent to a client. This
1899 // ensures on-change events that were generated during a previous sensor activation are not
1900 // erroneously sent to newly connected clients, especially if a second client registers for
1901 // an on-change sensor before the first client receives the updated event. Once an updated
1902 // event is received, the recent events will be marked as current, and any new clients will
1903 // immediately receive the most recent event.
1904 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1905 auto logger = mRecentEvent.find(handle);
1906 if (logger != mRecentEvent.end()) {
1907 logger->second->setLastEventStale();
1908 }
1909 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001910 } else {
1911 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001912 // this sensor is already activated, but we are adding a connection that uses it.
1913 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001914 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001915 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001916 // NOTE: The wake_up flag of this event may get set to
1917 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001918
1919 auto logger = mRecentEvent.find(handle);
1920 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001921 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001922 // Verify that the last sensor event was generated from the current activation
1923 // of the sensor. If not, it is possible for an on-change sensor to receive a
1924 // sensor event that is stale if two clients re-activate the sensor
1925 // simultaneously.
1926 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001927 event.sensor = handle;
1928 if (event.version == sizeof(sensors_event_t)) {
1929 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1930 setWakeLockAcquiredLocked(true);
1931 }
Yi Kong8f313e32018-07-17 14:13:29 -07001932 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001933 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001934 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001935 }
1936 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001937 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001938 }
1939 }
1940 }
1941 }
1942
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001943 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001944 BatteryService::enableSensor(connection->getUid(), handle);
1945 // the sensor was added (which means it wasn't already there)
1946 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001947 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001948 } else {
1949 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1950 handle, connection.get());
1951 }
1952
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301953 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001954 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301955 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1956 samplingPeriodNs = maxDelayNs;
1957 }
1958
Aravind Akella724d91d2013-06-27 12:04:23 -07001959 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1960 if (samplingPeriodNs < minDelayNs) {
1961 samplingPeriodNs = minDelayNs;
1962 }
1963
Aravind Akella6c2664a2014-08-13 12:24:50 -07001964 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1965 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001966 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1967
Aravind Akella4949c502015-02-11 15:54:35 -08001968 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001969 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001970
Peng Xu20483c42015-10-26 15:14:43 -07001971 // Call flush() before calling activate() on the sensor. Wait for a first
1972 // flush complete event before sending events on this connection. Ignore
1973 // one-shot sensors which don't support flush(). Ignore on-change sensors
1974 // to maintain the on-change logic (any on-change events except the initial
1975 // one should be trigger by a change in value). Also if this sensor isn't
1976 // already active, don't call flush().
1977 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001978 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001979 rec->getNumConnections() > 1) {
1980 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001981 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001982 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001983 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001984 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001985 } else {
1986 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001987 }
1988 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001989
1990 if (err == NO_ERROR) {
1991 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1992 err = sensor->activate(connection.get(), true);
1993 }
1994
Aravind Akella8a969552014-09-28 17:52:41 -07001995 if (err == NO_ERROR) {
1996 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001997
Brian Stack240d1d62019-05-17 09:49:39 -07001998 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1999 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07002000 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
2001 }
2002
Peng Xu51224682017-03-10 16:57:27 -08002003 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2004 SensorRegistrationInfo(handle, connection->getPackageName(),
2005 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07002006 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07002007 }
2008
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002009 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07002010 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002011 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002012 }
2013 return err;
2014}
2015
Peng Xu47e96012016-03-28 17:55:56 -07002016status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002017 if (mInitCheck != NO_ERROR)
2018 return mInitCheck;
2019
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002020 Mutex::Autolock _l(mLock);
2021 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002022 if (err == NO_ERROR) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002023 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002024 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07002025
2026 }
2027 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08002028 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2029 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07002030 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002031 }
2032 return err;
2033}
2034
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002035status_t SensorService::cleanupWithoutDisable(
2036 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002037 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002038 return cleanupWithoutDisableLocked(connection, handle);
2039}
2040
2041status_t SensorService::cleanupWithoutDisableLocked(
2042 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002043 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002044 if (rec) {
2045 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07002046 if (connection->removeSensor(handle)) {
2047 BatteryService::disableSensor(connection->getUid(), handle);
2048 }
Mathias Agopianfc328812010-07-14 23:41:37 -07002049 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07002050 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07002051 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07002052 }
2053 // see if this sensor becomes inactive
2054 if (rec->removeConnection(connection)) {
2055 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002056 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002057 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07002058 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002059 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002060 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002061 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07002062}
2063
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002064status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07002065 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002066 if (mInitCheck != NO_ERROR)
2067 return mInitCheck;
2068
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002069 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002070 if (sensor == nullptr ||
2071 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00002072 return BAD_VALUE;
2073 }
2074
Mathias Agopian1cd70002010-07-21 15:59:50 -07002075 if (ns < 0)
2076 return BAD_VALUE;
2077
Mathias Agopian62569ec2011-11-07 21:21:47 -08002078 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2079 if (ns < minDelayNs) {
2080 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07002081 }
2082
Mathias Agopianf001c922010-11-11 17:58:51 -08002083 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07002084}
2085
Svetoslavb412f6e2015-04-29 16:50:41 -07002086status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
2087 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00002088 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002089 SensorDevice& dev(SensorDevice::getInstance());
2090 const int halVersion = dev.getHalDeviceVersion();
2091 status_t err(NO_ERROR);
2092 Mutex::Autolock _l(mLock);
2093 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07002094 for (int handle : connection->getActiveSensorHandles()) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002095 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002096 if (sensor == nullptr) {
2097 continue;
2098 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002099 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
2100 ALOGE("flush called on a one-shot sensor");
2101 err = INVALID_OPERATION;
2102 continue;
2103 }
Aravind Akella8493b792014-09-08 15:45:47 -07002104 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002105 // For older devices just increment pending flush count which will send a trivial
2106 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07002107 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
2108 ALOGE("flush called on an inaccessible sensor");
2109 err = INVALID_OPERATION;
2110 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002111 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002112 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
2113 err = INVALID_OPERATION;
2114 continue;
2115 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002116 status_t err_flush = sensor->flush(connection.get(), handle);
2117 if (err_flush == NO_ERROR) {
2118 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07002119 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002120 }
2121 err = (err_flush != NO_ERROR) ? err_flush : err;
2122 }
Aravind Akella70018042014-04-07 22:52:37 +00002123 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07002124 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07002125}
Aravind Akella70018042014-04-07 22:52:37 +00002126
Svetoslavb412f6e2015-04-29 16:50:41 -07002127bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
2128 const String16& opPackageName) {
Brian Duddie4a4d0462022-05-09 16:49:49 -07002129 // Special case for Head Tracker sensor type: currently restricted to system usage only, unless
2130 // the restriction is specially lifted for testing
2131 if (sensor.getType() == SENSOR_TYPE_HEAD_TRACKER &&
2132 !isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
2133 if (!mHtRestricted) {
2134 ALOGI("Permitting access to HT sensor type outside system (%s)",
2135 String8(opPackageName).string());
2136 } else {
2137 ALOGW("%s %s a sensor (%s) as a non-system client", String8(opPackageName).string(),
2138 operation, sensor.getName().string());
2139 return false;
2140 }
2141 }
2142
Brian Stack793f4642019-04-18 17:21:34 -07002143 // Check if a permission is required for this sensor
2144 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00002145 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07002146 }
2147
Brian Stack793f4642019-04-18 17:21:34 -07002148 const int32_t opCode = sensor.getRequiredAppOp();
Brian Duddie457e6392020-06-19 11:38:29 -07002149 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07002150
Brian Stack793f4642019-04-18 17:21:34 -07002151 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07002152 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
2153 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
2154 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
2155 // Allow access to step sensors if the application targets pre-Q, which is before the
2156 // requirement to hold the AR permission to access Step Counter and Step Detector events
2157 // was introduced.
2158 canAccess = true;
2159 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07002160 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002161 if (opCode >= 0) {
2162 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
2163 IPCThreadState::self()->getCallingUid(), opPackageName);
2164 canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
2165 } else {
Brian Stack793f4642019-04-18 17:21:34 -07002166 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07002167 }
Brian Stack793f4642019-04-18 17:21:34 -07002168 }
2169
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002170 if (!canAccess) {
Brian Duddie457e6392020-06-19 11:38:29 -07002171 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
2172 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07002173 }
2174
2175 return canAccess;
2176}
2177
2178bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07002179 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07002180 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07002181
2182 // Runtime permissions can't use the cache as they may change.
2183 if (sensor.isRequiredPermissionRuntime()) {
2184 hasPermission = checkPermission(String16(requiredPermission),
matthuang65794462022-03-24 16:02:57 +08002185 IPCThreadState::self()->getCallingPid(),
2186 IPCThreadState::self()->getCallingUid(),
2187 /*logPermissionFailure=*/ false);
Aravind Akella70018042014-04-07 22:52:37 +00002188 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002189 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
2190 }
Brian Stack793f4642019-04-18 17:21:34 -07002191 return hasPermission;
2192}
Svetoslavb412f6e2015-04-29 16:50:41 -07002193
Brian Stack793f4642019-04-18 17:21:34 -07002194int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Anthony Stange07eb4212020-08-28 14:50:28 -04002195 // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
2196 // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
2197 // give it elevated privileges.
2198 if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
2199 return -1;
2200 }
2201
Brian Stack793f4642019-04-18 17:21:34 -07002202 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2203 int targetSdkVersion = -1;
2204 auto entry = sPackageTargetVersion.find(opPackageName);
2205 if (entry != sPackageTargetVersion.end()) {
2206 targetSdkVersion = entry->second;
2207 } else {
2208 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2209 if (binder != nullptr) {
2210 sp<content::pm::IPackageManagerNative> packageManager =
2211 interface_cast<content::pm::IPackageManagerNative>(binder);
2212 if (packageManager != nullptr) {
2213 binder::Status status = packageManager->getTargetSdkVersionForPackage(
2214 opPackageName, &targetSdkVersion);
2215 if (!status.isOk()) {
2216 targetSdkVersion = -1;
2217 }
2218 }
Svetoslavb412f6e2015-04-29 16:50:41 -07002219 }
Brian Stack793f4642019-04-18 17:21:34 -07002220 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07002221 }
Brian Stack793f4642019-04-18 17:21:34 -07002222 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00002223}
2224
Brian Duddie0d4ac562022-05-23 17:47:50 -07002225void SensorService::resetTargetSdkVersionCache(const String16& opPackageName) {
2226 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2227 auto iter = sPackageTargetVersion.find(opPackageName);
2228 if (iter != sPackageTargetVersion.end()) {
2229 sPackageTargetVersion.erase(iter);
2230 }
2231}
2232
Aravind Akella9a844cf2014-02-11 18:58:52 -08002233void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07002234 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2235 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08002236}
2237
Brian Duddie967ce172019-06-10 11:08:27 -07002238void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002239 if (!mWakeLockAcquired) {
2240 return;
2241 }
2242 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07002243 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
2244 if (connection->needsWakeLock()) {
2245 releaseLock = false;
2246 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08002247 }
2248 }
2249 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07002250 setWakeLockAcquiredLocked(false);
2251 }
2252}
2253
2254void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
2255 Mutex::Autolock _l(mLock);
2256 connection->writeToSocketFromCache();
2257 if (connection->needsWakeLock()) {
2258 setWakeLockAcquiredLocked(true);
2259 }
2260}
2261
Aravind Akella4949c502015-02-11 15:54:35 -08002262bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07002263 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08002264}
2265
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002266bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08002267 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07002268 String8 package(opPackageName);
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002269 return !isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07002270 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002271 return false;
Peng Xue36e3472016-11-03 11:57:10 -07002272}
2273
Svet Ganove752a5c2018-01-15 17:14:20 -08002274void SensorService::UidPolicy::registerSelf() {
2275 ActivityManager am;
2276 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
2277 | ActivityManager::UID_OBSERVER_IDLE
2278 | ActivityManager::UID_OBSERVER_ACTIVE,
2279 ActivityManager::PROCESS_STATE_UNKNOWN,
2280 String16("android"));
2281}
2282
2283void SensorService::UidPolicy::unregisterSelf() {
2284 ActivityManager am;
2285 am.unregisterUidObserver(this);
2286}
2287
2288void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
2289 onUidIdle(uid, disabled);
2290}
2291
2292void SensorService::UidPolicy::onUidActive(uid_t uid) {
2293 {
2294 Mutex::Autolock _l(mUidLock);
2295 mActiveUids.insert(uid);
2296 }
2297 sp<SensorService> service = mService.promote();
2298 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002299 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002300 }
2301}
2302
2303void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
2304 bool deleted = false;
2305 {
2306 Mutex::Autolock _l(mUidLock);
2307 if (mActiveUids.erase(uid) > 0) {
2308 deleted = true;
2309 }
2310 }
2311 if (deleted) {
2312 sp<SensorService> service = mService.promote();
2313 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002314 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002315 }
2316 }
2317}
2318
2319void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
2320 updateOverrideUid(uid, active, true);
2321}
2322
2323void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
2324 updateOverrideUid(uid, false, false);
2325}
2326
2327void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
2328 bool wasActive = false;
2329 bool isActive = false;
2330 {
2331 Mutex::Autolock _l(mUidLock);
2332 wasActive = isUidActiveLocked(uid);
2333 mOverrideUids.erase(uid);
2334 if (insert) {
2335 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2336 }
2337 isActive = isUidActiveLocked(uid);
2338 }
2339 if (wasActive != isActive) {
2340 sp<SensorService> service = mService.promote();
2341 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002342 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002343 }
2344 }
2345}
2346
2347bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2348 // Non-app UIDs are considered always active
2349 if (uid < FIRST_APPLICATION_UID) {
2350 return true;
2351 }
2352 Mutex::Autolock _l(mUidLock);
2353 return isUidActiveLocked(uid);
2354}
2355
2356bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2357 // Non-app UIDs are considered always active
2358 if (uid < FIRST_APPLICATION_UID) {
2359 return true;
2360 }
2361 auto it = mOverrideUids.find(uid);
2362 if (it != mOverrideUids.end()) {
2363 return it->second;
2364 }
2365 return mActiveUids.find(uid) != mActiveUids.end();
2366}
2367
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002368bool SensorService::isUidActive(uid_t uid) {
2369 return mUidPolicy->isUidActive(uid);
2370}
2371
Anh Phamaf91a912021-02-10 14:10:53 +01002372bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2373 int targetSdk = getTargetSdkVersion(opPackageName);
Anh Phama5538232021-06-23 08:41:11 +02002374 bool hasSamplingRatePermission = checkPermission(sAccessHighSensorSamplingRatePermission,
2375 IPCThreadState::self()->getCallingPid(),
matthuang65794462022-03-24 16:02:57 +08002376 IPCThreadState::self()->getCallingUid(),
2377 /*logPermissionFailure=*/ false);
Anh Phamaf91a912021-02-10 14:10:53 +01002378 if (targetSdk < __ANDROID_API_S__ ||
2379 (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2380 return false;
2381 }
2382 return true;
2383}
2384
Anh Pham3dae77f2021-06-11 16:24:37 +02002385/**
2386 * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS
2387 * permission.
2388 *
2389 * This needs to be kept in sync with the list defined on the Java side
2390 * in frameworks/base/core/java/android/hardware/SystemSensorManager.java
2391 */
Anh Phamaf91a912021-02-10 14:10:53 +01002392bool SensorService::isSensorInCappedSet(int sensorType) {
2393 return (sensorType == SENSOR_TYPE_ACCELEROMETER
2394 || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2395 || sensorType == SENSOR_TYPE_GYROSCOPE
2396 || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2397 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2398 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2399}
2400
2401status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2402 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002403 if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2404 return OK;
2405 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002406 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002407 if (shouldCapBasedOnPermission) {
2408 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2409 if (isPackageDebuggable(opPackageName)) {
2410 return PERMISSION_DENIED;
2411 }
2412 return OK;
2413 }
Evan Severson4c197852022-01-27 10:44:27 -08002414 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002415 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2416 return OK;
2417 }
Anh Phamaf91a912021-02-10 14:10:53 +01002418 return OK;
2419}
2420
2421status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2422 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002423 if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2424 return OK;
2425 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002426 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002427 if (shouldCapBasedOnPermission) {
2428 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2429 if (isPackageDebuggable(opPackageName)) {
2430 return PERMISSION_DENIED;
2431 }
2432 return OK;
2433 }
Evan Severson4c197852022-01-27 10:44:27 -08002434 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002435 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2436 return OK;
2437 }
Anh Phamaf91a912021-02-10 14:10:53 +01002438 return OK;
2439}
2440
Michael Groover5e1f60b2018-12-04 22:34:29 -08002441void SensorService::SensorPrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002442 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002443 SensorPrivacyManager spm;
2444 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2445 spm.addSensorPrivacyListener(this);
2446}
2447
2448void SensorService::SensorPrivacyPolicy::unregisterSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002449 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002450 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002451 spm.removeSensorPrivacyListener(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -08002452}
2453
2454bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2455 return mSensorPrivacyEnabled;
2456}
2457
Evan Severson4c197852022-01-27 10:44:27 -08002458binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2459 int sensor __unused, bool enabled) {
Michael Groover5e1f60b2018-12-04 22:34:29 -08002460 mSensorPrivacyEnabled = enabled;
2461 sp<SensorService> service = mService.promote();
Anh Pham5198c992021-02-10 14:15:30 +01002462
Michael Groover5e1f60b2018-12-04 22:34:29 -08002463 if (service != nullptr) {
Evan Severson4c197852022-01-27 10:44:27 -08002464 if (enabled) {
2465 service->disableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002466 } else {
Evan Severson4c197852022-01-27 10:44:27 -08002467 service->enableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002468 }
2469 }
2470 return binder::Status::ok();
2471}
Brian Duddie967ce172019-06-10 11:08:27 -07002472
Evan Severson4c197852022-01-27 10:44:27 -08002473void SensorService::MicrophonePrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002474 AutoCallerClear acc;
Anh Pham5198c992021-02-10 14:15:30 +01002475 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002476 mSensorPrivacyEnabled =
2477 spm.isToggleSensorPrivacyEnabled(
2478 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
2479 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE)
2480 || spm.isToggleSensorPrivacyEnabled(
2481 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE,
2482 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE);
2483 spm.addToggleSensorPrivacyListener(this);
Anh Pham5198c992021-02-10 14:15:30 +01002484}
2485
Evan Severson4c197852022-01-27 10:44:27 -08002486void SensorService::MicrophonePrivacyPolicy::unregisterSelf() {
2487 AutoCallerClear acc;
2488 SensorPrivacyManager spm;
2489 spm.removeToggleSensorPrivacyListener(this);
2490}
2491
2492binder::Status SensorService::MicrophonePrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2493 int sensor, bool enabled) {
2494 if (sensor != SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE) {
2495 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002496 }
Evan Severson4c197852022-01-27 10:44:27 -08002497 mSensorPrivacyEnabled = enabled;
2498 sp<SensorService> service = mService.promote();
2499
2500 if (service != nullptr) {
2501 if (enabled) {
2502 service->capRates();
2503 } else {
2504 service->uncapRates();
2505 }
2506 }
2507 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002508}
2509
Brian Duddie967ce172019-06-10 11:08:27 -07002510SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2511 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2512 : mConnectionHolder(holder), mAutolock(mutex) {}
2513
2514template<typename ConnectionType>
2515const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2516 const SortedVector<wp<ConnectionType>>& connectionList,
2517 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2518 referenceHolder->emplace_back();
2519 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2520 for (const wp<ConnectionType>& weakConnection : connectionList){
2521 sp<ConnectionType> connection = weakConnection.promote();
2522 if (connection != nullptr) {
2523 connections.push_back(std::move(connection));
2524 }
2525 }
2526 return connections;
2527}
2528
2529const std::vector<sp<SensorService::SensorEventConnection>>&
2530 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2531 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2532 &mReferencedActiveConnections);
2533}
2534
2535const std::vector<sp<SensorService::SensorDirectConnection>>&
2536 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2537 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2538 &mReferencedDirectConnections);
2539}
2540
2541void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2542 const sp<SensorService::SensorEventConnection>& connection) {
2543 if (mActiveConnections.indexOf(connection) < 0) {
2544 mActiveConnections.add(connection);
2545 }
2546}
2547
2548void SensorService::SensorConnectionHolder::removeEventConnection(
2549 const wp<SensorService::SensorEventConnection>& connection) {
2550 mActiveConnections.remove(connection);
2551}
2552
2553void SensorService::SensorConnectionHolder::addDirectConnection(
2554 const sp<SensorService::SensorDirectConnection>& connection) {
2555 mDirectConnections.add(connection);
2556}
2557
2558void SensorService::SensorConnectionHolder::removeDirectConnection(
2559 const wp<SensorService::SensorDirectConnection>& connection) {
2560 mDirectConnections.remove(connection);
2561}
2562
2563SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2564 return ConnectionSafeAutolock(*this, mutex);
2565}
2566
Anh Phamaf91a912021-02-10 14:10:53 +01002567bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2568 bool debugMode = false;
2569 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2570 if (binder != nullptr) {
2571 sp<content::pm::IPackageManagerNative> packageManager =
2572 interface_cast<content::pm::IPackageManagerNative>(binder);
2573 if (packageManager != nullptr) {
2574 binder::Status status = packageManager->isPackageDebuggable(
2575 opPackageName, &debugMode);
2576 }
2577 }
2578 return debugMode;
2579}
Brian Duddie967ce172019-06-10 11:08:27 -07002580} // namespace android