blob: 6504b79527ce646ce90d98449e45622ce8666655 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Vladimir Komsiyski29d2afd2022-12-06 13:24:10 +010016#include <aidl/android/hardware/sensors/ISensors.h>
Anh Phamaf91a912021-02-10 14:10:53 +010017#include <android-base/strings.h>
Brian Stack793f4642019-04-18 17:21:34 -070018#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080019#include <android/util/ProtoOutputStream.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080020#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070021#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070022#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070023#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080024#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070025#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080026#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070027#include <cutils/properties.h>
Brian Duddie0a4cebb2022-08-25 19:20:18 +000028#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070029#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070030#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080031#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070032#include <openssl/digest.h>
33#include <openssl/hmac.h>
34#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070035#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080036#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070037#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070038
Mathias Agopian787ac1b2012-09-18 18:49:18 -070039#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070040#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080041#include "GravitySensor.h"
Tyler Trephanc7b92632021-07-21 10:39:38 -070042#include "LimitedAxesImuSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080043#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070044#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080045#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070047#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048
Mathias Agopian984826c2011-05-17 22:54:42 -070049#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070050#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080051#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080052#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080053#include "SensorRecord.h"
54#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080055
56#include <inttypes.h>
57#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070058#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080059#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080060#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070061#include <sys/stat.h>
62#include <sys/types.h>
63#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070064
Andrew Lehmer3a602572021-03-25 15:19:56 -070065#include <ctime>
66#include <future>
67
Svet Ganove752a5c2018-01-15 17:14:20 -080068#include <private/android_filesystem_config.h>
69
Andrew Lehmer3a602572021-03-25 15:19:56 -070070using namespace std::chrono_literals;
71
Mathias Agopianfc328812010-07-14 23:41:37 -070072namespace android {
73// ---------------------------------------------------------------------------
74
Mathias Agopian33015422011-05-27 18:18:13 -070075/*
76 * Notes:
77 *
78 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070079 * - run mag sensor from time to time to force calibration
80 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
81 *
82 */
83
Aravind Akella8ef3c892015-07-10 11:24:28 -070084const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070085uint8_t SensorService::sHmacGlobalKey[128] = {};
86bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070087std::map<String16, int> SensorService::sPackageTargetVersion;
88Mutex SensorService::sPackageTargetVersionLock;
Anthony Stange07eb4212020-08-28 14:50:28 -040089String16 SensorService::sSensorInterfaceDescriptorPrefix =
90 String16("android.frameworks.sensorservice@");
Brian Stack793f4642019-04-18 17:21:34 -070091AppOpsManager SensorService::sAppOpsManager;
Andrew Lehmer3a602572021-03-25 15:19:56 -070092std::atomic_uint64_t SensorService::curProxCallbackSeq(0);
93std::atomic_uint64_t SensorService::completedCallbackSeq(0);
Greg Kaiser53ca2e02016-06-21 16:11:14 -070094
95#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
96#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070097#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070098
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070099// Permissions.
Anh Phamaf91a912021-02-10 14:10:53 +0100100static const String16 sAccessHighSensorSamplingRatePermission(
101 "android.permission.HIGH_SAMPLING_RATE_SENSORS");
Peng Xudd5c5cb2017-03-16 17:39:43 -0700102static const String16 sDumpPermission("android.permission.DUMP");
103static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -0800104static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700105
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200106namespace {
107
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200108int32_t nextRuntimeSensorHandle() {
Vladimir Komsiyski29d2afd2022-12-06 13:24:10 +0100109 using ::aidl::android::hardware::sensors::ISensors;
110 static int32_t nextHandle = ISensors::RUNTIME_SENSORS_HANDLE_BASE;
111 if (nextHandle == ISensors::RUNTIME_SENSORS_HANDLE_END) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200112 return -1;
113 }
114 return nextHandle++;
115}
116
117class RuntimeSensorCallbackProxy : public RuntimeSensor::StateChangeCallback {
118 public:
119 RuntimeSensorCallbackProxy(sp<SensorService::RuntimeSensorStateChangeCallback> callback)
120 : mCallback(std::move(callback)) {}
121 void onStateChanged(bool enabled, int64_t samplingPeriodNs,
122 int64_t batchReportLatencyNs) override {
123 mCallback->onStateChanged(enabled, samplingPeriodNs, batchReportLatencyNs);
124 }
125 private:
126 sp<SensorService::RuntimeSensorStateChangeCallback> mCallback;
127};
128
129} // namespace
130
Tyler Trephanc7b92632021-07-21 10:39:38 -0700131static bool isAutomotive() {
132 sp<IServiceManager> serviceManager = defaultServiceManager();
133 if (serviceManager.get() == nullptr) {
134 ALOGE("%s: unable to access native ServiceManager", __func__);
135 return false;
136 }
137
138 sp<content::pm::IPackageManagerNative> packageManager;
139 sp<IBinder> binder = serviceManager->waitForService(String16("package_native"));
140 packageManager = interface_cast<content::pm::IPackageManagerNative>(binder);
141 if (packageManager == nullptr) {
142 ALOGE("%s: unable to access native PackageManager", __func__);
143 return false;
144 }
145
146 bool isAutomotive = false;
147 binder::Status status =
148 packageManager->hasSystemFeature(String16("android.hardware.type.automotive"), 0,
149 &isAutomotive);
150 if (!status.isOk()) {
151 ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str());
152 return false;
153 }
154
155 return isAutomotive;
156}
157
Mathias Agopianfc328812010-07-14 23:41:37 -0700158SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -0700159 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700160 mWakeLockAcquired(false), mLastReportedProxIsActive(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +0900161 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800162 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Evan Severson4c197852022-01-27 10:44:27 -0800163 mMicSensorPrivacyPolicy = new MicrophonePrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700164}
165
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200166int SensorService::registerRuntimeSensor(
167 const sensor_t& sensor, int deviceId, sp<RuntimeSensorStateChangeCallback> callback) {
168 int handle = 0;
169 while (handle == 0 || !mSensors.isNewHandle(handle)) {
170 handle = nextRuntimeSensorHandle();
171 if (handle < 0) {
172 // Ran out of the dedicated range for runtime sensors.
173 return handle;
174 }
175 }
176
177 ALOGI("Registering runtime sensor handle 0x%x, type %d, name %s",
178 handle, sensor.type, sensor.name);
179
180 sp<RuntimeSensor::StateChangeCallback> runtimeSensorCallback(
181 new RuntimeSensorCallbackProxy(std::move(callback)));
182 sensor_t runtimeSensor = sensor;
183 // force the handle to be consistent
184 runtimeSensor.handle = handle;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100185 auto si = std::make_shared<RuntimeSensor>(runtimeSensor, std::move(runtimeSensorCallback));
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200186
187 Mutex::Autolock _l(mLock);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100188 if (!registerSensor(std::move(si), /* isDebug= */ false, /* isVirtual= */ false, deviceId)) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200189 // The registration was unsuccessful.
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100190 return mSensors.getNonSensor().getHandle();
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200191 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100192
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200193 return handle;
194}
195
196status_t SensorService::unregisterRuntimeSensor(int handle) {
197 ALOGI("Unregistering runtime sensor handle 0x%x disconnected", handle);
198 {
199 Mutex::Autolock _l(mLock);
200 if (!unregisterDynamicSensorLocked(handle)) {
201 ALOGE("Runtime sensor release error.");
202 return UNKNOWN_ERROR;
203 }
204 }
205
206 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
207 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
208 connection->removeSensor(handle);
209 }
210 return OK;
211}
212
213status_t SensorService::sendRuntimeSensorEvent(const sensors_event_t& event) {
214 Mutex::Autolock _l(mLock);
215 mRuntimeSensorEventQueue.push(event);
216 return OK;
217}
218
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700219bool SensorService::initializeHmacKey() {
220 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
221 if (fd != -1) {
222 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
223 close(fd);
224 if (result == sizeof(sHmacGlobalKey)) {
225 return true;
226 }
227 ALOGW("Unable to read HMAC key; generating new one.");
228 }
229
230 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
231 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
232 return false;
233 }
234
235 // We need to make sure this is only readable to us.
236 bool wroteKey = false;
237 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
238 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
239 S_IRUSR|S_IWUSR);
240 if (fd != -1) {
241 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
242 close(fd);
243 wroteKey = (result == sizeof(sHmacGlobalKey));
244 }
245 if (wroteKey) {
246 ALOGI("Generated new HMAC key.");
247 } else {
248 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
249 "after reboot.");
250 }
251 // Even if we failed to write the key we return true, because we did
252 // initialize the HMAC key.
253 return true;
254}
255
Peng Xu98d30f62016-08-01 18:12:11 -0700256// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
257void SensorService::enableSchedFifoMode() {
258 struct sched_param param = {0};
259 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
260 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
261 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
262 }
263}
264
Peng Xu47e96012016-03-28 17:55:56 -0700265void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000266 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800267 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700268
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700269 sHmacGlobalKeyIsValid = initializeHmacKey();
270
Mathias Agopianf001c922010-11-11 17:58:51 -0800271 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800272 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700273 ssize_t count = dev.getSensorList(&list);
274 if (count > 0) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700275 bool hasGyro = false, hasAccel = false, hasMag = false;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700276 bool hasGyroUncalibrated = false;
277 bool hasAccelUncalibrated = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700278 uint32_t virtualSensorsNeeds =
279 (1<<SENSOR_TYPE_GRAVITY) |
280 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700281 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
282 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
283 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700284
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700285 for (ssize_t i=0 ; i<count ; i++) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700286 bool useThisSensor = true;
Peng Xuf66684a2015-07-23 11:41:53 -0700287
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700288 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700289 case SENSOR_TYPE_ACCELEROMETER:
290 hasAccel = true;
291 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700292 case SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED:
293 hasAccelUncalibrated = true;
294 break;
Aravind Akellaf5047892015-07-20 17:29:33 -0700295 case SENSOR_TYPE_MAGNETIC_FIELD:
296 hasMag = true;
297 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700298 case SENSOR_TYPE_GYROSCOPE:
299 hasGyro = true;
300 break;
Tyler Trephanc7b92632021-07-21 10:39:38 -0700301 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
302 hasGyroUncalibrated = true;
303 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700304 case SENSOR_TYPE_GRAVITY:
305 case SENSOR_TYPE_LINEAR_ACCELERATION:
306 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700307 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
308 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
309 if (IGNORE_HARDWARE_FUSION) {
310 useThisSensor = false;
311 } else {
312 virtualSensorsNeeds &= ~(1<<list[i].type);
313 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700314 break;
Arthur Ishiguro2fd90a72021-11-12 17:24:41 +0000315 default:
316 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700317 }
Peng Xuf66684a2015-07-23 11:41:53 -0700318 if (useThisSensor) {
Andrew Lehmer3a602572021-03-25 15:19:56 -0700319 if (list[i].type == SENSOR_TYPE_PROXIMITY) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100320 auto s = std::make_shared<ProximitySensor>(list[i], *this);
321 const int handle = s->getSensor().getHandle();
322 if (registerSensor(std::move(s))) {
323 mProxSensorHandles.push_back(handle);
324 }
Andrew Lehmer3a602572021-03-25 15:19:56 -0700325 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100326 registerSensor(std::make_shared<HardwareSensor>(list[i]));
Andrew Lehmer3a602572021-03-25 15:19:56 -0700327 }
Peng Xuf66684a2015-07-23 11:41:53 -0700328 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700329 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700330
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700331 // it's safe to instantiate the SensorFusion object here
332 // (it wants to be instantiated after h/w sensors have been
333 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700334 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700335
Tyler Trephanc7b92632021-07-21 10:39:38 -0700336 if ((hasGyro || hasGyroUncalibrated) && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700337 // Add Android virtual sensors if they're not already
338 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700339 bool needRotationVector =
340 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100341 registerVirtualSensor(std::make_shared<RotationVectorSensor>(),
342 /* isDebug= */ !needRotationVector);
343 registerVirtualSensor(std::make_shared<OrientationSensor>(),
344 /* isDebug= */ !needRotationVector);
Mathias Agopian03193062013-05-10 19:32:39 -0700345
Peng Xu0cc8f802016-04-05 23:46:03 -0700346 // virtual debugging sensors are not for user
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100347 registerVirtualSensor(std::make_shared<CorrectedGyroSensor>(list, count),
348 /* isDebug= */ true);
349 registerVirtualSensor(std::make_shared<GyroDriftSensor>(), /* isDebug= */ true);
Mathias Agopian33264862012-06-28 19:46:54 -0700350 }
351
Tyler Trephanc7b92632021-07-21 10:39:38 -0700352 if (hasAccel && (hasGyro || hasGyroUncalibrated)) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700353 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100354 registerVirtualSensor(std::make_shared<GravitySensor>(list, count),
355 /* isDebug= */ !needGravitySensor);
Peng Xuf66684a2015-07-23 11:41:53 -0700356
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800357 bool needLinearAcceleration =
358 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100359 registerVirtualSensor(std::make_shared<LinearAccelerationSensor>(list, count),
360 /* isDebug= */ !needLinearAcceleration);
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800361
Peng Xu0cc8f802016-04-05 23:46:03 -0700362 bool needGameRotationVector =
363 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100364 registerVirtualSensor(std::make_shared<GameRotationVectorSensor>(),
365 /* isDebug= */ !needGameRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700366 }
367
368 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700369 bool needGeoMagRotationVector =
370 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100371 registerVirtualSensor(std::make_shared<GeoMagRotationVectorSensor>(),
372 /* isDebug= */ !needGeoMagRotationVector);
Peng Xuf66684a2015-07-23 11:41:53 -0700373 }
374
Tyler Trephanc7b92632021-07-21 10:39:38 -0700375 if (isAutomotive()) {
376 if (hasAccel) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100377 registerVirtualSensor(
378 std::make_shared<LimitedAxesImuSensor>(
379 list, count, SENSOR_TYPE_ACCELEROMETER));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700380 }
381
382 if (hasGyro) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100383 registerVirtualSensor(
384 std::make_shared<LimitedAxesImuSensor>(
385 list, count, SENSOR_TYPE_GYROSCOPE));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700386 }
387
388 if (hasAccelUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100389 registerVirtualSensor(
390 std::make_shared<LimitedAxesImuSensor>(
391 list, count, SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700392 }
393
394 if (hasGyroUncalibrated) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100395 registerVirtualSensor(
396 std::make_shared<LimitedAxesImuSensor>(
397 list, count, SENSOR_TYPE_GYROSCOPE_UNCALIBRATED));
Tyler Trephanc7b92632021-07-21 10:39:38 -0700398 }
399 }
400
Aravind Akella5466c3d2014-08-22 16:11:10 -0700401 // Check if the device really supports batching by looking at the FIFO event
402 // counts for each sensor.
403 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700404 mSensors.forEachSensor(
405 [&batchingSupported] (const Sensor& s) -> bool {
406 if (s.getFifoMaxEventCount() > 0) {
407 batchingSupported = true;
408 }
409 return !batchingSupported;
410 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700411
412 if (batchingSupported) {
413 // Increase socket buffer size to a max of 100 KB for batching capabilities.
414 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
415 } else {
416 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
417 }
418
419 // Compare the socketBufferSize value against the system limits and limit
420 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700421 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
422 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700423 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700424 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700425 size_t maxSystemSocketBufferSize;
426 sscanf(line, "%zu", &maxSystemSocketBufferSize);
427 if (mSocketBufferSize > maxSystemSocketBufferSize) {
428 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700429 }
430 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700431 if (fp) {
432 fclose(fp);
433 }
434
Aravind Akella9a844cf2014-02-11 18:58:52 -0800435 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700436 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700437 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
438 mSensorEventBuffer = new sensors_event_t[minBufferSize];
439 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700440 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700441 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700442
Aravind Akella18d6d512015-06-18 14:18:28 -0700443 mNextSensorRegIndex = 0;
444 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
445 mLastNSensorRegistrations.push();
446 }
447
448 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700449 mAckReceiver = new SensorEventAckReceiver(this);
450 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700451 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700452
453 // priority can only be changed after run
454 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800455
456 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800457 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800458
459 // Start watching sensor privacy changes
460 mSensorPrivacyPolicy->registerSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800461
462 // Start watching mic sensor privacy changes
463 mMicSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800464 }
465 }
466}
467
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700468void SensorService::onUidStateChanged(uid_t uid, UidState state) {
469 SensorDevice& dev(SensorDevice::getInstance());
470
Brian Duddie967ce172019-06-10 11:08:27 -0700471 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700472 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700473 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700474 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700475 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700476 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700477
478 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
479 if (conn->getUid() == uid) {
480 // Update sensor subscriptions if needed
481 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
482 conn->onSensorAccessChanged(hasAccess);
483 }
484 }
Chris Kuiper587ef9b2021-10-12 16:36:43 -0700485 checkAndReportProxStateChangeLocked();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700486}
487
488bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
489 Mutex::Autolock _l(mLock);
490 return hasSensorAccessLocked(uid, opPackageName);
491}
492
493bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
494 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
495 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700496}
497
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100498bool SensorService::registerSensor(std::shared_ptr<SensorInterface> s, bool isDebug, bool isVirtual,
499 int deviceId) {
500 const int handle = s->getSensor().getHandle();
501 const int type = s->getSensor().getType();
502 if (mSensors.add(handle, std::move(s), isDebug, isVirtual, deviceId)) {
Brian Stack4baa5be2018-09-18 14:03:13 -0700503 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100504 return true;
Peng Xu0cc8f802016-04-05 23:46:03 -0700505 } else {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100506 LOG_FATAL("Failed to register sensor with handle %d", handle);
507 return false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700508 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800509}
510
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100511bool SensorService::registerDynamicSensorLocked(std::shared_ptr<SensorInterface> s, bool isDebug) {
512 return registerSensor(std::move(s), isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800513}
514
Peng Xu6a2d3a02015-12-21 12:00:23 -0800515bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700516 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800517
518 const auto i = mRecentEvent.find(handle);
519 if (i != mRecentEvent.end()) {
520 delete i->second;
521 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800522 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700523 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800524}
525
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100526bool SensorService::registerVirtualSensor(std::shared_ptr<SensorInterface> s, bool isDebug) {
527 return registerSensor(std::move(s), isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700528}
529
Peng Xu47e96012016-03-28 17:55:56 -0700530SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800531 for (auto && entry : mRecentEvent) {
532 delete entry.second;
533 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800534 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800535 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson4c197852022-01-27 10:44:27 -0800536 mMicSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700537}
538
539status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700540 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700541 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800542 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700543 IPCThreadState::self()->getCallingPid(),
544 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700545 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700546 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700547 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800548 return INVALID_OPERATION;
549 }
Brian Duddie967ce172019-06-10 11:08:27 -0700550 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800551 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700552 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700553 // If already in restricted mode. Ignore.
554 if (mCurrentOperatingMode == RESTRICTED) {
555 return status_t(NO_ERROR);
556 }
557 // If in any mode other than normal, ignore.
558 if (mCurrentOperatingMode != NORMAL) {
559 return INVALID_OPERATION;
560 }
Peng Xue36e3472016-11-03 11:57:10 -0700561
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700562 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800563 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700564 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700565 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700566 return status_t(NO_ERROR);
567 } else if (args.size() == 1 && args[0] == String16("enable")) {
568 // If currently in restricted mode, reset back to NORMAL mode else ignore.
569 if (mCurrentOperatingMode == RESTRICTED) {
570 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800571 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700572 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700573 }
Aravind Akella841a5922015-06-29 12:37:48 -0700574 if (mCurrentOperatingMode == DATA_INJECTION) {
575 resetToNormalModeLocked();
576 }
577 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700578 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700579 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
580 if (mCurrentOperatingMode == NORMAL) {
581 dev.disableAllSensors();
582 status_t err = dev.setMode(DATA_INJECTION);
583 if (err == NO_ERROR) {
584 mCurrentOperatingMode = DATA_INJECTION;
585 } else {
586 // Re-enable sensors.
587 dev.enableAllSensors();
588 }
589 mWhiteListedPackage.setTo(String8(args[1]));
590 return NO_ERROR;
591 } else if (mCurrentOperatingMode == DATA_INJECTION) {
592 // Already in DATA_INJECTION mode. Treat this as a no_op.
593 return NO_ERROR;
594 } else {
595 // Transition to data injection mode supported only from NORMAL mode.
596 return INVALID_OPERATION;
597 }
Mike Ma24743862020-01-29 00:36:55 -0800598 } else if (args.size() == 1 && args[0] == String16("--proto")) {
599 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700600 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700601 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700602 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700603 } else {
604 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700605 //
Brian Stack51498e62018-10-03 10:52:21 -0700606 timespec curTime;
607 clock_gettime(CLOCK_REALTIME, &curTime);
608 struct tm* timeinfo = localtime(&(curTime.tv_sec));
609 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
610 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800611 result.append("Sensor Device:\n");
612 result.append(SensorDevice::getInstance().dump().c_str());
613
614 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700615 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700616
Peng Xu6a2d3a02015-12-21 12:00:23 -0800617 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700618 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700619
Peng Xu0cc8f802016-04-05 23:46:03 -0700620 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800621 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100622 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
623 if (!i.second->isEmpty() && s != nullptr) {
Peng Xufba3c112016-09-08 12:36:59 -0700624 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
625 i.second->setFormat("normal");
626 } else {
627 i.second->setFormat("mask_data");
628 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800629 // if there is events and sensor does not need special permission.
630 result.appendFormat("%s: ", s->getSensor().getName().string());
631 result.append(i.second->dump().c_str());
632 }
633 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700634
Aravind Akella444f2672015-05-07 12:40:52 -0700635 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700636 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700637 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
638 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700639 if (dev.isSensorActive(handle)) {
640 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
641 getSensorName(handle).string(),
642 handle,
643 mActiveSensors.valueAt(i)->getNumConnections());
644 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700645 }
646
Andreas Gamped4036b62015-07-28 13:49:04 -0700647 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700648 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700649 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
650 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700651 result.appendFormat("Mode :");
652 switch(mCurrentOperatingMode) {
653 case NORMAL:
654 result.appendFormat(" NORMAL\n");
655 break;
656 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700657 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700658 break;
659 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700660 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700661 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800662 result.appendFormat("Sensor Privacy: %s\n",
663 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700664
Brian Duddie967ce172019-06-10 11:08:27 -0700665 const auto& activeConnections = connLock.getActiveConnections();
666 result.appendFormat("%zd active connections\n", activeConnections.size());
667 for (size_t i=0 ; i < activeConnections.size() ; i++) {
668 result.appendFormat("Connection Number: %zu \n", i);
669 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700670 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700671
Brian Duddie967ce172019-06-10 11:08:27 -0700672 const auto& directConnections = connLock.getDirectConnections();
673 result.appendFormat("%zd direct connections\n", directConnections.size());
674 for (size_t i = 0 ; i < directConnections.size() ; i++) {
675 result.appendFormat("Direct connection %zu:\n", i);
676 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700677 }
678
Aravind Akella18d6d512015-06-18 14:18:28 -0700679 result.appendFormat("Previous Registrations:\n");
680 // Log in the reverse chronological order.
681 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
682 SENSOR_REGISTRATIONS_BUF_SIZE;
683 const int startIndex = currentIndex;
684 do {
685 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
686 if (SensorRegistrationInfo::isSentinel(reg_info)) {
687 // Ignore sentinel, proceed to next item.
688 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
689 SENSOR_REGISTRATIONS_BUF_SIZE;
690 continue;
691 }
Peng Xu51224682017-03-10 16:57:27 -0800692 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700693 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
694 SENSOR_REGISTRATIONS_BUF_SIZE;
695 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700696 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700697 }
698 write(fd, result.string(), result.size());
699 return NO_ERROR;
700}
701
Mike Ma24743862020-01-29 00:36:55 -0800702/**
703 * Dump debugging information as android.service.SensorServiceProto protobuf message using
704 * ProtoOutputStream.
705 *
706 * See proto definition and some notes about ProtoOutputStream in
707 * frameworks/base/core/proto/android/service/sensor_service.proto
708 */
709status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
710 using namespace service::SensorServiceProto;
711 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800712 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
713 if (!mSensors.hasAnySensor()) {
714 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
715 }
Mike Ma24743862020-01-29 00:36:55 -0800716 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
717
718 timespec curTime;
719 clock_gettime(CLOCK_REALTIME, &curTime);
720 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
721
722 // Write SensorDeviceProto
723 uint64_t token = proto.start(SENSOR_DEVICE);
724 SensorDevice::getInstance().dump(&proto);
725 proto.end(token);
726
727 // Write SensorListProto
728 token = proto.start(SENSORS);
729 mSensors.dump(&proto);
730 proto.end(token);
731
732 // Write SensorFusionProto
733 token = proto.start(FUSION_STATE);
734 SensorFusion::getInstance().dump(&proto);
735 proto.end(token);
736
737 // Write SensorEventsProto
738 token = proto.start(SENSOR_EVENTS);
739 for (auto&& i : mRecentEvent) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100740 std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
741 if (!i.second->isEmpty() && s != nullptr) {
Mike Ma24743862020-01-29 00:36:55 -0800742 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
743 "normal" : "mask_data");
744 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
745 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
746 std::string(s->getSensor().getName().string()));
747 i.second->dump(&proto);
748 proto.end(mToken);
749 }
750 }
751 proto.end(token);
752
753 // Write ActiveSensorProto
754 SensorDevice& dev = SensorDevice::getInstance();
755 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
756 int handle = mActiveSensors.keyAt(i);
757 if (dev.isSensorActive(handle)) {
758 token = proto.start(ACTIVE_SENSORS);
759 proto.write(service::ActiveSensorProto::NAME,
760 std::string(getSensorName(handle).string()));
761 proto.write(service::ActiveSensorProto::HANDLE, handle);
762 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
763 int(mActiveSensors.valueAt(i)->getNumConnections()));
764 proto.end(token);
765 }
766 }
767
768 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
769 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
770 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
771
772 switch(mCurrentOperatingMode) {
773 case NORMAL:
774 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
775 break;
776 case RESTRICTED:
777 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
778 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
779 break;
780 case DATA_INJECTION:
781 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
782 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
783 break;
784 default:
785 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
786 }
787 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
788
789 // Write repeated SensorEventConnectionProto
790 const auto& activeConnections = connLock->getActiveConnections();
791 for (size_t i = 0; i < activeConnections.size(); i++) {
792 token = proto.start(ACTIVE_CONNECTIONS);
793 activeConnections[i]->dump(&proto);
794 proto.end(token);
795 }
796
797 // Write repeated SensorDirectConnectionProto
798 const auto& directConnections = connLock->getDirectConnections();
799 for (size_t i = 0 ; i < directConnections.size() ; i++) {
800 token = proto.start(DIRECT_CONNECTIONS);
801 directConnections[i]->dump(&proto);
802 proto.end(token);
803 }
804
805 // Write repeated SensorRegistrationInfoProto
806 const int startIndex = mNextSensorRegIndex;
807 int curr = startIndex;
808 do {
809 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
810 if (SensorRegistrationInfo::isSentinel(reg_info)) {
811 // Ignore sentinel, proceed to next item.
812 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
813 continue;
814 }
815 token = proto.start(PREVIOUS_REGISTRATIONS);
816 reg_info.dump(&proto);
817 proto.end(token);
818 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
819 } while (startIndex != curr);
820
821 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
822}
823
Michael Groover5e1f60b2018-12-04 22:34:29 -0800824void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700825 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
826 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800827}
828
Brian Duddie967ce172019-06-10 11:08:27 -0700829void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800830 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700831 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
832 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
833 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800834 }
835 dev.disableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700836 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800837 // Clear all pending flush connections for all active sensors. If one of the active
838 // connections has called flush() and the underlying sensor has been disabled before a
839 // flush complete event is returned, we need to remove the connection from this queue.
840 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
841 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
842 }
843}
844
845void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700846 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
847 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800848}
849
Brian Duddie967ce172019-06-10 11:08:27 -0700850void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800851 // sensors should only be enabled if the operating state is not restricted and sensor
852 // privacy is not enabled.
853 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
854 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
855 mCurrentOperatingMode,
856 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
857 return;
858 }
859 SensorDevice& dev(SensorDevice::getInstance());
860 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700861 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
862 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
863 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800864 }
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700865 checkAndReportProxStateChangeLocked();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800866}
867
Evan Severson4c197852022-01-27 10:44:27 -0800868void SensorService::capRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100869 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
870 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800871 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100872 }
873
874 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800875 conn->onMicSensorAccessChanged(true);
Anh Pham5198c992021-02-10 14:15:30 +0100876 }
877}
878
Evan Severson4c197852022-01-27 10:44:27 -0800879void SensorService::uncapRates() {
Anh Pham5198c992021-02-10 14:15:30 +0100880 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
881 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800882 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100883 }
884
885 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Evan Severson4c197852022-01-27 10:44:27 -0800886 conn->onMicSensorAccessChanged(false);
Anh Pham5198c992021-02-10 14:15:30 +0100887 }
888}
Brian Duddie967ce172019-06-10 11:08:27 -0700889
Svet Ganove752a5c2018-01-15 17:14:20 -0800890// NOTE: This is a remote API - make sure all args are validated
891status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
892 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
893 return PERMISSION_DENIED;
894 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700895 if (args.size() == 0) {
896 return BAD_INDEX;
897 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800898 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
899 return BAD_VALUE;
900 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700901 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800902 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700903 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800904 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700905 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800906 return handleGetUidState(args, out, err);
Brian Duddie4a4d0462022-05-09 16:49:49 -0700907 } else if (args[0] == String16("unrestrict-ht")) {
908 mHtRestricted = false;
909 return NO_ERROR;
910 } else if (args[0] == String16("restrict-ht")) {
911 mHtRestricted = true;
912 return NO_ERROR;
Svet Ganove752a5c2018-01-15 17:14:20 -0800913 } else if (args.size() == 1 && args[0] == String16("help")) {
914 printHelp(out);
915 return NO_ERROR;
916 }
917 printHelp(err);
918 return BAD_VALUE;
919}
920
Tanmay Patild33a1822019-04-11 18:38:55 -0700921static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800922 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700923 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800924 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700925 ALOGE("Unknown package: '%s'", String8(packageName).string());
926 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800927 return BAD_VALUE;
928 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700929
930 if (userId < 0) {
931 ALOGE("Invalid user: %d", userId);
932 dprintf(err, "Invalid user: %d\n", userId);
933 return BAD_VALUE;
934 }
935
936 uid = multiuser_get_uid(userId, uid);
937 return NO_ERROR;
938}
939
940status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
941 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
942 if (!(args.size() == 3 || args.size() == 5)) {
943 printHelp(err);
944 return BAD_VALUE;
945 }
946
Svet Ganove752a5c2018-01-15 17:14:20 -0800947 bool active = false;
948 if (args[2] == String16("active")) {
949 active = true;
950 } else if ((args[2] != String16("idle"))) {
951 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
952 return BAD_VALUE;
953 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700954
955 int userId = 0;
956 if (args.size() == 5 && args[3] == String16("--user")) {
957 userId = atoi(String8(args[4]));
958 }
959
960 uid_t uid;
961 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
962 return BAD_VALUE;
963 }
964
Svet Ganove752a5c2018-01-15 17:14:20 -0800965 mUidPolicy->addOverrideUid(uid, active);
966 return NO_ERROR;
967}
968
969status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700970 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
971 if (!(args.size() == 2 || args.size() == 4)) {
972 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800973 return BAD_VALUE;
974 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700975
976 int userId = 0;
977 if (args.size() == 4 && args[2] == String16("--user")) {
978 userId = atoi(String8(args[3]));
979 }
980
981 uid_t uid;
982 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
983 return BAD_VALUE;
984 }
985
Svet Ganove752a5c2018-01-15 17:14:20 -0800986 mUidPolicy->removeOverrideUid(uid);
987 return NO_ERROR;
988}
989
990status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700991 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
992 if (!(args.size() == 2 || args.size() == 4)) {
993 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800994 return BAD_VALUE;
995 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700996
997 int userId = 0;
998 if (args.size() == 4 && args[2] == String16("--user")) {
999 userId = atoi(String8(args[3]));
1000 }
1001
1002 uid_t uid;
1003 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1004 return BAD_VALUE;
1005 }
1006
Svet Ganove752a5c2018-01-15 17:14:20 -08001007 if (mUidPolicy->isUidActive(uid)) {
1008 return dprintf(out, "active\n");
1009 } else {
1010 return dprintf(out, "idle\n");
1011 }
1012}
1013
1014status_t SensorService::printHelp(int out) {
1015 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -07001016 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1017 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1018 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -08001019 " help print this message\n");
1020}
1021
Peng Xu0cc8f802016-04-05 23:46:03 -07001022//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -08001023void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001024 sensors_event_t const* buffer, const int count) {
1025 for (int i=0 ; i<count ; i++) {
1026 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -07001027 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1028 handle = buffer[i].meta_data.sensor;
1029 }
Aravind Akella0e025c52014-06-03 19:19:57 -07001030 if (connection->hasSensor(handle)) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001031 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -07001032 // If this buffer has an event from a one_shot sensor and this connection is registered
1033 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -07001034 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -07001035 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1036 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001037 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001038 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001039
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001040 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001041 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001042}
1043
Peng Xu47e96012016-03-28 17:55:56 -07001044bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +00001045 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -07001046
Peng Xueb4d6282015-12-10 18:02:41 -08001047 // each virtual sensor could generate an event per "real" event, that's why we need to size
1048 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
1049 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -07001050 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001051 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -07001052 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -07001053
Mathias Agopianf001c922010-11-11 17:58:51 -08001054 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -07001055
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001056 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -07001057 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001058 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
1059 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -07001060 if(count == DEAD_OBJECT && device.isReconnecting()) {
1061 device.reconnect();
1062 continue;
1063 } else {
1064 ALOGE("sensor poll failed (%s)", strerror(-count));
1065 break;
1066 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001067 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001068
1069 // Reset sensors_event_t.flags to zero for all events in the buffer.
1070 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001071 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001072 }
Brian Duddie967ce172019-06-10 11:08:27 -07001073 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -07001074
Aravind Akella9a844cf2014-02-11 18:58:52 -08001075 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
1076 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
1077 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
1078 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
1079 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001080 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001081 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001082 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001083 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001084 }
1085 }
1086
Brian Stackb7bfc0f2018-09-25 09:41:16 -07001087 if (wakeEvents > 0) {
1088 if (!mWakeLockAcquired) {
1089 setWakeLockAcquiredLocked(true);
1090 }
1091 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001092 }
Aravind Akella8493b792014-09-08 15:45:47 -07001093 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -08001094
Mathias Agopianf001c922010-11-11 17:58:51 -08001095 // handle virtual sensors
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001096 bool bufferNeedsSorting = false;
Mathias Agopianf001c922010-11-11 17:58:51 -08001097 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -07001098 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -07001099 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001100 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -07001101 SensorFusion& fusion(SensorFusion::getInstance());
1102 if (fusion.isEnabled()) {
1103 for (size_t i=0 ; i<size_t(count) ; i++) {
1104 fusion.process(event[i]);
1105 }
1106 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001107 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -07001108 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001109 if (count + k >= minBufferSize) {
1110 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -07001111 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001112 count, k, minBufferSize);
1113 break;
1114 }
Mathias Agopianf001c922010-11-11 17:58:51 -08001115 sensors_event_t out;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001116 std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001117 if (si == nullptr) {
1118 ALOGE("handle %d is not an valid virtual sensor", handle);
1119 continue;
1120 }
1121
Mathias Agopiand1920ff2012-05-29 19:46:14 -07001122 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -07001123 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -08001124 k++;
1125 }
1126 }
1127 }
1128 if (k) {
1129 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -07001130 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -08001131 count += k;
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001132 bufferNeedsSorting = true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001133 }
1134 }
1135 }
1136
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001137 // handle runtime sensors
1138 {
1139 size_t k = 0;
1140 while (!mRuntimeSensorEventQueue.empty()) {
1141 if (count + k >= minBufferSize) {
1142 ALOGE("buffer too small to hold all events: count=%zd, k=%zu, size=%zu",
1143 count, k, minBufferSize);
1144 break;
1145 }
1146 mSensorEventBuffer[count + k] = mRuntimeSensorEventQueue.front();
1147 mRuntimeSensorEventQueue.pop();
1148 k++;
1149 }
1150 if (k) {
1151 // record the last synthesized values
1152 recordLastValueLocked(&mSensorEventBuffer[count], k);
1153 count += k;
1154 bufferNeedsSorting = true;
1155 }
1156 }
1157
1158 if (bufferNeedsSorting) {
1159 // sort the buffer by time-stamps
1160 sortEventBuffer(mSensorEventBuffer, count);
1161 }
1162
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001163 // handle backward compatibility for RotationVector sensor
1164 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
1165 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -07001166 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001167 // All the 4 components of the quaternion should be available
1168 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -07001169 mSensorEventBuffer[i].data[4] = -1;
1170 }
1171 }
1172 }
1173
Brian Duddie967ce172019-06-10 11:08:27 -07001174 // Cache the list of active connections, since we use it in multiple places below but won't
1175 // modify it here
1176 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
1177
Aravind Akella8493b792014-09-08 15:45:47 -07001178 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -07001179 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
1180 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
1181 // SensorEventConnection mapped to the corresponding flush_complete_event in
1182 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -07001183 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -07001184 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
1185 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
1186 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001187 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -07001188 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
1189 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001190 }
1191 }
Peng Xu2576cb62016-01-20 00:22:09 -08001192
1193 // handle dynamic sensor meta events, process registration and unregistration of dynamic
1194 // sensor based on content of event.
1195 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
1196 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
1197 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1198 const sensor_t& dynamicSensor =
1199 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
1200 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
1201 handle, dynamicSensor.type, dynamicSensor.name);
1202
Peng Xu0cc8f802016-04-05 23:46:03 -07001203 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -08001204 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -07001205 sensor_t s = dynamicSensor;
1206 // make sure the dynamic sensor flag is set
1207 s.flags |= DYNAMIC_SENSOR_MASK;
1208 // force the handle to be consistent
1209 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -08001210
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001211 auto si = std::make_shared<HardwareSensor>(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -08001212
Peng Xu0cc8f802016-04-05 23:46:03 -07001213 // This will release hold on dynamic sensor meta, so it should be called
1214 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -07001215 device.handleDynamicSensorConnection(handle, true /*connected*/);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001216 registerDynamicSensorLocked(std::move(si));
Peng Xu47e96012016-03-28 17:55:56 -07001217 } else {
1218 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
1219 }
Peng Xu2576cb62016-01-20 00:22:09 -08001220 } else {
1221 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
1222 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1223
1224 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001225 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -08001226 ALOGE("Dynamic sensor release error.");
1227 }
1228
Brian Duddie967ce172019-06-10 11:08:27 -07001229 for (const sp<SensorEventConnection>& connection : activeConnections) {
1230 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001231 }
1232 }
1233 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001234 }
1235
Aravind Akella9a844cf2014-02-11 18:58:52 -08001236 // Send our events to clients. Check the state of wake lock for each client and release the
1237 // lock if none of the clients need it.
1238 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001239 for (const sp<SensorEventConnection>& connection : activeConnections) {
1240 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1241 mMapFlushEventsToConnections);
1242 needsWakeLock |= connection->needsWakeLock();
1243 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1244 // Early check for one-shot sensors.
1245 if (connection->hasOneShotSensors()) {
1246 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001247 }
1248 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001249
Aravind Akella9a844cf2014-02-11 18:58:52 -08001250 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001251 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001252 }
Aravind Akella8493b792014-09-08 15:45:47 -07001253 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001254
Steve Block3c20fbe2012-01-05 23:22:43 +00001255 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001256 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001257 return false;
1258}
1259
Aravind Akella56ae4262014-07-10 16:01:10 -07001260sp<Looper> SensorService::getLooper() const {
1261 return mLooper;
1262}
1263
Aravind Akellab4373ac2014-10-29 17:55:20 -07001264void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001265 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1266 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1267 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001268 }
Brian Duddie967ce172019-06-10 11:08:27 -07001269 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001270}
1271
1272void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1273 if (acquire) {
1274 if (!mWakeLockAcquired) {
1275 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1276 mWakeLockAcquired = true;
1277 }
1278 mLooper->wake();
1279 } else {
1280 if (mWakeLockAcquired) {
1281 release_wake_lock(WAKE_LOCK_NAME);
1282 mWakeLockAcquired = false;
1283 }
1284 }
1285}
1286
Aravind Akellab4373ac2014-10-29 17:55:20 -07001287bool SensorService::isWakeLockAcquired() {
1288 Mutex::Autolock _l(mLock);
1289 return mWakeLockAcquired;
1290}
1291
Aravind Akella56ae4262014-07-10 16:01:10 -07001292bool SensorService::SensorEventAckReceiver::threadLoop() {
1293 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001294 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001295 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001296 bool wakeLockAcquired = mService->isWakeLockAcquired();
1297 int timeout = -1;
1298 if (wakeLockAcquired) timeout = 5000;
1299 int ret = looper->pollOnce(timeout);
1300 if (ret == ALOOPER_POLL_TIMEOUT) {
1301 mService->resetAllWakeLockRefCounts();
1302 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001303 } while(!Thread::exitPending());
1304 return false;
1305}
1306
Aravind Akella9a844cf2014-02-11 18:58:52 -08001307void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001308 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001309 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001310 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1311 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001312 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001313 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001314 }
Peng Xu2576cb62016-01-20 00:22:09 -08001315
Peng Xu6a2d3a02015-12-21 12:00:23 -08001316 auto logger = mRecentEvent.find(buffer[i].sensor);
1317 if (logger != mRecentEvent.end()) {
1318 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001319 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001320 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001321}
1322
Peng Xu47e96012016-03-28 17:55:56 -07001323void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001324 struct compar {
1325 static int cmp(void const* lhs, void const* rhs) {
1326 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1327 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001328 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001329 }
1330 };
1331 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1332}
1333
Mathias Agopian5d270722010-07-19 15:20:39 -07001334String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001335 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001336}
1337
Arthur Ishiguro883748c2020-10-28 13:18:02 -07001338String8 SensorService::getSensorStringType(int handle) const {
1339 return mSensors.getStringType(handle);
1340}
1341
Aravind Akellab4099e72013-10-15 15:43:10 -07001342bool SensorService::isVirtualSensor(int handle) const {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001343 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001344 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001345}
1346
Aravind Akella9a844cf2014-02-11 18:58:52 -08001347bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001348 int handle = event.sensor;
1349 if (event.type == SENSOR_TYPE_META_DATA) {
1350 handle = event.meta_data.sensor;
1351 }
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001352 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001353 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001354}
1355
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001356int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1357 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1358 // UUID is not supported for this device.
1359 return 0;
1360 }
1361 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1362 // This sensor can be uniquely identified in the system by
1363 // the combination of its type and name.
1364 return -1;
1365 }
1366
1367 // We have a dynamic sensor.
1368
1369 if (!sHmacGlobalKeyIsValid) {
lifr3ab0a1b2021-08-06 00:14:26 +08001370 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001371 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1372 return 0;
1373 }
1374
1375 // We want each app author/publisher to get a different ID, so that the
1376 // same dynamic sensor cannot be tracked across apps by multiple
1377 // authors/publishers. So we use both our UUID and our User ID.
1378 // Note potential confusion:
1379 // UUID => Universally Unique Identifier.
1380 // UID => User Identifier.
1381 // We refrain from using "uid" except as needed by API to try to
1382 // keep this distinction clear.
1383
1384 auto appUserId = IPCThreadState::self()->getCallingUid();
1385 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1386 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1387 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1388
1389 // Now we use our key on our UUID/app combo to get the hash.
1390 uint8_t hash[EVP_MAX_MD_SIZE];
1391 unsigned int hashLen;
1392 if (HMAC(EVP_sha256(),
1393 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1394 uuidAndApp, sizeof(uuidAndApp),
1395 hash, &hashLen) == nullptr) {
lifr3ab0a1b2021-08-06 00:14:26 +08001396 // Rather than risk exposing UUIDs, we slow down dynamic sensors.
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001397 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1398 return 0;
1399 }
1400
1401 int32_t id = 0;
1402 if (hashLen < sizeof(id)) {
1403 // We never expect this case, but out of paranoia, we handle it.
1404 // Our 'id' length is already quite small, we don't want the
1405 // effective length of it to be even smaller.
1406 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1407 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1408 return 0;
1409 }
1410
1411 // This is almost certainly less than all of 'hash', but it's as secure
1412 // as we can be with our current 'id' length.
1413 memcpy(&id, hash, sizeof(id));
1414
1415 // Note at the beginning of the function that we return the values of
1416 // 0 and -1 to represent special cases. As a result, we can't return
1417 // those as dynamic sensor IDs. If we happened to hash to one of those
1418 // values, we change 'id' so we report as a dynamic sensor, and not as
1419 // one of those special cases.
1420 if (id == -1) {
1421 id = -2;
1422 } else if (id == 0) {
1423 id = 1;
1424 }
1425 return id;
1426}
1427
1428void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1429 for (auto &sensor : sensorList) {
1430 int32_t id = getIdFromUuid(sensor.getUuid());
1431 sensor.setId(id);
Eric Laurente3f27df2022-01-05 19:20:32 +01001432 // The sensor UUID must always be anonymized here for non privileged clients.
1433 // There is no other checks after this point before returning to client process.
1434 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1435 sensor.anonymizeUuid();
1436 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001437 }
1438}
1439
Anh Pham4e291332021-02-10 14:17:56 +01001440Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -07001441 char value[PROPERTY_VALUE_MAX];
1442 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001443 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001444 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001445 Vector<Sensor> accessibleSensorList;
Anh Pham4e291332021-02-10 14:17:56 +01001446
Brian Duddie0d4ac562022-05-23 17:47:50 -07001447 resetTargetSdkVersionCache(opPackageName);
Anh Pham4e291332021-02-10 14:17:56 +01001448 bool isCapped = isRateCappedBasedOnPermission(opPackageName);
Aravind Akella70018042014-04-07 22:52:37 +00001449 for (size_t i = 0; i < initialSensorList.size(); i++) {
1450 Sensor sensor = initialSensorList[i];
Anh Pham4e291332021-02-10 14:17:56 +01001451 if (isCapped && isSensorInCappedSet(sensor.getType())) {
1452 sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
1453 sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
1454 }
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001455 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001456 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001457 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001458 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001459}
1460
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001461void SensorService::addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
1462 Vector<Sensor>& accessibleSensorList) {
1463 if (canAccessSensor(sensor, "can't see", opPackageName)) {
1464 accessibleSensorList.add(sensor);
1465 } else if (sensor.getType() != SENSOR_TYPE_HEAD_TRACKER) {
1466 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1467 sensor.getName().string(), sensor.getRequiredPermission().string(),
1468 sensor.getRequiredAppOp());
1469 }
1470}
1471
Peng Xu47e96012016-03-28 17:55:56 -07001472Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001473 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001474 mSensors.forEachSensor(
Brian Duddie4a4d0462022-05-09 16:49:49 -07001475 [this, &opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001476 if (sensor.isDynamicSensor()) {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +02001477 addSensorIfAccessible(opPackageName, sensor, accessibleSensorList);
1478 }
1479 return true;
1480 });
1481 makeUuidsIntoIdsForSensorList(accessibleSensorList);
1482 return accessibleSensorList;
1483}
1484
1485Vector<Sensor> SensorService::getRuntimeSensorList(const String16& opPackageName, int deviceId) {
1486 Vector<Sensor> accessibleSensorList;
1487 mSensors.forEachEntry(
1488 [this, &opPackageName, deviceId, &accessibleSensorList] (
1489 const SensorServiceUtil::SensorList::Entry& e) -> bool {
1490 if (e.deviceId == deviceId) {
1491 addSensorIfAccessible(opPackageName, e.si->getSensor(), accessibleSensorList);
Peng Xu0cc8f802016-04-05 23:46:03 -07001492 }
1493 return true;
1494 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001495 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001496 return accessibleSensorList;
1497}
1498
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001499sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001500 int requestedMode, const String16& opPackageName, const String16& attributionTag) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001501 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1502 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001503 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001504 }
Brian Duddie0d4ac562022-05-23 17:47:50 -07001505 resetTargetSdkVersionCache(opPackageName);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001506
1507 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001508 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1509 // operating in DI mode.
1510 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001511 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1512 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001513 }
1514
Mathias Agopian5307d172012-09-18 17:02:43 -07001515 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001516 pid_t pid = IPCThreadState::self()->getCallingPid();
1517
1518 String8 connPackageName =
1519 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1520 String16 connOpPackageName =
1521 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1522 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -08001523 requestedMode == DATA_INJECTION, connOpPackageName, attributionTag));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001524 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001525 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001526 // Add the associated file descriptor to the Looper for polling whenever there is data to
1527 // be injected.
1528 result->updateLooperRegistration(mLooper);
1529 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001530 return result;
1531}
1532
Aravind Akella841a5922015-06-29 12:37:48 -07001533int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001534 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001535 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001536}
1537
Peng Xue36e3472016-11-03 11:57:10 -07001538sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1539 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1540 const native_handle *resource) {
Brian Duddie0d4ac562022-05-23 17:47:50 -07001541 resetTargetSdkVersionCache(opPackageName);
Brian Duddie967ce172019-06-10 11:08:27 -07001542 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001543
Michael Groover5e1f60b2018-12-04 22:34:29 -08001544 // No new direct connections are allowed when sensor privacy is enabled
1545 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1546 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1547 return nullptr;
1548 }
1549
Peng Xue36e3472016-11-03 11:57:10 -07001550 struct sensors_direct_mem_t mem = {
1551 .type = type,
1552 .format = format,
1553 .size = size,
1554 .handle = resource,
1555 };
1556 uid_t uid = IPCThreadState::self()->getCallingUid();
1557
1558 if (mem.handle == nullptr) {
1559 ALOGE("Failed to clone resource handle");
1560 return nullptr;
1561 }
1562
1563 // check format
1564 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1565 ALOGE("Direct channel format %d is unsupported!", format);
1566 return nullptr;
1567 }
1568
1569 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001570 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1571 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001572 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001573 return nullptr;
1574 }
1575 }
1576
1577 // check specific to memory type
1578 switch(type) {
1579 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001580 if (resource->numFds < 1) {
1581 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1582 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1583 return nullptr;
1584 }
Peng Xue36e3472016-11-03 11:57:10 -07001585 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001586 if (!ashmem_valid(fd)) {
1587 ALOGE("Supplied Ashmem memory region is invalid");
1588 return nullptr;
1589 }
1590
Peng Xue36e3472016-11-03 11:57:10 -07001591 int size2 = ashmem_get_size_region(fd);
1592 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001593 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001594 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1595 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001596 return nullptr;
1597 }
1598 break;
1599 }
1600 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001601 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001602 break;
1603 default:
1604 ALOGE("Unknown direct connection memory type %d", type);
1605 return nullptr;
1606 }
1607
1608 native_handle_t *clone = native_handle_clone(resource);
1609 if (!clone) {
1610 return nullptr;
1611 }
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001612 native_handle_set_fdsan_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001613
Brian Duddie967ce172019-06-10 11:08:27 -07001614 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001615 SensorDevice& dev(SensorDevice::getInstance());
1616 int channelHandle = dev.registerDirectChannel(&mem);
1617
1618 if (channelHandle <= 0) {
1619 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1620 } else {
1621 mem.handle = clone;
1622 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1623 }
1624
1625 if (conn == nullptr) {
Brian Duddie0a4cebb2022-08-25 19:20:18 +00001626 native_handle_close_with_tag(clone);
Peng Xue36e3472016-11-03 11:57:10 -07001627 native_handle_delete(clone);
1628 } else {
1629 // add to list of direct connections
1630 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001631 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001632 }
1633 return conn;
1634}
1635
Peng Xudd5c5cb2017-03-16 17:39:43 -07001636int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001637 int32_t handle, int32_t type,
1638 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001639 Mutex::Autolock _l(mLock);
1640
Alexey Polyudov88711e82017-05-23 19:54:04 -07001641 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001642 return PERMISSION_DENIED;
1643 }
1644
1645 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001646 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001647 size_t expectSize = INT32_MAX;
1648 switch (type) {
1649 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1650 isFloat = true;
1651 expectSize = 3;
1652 break;
1653 case AINFO_LOCAL_GRAVITY:
1654 isFloat = true;
1655 expectSize = 1;
1656 break;
1657 case AINFO_DOCK_STATE:
1658 case AINFO_HIGH_PERFORMANCE_MODE:
1659 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1660 isFloat = false;
1661 expectSize = 1;
1662 break;
1663 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001664 // CUSTOM events must only contain float data; it may have variable size
1665 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1666 ints.size() ||
1667 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1668 handle < 0) {
1669 return BAD_VALUE;
1670 }
1671 isFloat = true;
1672 isCustom = true;
1673 expectSize = floats.size();
1674 break;
1675 }
1676
1677 if (!isCustom && handle != -1) {
1678 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001679 }
1680
1681 // three events: first one is begin tag, last one is end tag, the one in the middle
1682 // is the payload.
1683 sensors_event_t event[3];
1684 int64_t timestamp = elapsedRealtimeNano();
1685 for (sensors_event_t* i = event; i < event + 3; i++) {
1686 *i = (sensors_event_t) {
1687 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001688 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001689 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1690 .timestamp = timestamp++,
1691 .additional_info = (additional_info_event_t) {
1692 .serial = 0
1693 }
1694 };
1695 }
1696
1697 event[0].additional_info.type = AINFO_BEGIN;
1698 event[1].additional_info.type = type;
1699 event[2].additional_info.type = AINFO_END;
1700
1701 if (isFloat) {
1702 if (floats.size() != expectSize) {
1703 return BAD_VALUE;
1704 }
1705 for (size_t i = 0; i < expectSize; ++i) {
1706 event[1].additional_info.data_float[i] = floats[i];
1707 }
1708 } else {
1709 if (ints.size() != expectSize) {
1710 return BAD_VALUE;
1711 }
1712 for (size_t i = 0; i < expectSize; ++i) {
1713 event[1].additional_info.data_int32[i] = ints[i];
1714 }
1715 }
1716
1717 SensorDevice& dev(SensorDevice::getInstance());
1718 for (sensors_event_t* i = event; i < event + 3; i++) {
1719 int ret = dev.injectSensorData(i);
1720 if (ret != NO_ERROR) {
1721 return ret;
1722 }
1723 }
1724 return NO_ERROR;
1725}
1726
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001727status_t SensorService::resetToNormalMode() {
1728 Mutex::Autolock _l(mLock);
1729 return resetToNormalModeLocked();
1730}
1731
1732status_t SensorService::resetToNormalModeLocked() {
1733 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001734 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301735 if (err == NO_ERROR) {
1736 mCurrentOperatingMode = NORMAL;
1737 dev.enableAllSensors();
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001738 checkAndReportProxStateChangeLocked();
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301739 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001740 return err;
1741}
1742
Peng Xu47e96012016-03-28 17:55:56 -07001743void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001744 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001745 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001746 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001747 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001748 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001749 int handle = mActiveSensors.keyAt(i);
1750 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001751 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001752 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001753 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001754 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001755 } else {
1756 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001757 }
Brian Duddie7be85572021-12-21 10:44:55 -08001758 if (c->removeSensor(handle)) {
1759 BatteryService::disableSensor(c->getUid(), handle);
1760 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001761 }
1762 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001763 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001764 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001765 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001766 c, i, handle);
1767
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001768 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001769 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001770 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001771 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001772 delete rec;
1773 size--;
1774 } else {
1775 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001776 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001777 }
Aravind Akella8a969552014-09-28 17:52:41 -07001778 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001779 mConnectionHolder.removeEventConnection(connection);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001780 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001781 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001782 }
Peng Xu4f707f82016-09-26 11:28:32 -07001783
1784 SensorDevice& dev(SensorDevice::getInstance());
1785 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001786}
1787
Peng Xue36e3472016-11-03 11:57:10 -07001788void SensorService::cleanupConnection(SensorDirectConnection* c) {
1789 Mutex::Autolock _l(mLock);
1790
1791 SensorDevice& dev(SensorDevice::getInstance());
1792 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001793 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001794}
1795
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001796void SensorService::checkAndReportProxStateChangeLocked() {
1797 if (mProxSensorHandles.empty()) return;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001798
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001799 SensorDevice& dev(SensorDevice::getInstance());
1800 bool isActive = false;
1801 for (auto& sensor : mProxSensorHandles) {
1802 if (dev.isSensorActive(sensor)) {
1803 isActive = true;
1804 break;
1805 }
1806 }
1807 if (isActive != mLastReportedProxIsActive) {
1808 notifyProximityStateLocked(isActive, mProximityActiveListeners);
1809 mLastReportedProxIsActive = isActive;
Andrew Lehmer3a602572021-03-25 15:19:56 -07001810 }
1811}
1812
1813void SensorService::notifyProximityStateLocked(
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001814 const bool isActive,
Santos Cordon7ea287a2021-06-14 13:45:29 +01001815 const std::vector<sp<ProximityActiveListener>>& listeners) {
Santos Cordon7ea287a2021-06-14 13:45:29 +01001816 const uint64_t mySeq = ++curProxCallbackSeq;
1817 std::thread t([isActive, mySeq, listenersCopy = listeners]() {
1818 while (completedCallbackSeq.load() != mySeq - 1)
1819 std::this_thread::sleep_for(1ms);
1820 for (auto& listener : listenersCopy)
1821 listener->onProximityActive(isActive);
1822 completedCallbackSeq++;
1823 });
1824 t.detach();
Andrew Lehmer3a602572021-03-25 15:19:56 -07001825}
1826
1827status_t SensorService::addProximityActiveListener(const sp<ProximityActiveListener>& callback) {
1828 if (callback == nullptr) {
1829 return BAD_VALUE;
1830 }
1831
1832 Mutex::Autolock _l(mLock);
1833
1834 // Check if the callback was already added.
1835 for (const auto& cb : mProximityActiveListeners) {
1836 if (cb == callback) {
1837 return ALREADY_EXISTS;
1838 }
1839 }
1840
1841 mProximityActiveListeners.push_back(callback);
1842 std::vector<sp<ProximityActiveListener>> listener(1, callback);
Chris Kuiperdf11ff22021-10-12 16:30:01 -07001843 notifyProximityStateLocked(mLastReportedProxIsActive, listener);
Andrew Lehmer3a602572021-03-25 15:19:56 -07001844 return OK;
1845}
1846
1847status_t SensorService::removeProximityActiveListener(
1848 const sp<ProximityActiveListener>& callback) {
1849 if (callback == nullptr) {
1850 return BAD_VALUE;
1851 }
1852
1853 Mutex::Autolock _l(mLock);
1854
1855 for (auto iter = mProximityActiveListeners.begin();
1856 iter != mProximityActiveListeners.end();
1857 ++iter) {
1858 if (*iter == callback) {
1859 mProximityActiveListeners.erase(iter);
1860 return OK;
1861 }
1862 }
1863 return NAME_NOT_FOUND;
1864}
1865
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001866std::shared_ptr<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001867 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001868}
1869
Mathias Agopianfc328812010-07-14 23:41:37 -07001870status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001871 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001872 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001873 if (mInitCheck != NO_ERROR)
1874 return mInitCheck;
1875
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01001876 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001877 if (sensor == nullptr ||
1878 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001879 return BAD_VALUE;
1880 }
1881
Brian Duddie967ce172019-06-10 11:08:27 -07001882 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001883 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001884 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001885 return INVALID_OPERATION;
1886 }
1887
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001888 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001889 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001890 rec = new SensorRecord(connection);
1891 mActiveSensors.add(handle, rec);
1892 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001893 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001894 }
Brian Stack26029ee2019-04-22 17:25:49 -07001895
1896 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1897 // the recent event as stale to ensure that the previous event is not sent to a client. This
1898 // ensures on-change events that were generated during a previous sensor activation are not
1899 // erroneously sent to newly connected clients, especially if a second client registers for
1900 // an on-change sensor before the first client receives the updated event. Once an updated
1901 // event is received, the recent events will be marked as current, and any new clients will
1902 // immediately receive the most recent event.
1903 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1904 auto logger = mRecentEvent.find(handle);
1905 if (logger != mRecentEvent.end()) {
1906 logger->second->setLastEventStale();
1907 }
1908 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001909 } else {
1910 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001911 // this sensor is already activated, but we are adding a connection that uses it.
1912 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001913 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001914 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001915 // NOTE: The wake_up flag of this event may get set to
1916 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001917
1918 auto logger = mRecentEvent.find(handle);
1919 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001920 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001921 // Verify that the last sensor event was generated from the current activation
1922 // of the sensor. If not, it is possible for an on-change sensor to receive a
1923 // sensor event that is stale if two clients re-activate the sensor
1924 // simultaneously.
1925 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001926 event.sensor = handle;
1927 if (event.version == sizeof(sensors_event_t)) {
1928 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1929 setWakeLockAcquiredLocked(true);
1930 }
Yi Kong8f313e32018-07-17 14:13:29 -07001931 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001932 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001933 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001934 }
1935 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001936 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001937 }
1938 }
1939 }
1940 }
1941
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001942 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001943 BatteryService::enableSensor(connection->getUid(), handle);
1944 // the sensor was added (which means it wasn't already there)
1945 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001946 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001947 } else {
1948 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1949 handle, connection.get());
1950 }
1951
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301952 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001953 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301954 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1955 samplingPeriodNs = maxDelayNs;
1956 }
1957
Aravind Akella724d91d2013-06-27 12:04:23 -07001958 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1959 if (samplingPeriodNs < minDelayNs) {
1960 samplingPeriodNs = minDelayNs;
1961 }
1962
Aravind Akella6c2664a2014-08-13 12:24:50 -07001963 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1964 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001965 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1966
Aravind Akella4949c502015-02-11 15:54:35 -08001967 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001968 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001969
Peng Xu20483c42015-10-26 15:14:43 -07001970 // Call flush() before calling activate() on the sensor. Wait for a first
1971 // flush complete event before sending events on this connection. Ignore
1972 // one-shot sensors which don't support flush(). Ignore on-change sensors
1973 // to maintain the on-change logic (any on-change events except the initial
1974 // one should be trigger by a change in value). Also if this sensor isn't
1975 // already active, don't call flush().
1976 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001977 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001978 rec->getNumConnections() > 1) {
1979 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001980 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001981 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001982 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001983 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001984 } else {
1985 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001986 }
1987 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001988
1989 if (err == NO_ERROR) {
1990 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1991 err = sensor->activate(connection.get(), true);
1992 }
1993
Aravind Akella8a969552014-09-28 17:52:41 -07001994 if (err == NO_ERROR) {
1995 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001996
Brian Stack240d1d62019-05-17 09:49:39 -07001997 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1998 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001999 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
2000 }
2001
Peng Xu51224682017-03-10 16:57:27 -08002002 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2003 SensorRegistrationInfo(handle, connection->getPackageName(),
2004 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07002005 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07002006 }
2007
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002008 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07002009 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002010 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002011 }
2012 return err;
2013}
2014
Peng Xu47e96012016-03-28 17:55:56 -07002015status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002016 if (mInitCheck != NO_ERROR)
2017 return mInitCheck;
2018
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002019 Mutex::Autolock _l(mLock);
2020 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002021 if (err == NO_ERROR) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002022 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002023 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07002024
2025 }
2026 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08002027 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
2028 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07002029 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002030 }
2031 return err;
2032}
2033
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002034status_t SensorService::cleanupWithoutDisable(
2035 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002036 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07002037 return cleanupWithoutDisableLocked(connection, handle);
2038}
2039
2040status_t SensorService::cleanupWithoutDisableLocked(
2041 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07002042 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002043 if (rec) {
2044 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07002045 if (connection->removeSensor(handle)) {
2046 BatteryService::disableSensor(connection->getUid(), handle);
2047 }
Mathias Agopianfc328812010-07-14 23:41:37 -07002048 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07002049 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07002050 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07002051 }
2052 // see if this sensor becomes inactive
2053 if (rec->removeConnection(connection)) {
2054 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002055 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07002056 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07002057 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002058 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002059 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07002060 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07002061}
2062
Mathias Agopian7c1c5312010-07-21 15:59:50 -07002063status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07002064 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07002065 if (mInitCheck != NO_ERROR)
2066 return mInitCheck;
2067
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002068 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002069 if (sensor == nullptr ||
2070 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00002071 return BAD_VALUE;
2072 }
2073
Mathias Agopian1cd70002010-07-21 15:59:50 -07002074 if (ns < 0)
2075 return BAD_VALUE;
2076
Mathias Agopian62569ec2011-11-07 21:21:47 -08002077 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
2078 if (ns < minDelayNs) {
2079 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07002080 }
2081
Mathias Agopianf001c922010-11-11 17:58:51 -08002082 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07002083}
2084
Svetoslavb412f6e2015-04-29 16:50:41 -07002085status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
2086 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00002087 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002088 SensorDevice& dev(SensorDevice::getInstance());
2089 const int halVersion = dev.getHalDeviceVersion();
2090 status_t err(NO_ERROR);
2091 Mutex::Autolock _l(mLock);
2092 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07002093 for (int handle : connection->getActiveSensorHandles()) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +01002094 std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -07002095 if (sensor == nullptr) {
2096 continue;
2097 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002098 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
2099 ALOGE("flush called on a one-shot sensor");
2100 err = INVALID_OPERATION;
2101 continue;
2102 }
Aravind Akella8493b792014-09-08 15:45:47 -07002103 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002104 // For older devices just increment pending flush count which will send a trivial
2105 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07002106 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
2107 ALOGE("flush called on an inaccessible sensor");
2108 err = INVALID_OPERATION;
2109 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002110 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002111 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
2112 err = INVALID_OPERATION;
2113 continue;
2114 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002115 status_t err_flush = sensor->flush(connection.get(), handle);
2116 if (err_flush == NO_ERROR) {
2117 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07002118 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07002119 }
2120 err = (err_flush != NO_ERROR) ? err_flush : err;
2121 }
Aravind Akella70018042014-04-07 22:52:37 +00002122 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07002123 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07002124}
Aravind Akella70018042014-04-07 22:52:37 +00002125
Svetoslavb412f6e2015-04-29 16:50:41 -07002126bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
2127 const String16& opPackageName) {
Brian Duddie4a4d0462022-05-09 16:49:49 -07002128 // Special case for Head Tracker sensor type: currently restricted to system usage only, unless
2129 // the restriction is specially lifted for testing
2130 if (sensor.getType() == SENSOR_TYPE_HEAD_TRACKER &&
2131 !isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
2132 if (!mHtRestricted) {
2133 ALOGI("Permitting access to HT sensor type outside system (%s)",
2134 String8(opPackageName).string());
2135 } else {
2136 ALOGW("%s %s a sensor (%s) as a non-system client", String8(opPackageName).string(),
2137 operation, sensor.getName().string());
2138 return false;
2139 }
2140 }
2141
Brian Stack793f4642019-04-18 17:21:34 -07002142 // Check if a permission is required for this sensor
2143 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00002144 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07002145 }
2146
Brian Stack793f4642019-04-18 17:21:34 -07002147 const int32_t opCode = sensor.getRequiredAppOp();
Brian Duddie457e6392020-06-19 11:38:29 -07002148 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07002149
Brian Stack793f4642019-04-18 17:21:34 -07002150 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07002151 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
2152 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
2153 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
2154 // Allow access to step sensors if the application targets pre-Q, which is before the
2155 // requirement to hold the AR permission to access Step Counter and Step Detector events
2156 // was introduced.
2157 canAccess = true;
2158 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07002159 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002160 if (opCode >= 0) {
2161 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
2162 IPCThreadState::self()->getCallingUid(), opPackageName);
2163 canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
2164 } else {
Brian Stack793f4642019-04-18 17:21:34 -07002165 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07002166 }
Brian Stack793f4642019-04-18 17:21:34 -07002167 }
2168
Arthur Ishiguro883748c2020-10-28 13:18:02 -07002169 if (!canAccess) {
Brian Duddie457e6392020-06-19 11:38:29 -07002170 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
2171 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07002172 }
2173
2174 return canAccess;
2175}
2176
2177bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07002178 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07002179 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07002180
2181 // Runtime permissions can't use the cache as they may change.
2182 if (sensor.isRequiredPermissionRuntime()) {
2183 hasPermission = checkPermission(String16(requiredPermission),
matthuang65794462022-03-24 16:02:57 +08002184 IPCThreadState::self()->getCallingPid(),
2185 IPCThreadState::self()->getCallingUid(),
2186 /*logPermissionFailure=*/ false);
Aravind Akella70018042014-04-07 22:52:37 +00002187 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07002188 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
2189 }
Brian Stack793f4642019-04-18 17:21:34 -07002190 return hasPermission;
2191}
Svetoslavb412f6e2015-04-29 16:50:41 -07002192
Brian Stack793f4642019-04-18 17:21:34 -07002193int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Anthony Stange07eb4212020-08-28 14:50:28 -04002194 // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
2195 // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
2196 // give it elevated privileges.
2197 if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
2198 return -1;
2199 }
2200
Brian Stack793f4642019-04-18 17:21:34 -07002201 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2202 int targetSdkVersion = -1;
2203 auto entry = sPackageTargetVersion.find(opPackageName);
2204 if (entry != sPackageTargetVersion.end()) {
2205 targetSdkVersion = entry->second;
2206 } else {
2207 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2208 if (binder != nullptr) {
2209 sp<content::pm::IPackageManagerNative> packageManager =
2210 interface_cast<content::pm::IPackageManagerNative>(binder);
2211 if (packageManager != nullptr) {
2212 binder::Status status = packageManager->getTargetSdkVersionForPackage(
2213 opPackageName, &targetSdkVersion);
2214 if (!status.isOk()) {
2215 targetSdkVersion = -1;
2216 }
2217 }
Svetoslavb412f6e2015-04-29 16:50:41 -07002218 }
Brian Stack793f4642019-04-18 17:21:34 -07002219 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07002220 }
Brian Stack793f4642019-04-18 17:21:34 -07002221 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00002222}
2223
Brian Duddie0d4ac562022-05-23 17:47:50 -07002224void SensorService::resetTargetSdkVersionCache(const String16& opPackageName) {
2225 Mutex::Autolock packageLock(sPackageTargetVersionLock);
2226 auto iter = sPackageTargetVersion.find(opPackageName);
2227 if (iter != sPackageTargetVersion.end()) {
2228 sPackageTargetVersion.erase(iter);
2229 }
2230}
2231
Aravind Akella9a844cf2014-02-11 18:58:52 -08002232void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07002233 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
2234 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08002235}
2236
Brian Duddie967ce172019-06-10 11:08:27 -07002237void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08002238 if (!mWakeLockAcquired) {
2239 return;
2240 }
2241 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07002242 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
2243 if (connection->needsWakeLock()) {
2244 releaseLock = false;
2245 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08002246 }
2247 }
2248 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07002249 setWakeLockAcquiredLocked(false);
2250 }
2251}
2252
2253void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
2254 Mutex::Autolock _l(mLock);
2255 connection->writeToSocketFromCache();
2256 if (connection->needsWakeLock()) {
2257 setWakeLockAcquiredLocked(true);
2258 }
2259}
2260
Aravind Akella4949c502015-02-11 15:54:35 -08002261bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07002262 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08002263}
2264
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002265bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08002266 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07002267 String8 package(opPackageName);
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002268 return !isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07002269 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07002270 return false;
Peng Xue36e3472016-11-03 11:57:10 -07002271}
2272
Svet Ganove752a5c2018-01-15 17:14:20 -08002273void SensorService::UidPolicy::registerSelf() {
2274 ActivityManager am;
2275 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
2276 | ActivityManager::UID_OBSERVER_IDLE
2277 | ActivityManager::UID_OBSERVER_ACTIVE,
2278 ActivityManager::PROCESS_STATE_UNKNOWN,
2279 String16("android"));
2280}
2281
2282void SensorService::UidPolicy::unregisterSelf() {
2283 ActivityManager am;
2284 am.unregisterUidObserver(this);
2285}
2286
2287void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
2288 onUidIdle(uid, disabled);
2289}
2290
2291void SensorService::UidPolicy::onUidActive(uid_t uid) {
2292 {
2293 Mutex::Autolock _l(mUidLock);
2294 mActiveUids.insert(uid);
2295 }
2296 sp<SensorService> service = mService.promote();
2297 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002298 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002299 }
2300}
2301
2302void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
2303 bool deleted = false;
2304 {
2305 Mutex::Autolock _l(mUidLock);
2306 if (mActiveUids.erase(uid) > 0) {
2307 deleted = true;
2308 }
2309 }
2310 if (deleted) {
2311 sp<SensorService> service = mService.promote();
2312 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002313 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002314 }
2315 }
2316}
2317
2318void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
2319 updateOverrideUid(uid, active, true);
2320}
2321
2322void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
2323 updateOverrideUid(uid, false, false);
2324}
2325
2326void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
2327 bool wasActive = false;
2328 bool isActive = false;
2329 {
2330 Mutex::Autolock _l(mUidLock);
2331 wasActive = isUidActiveLocked(uid);
2332 mOverrideUids.erase(uid);
2333 if (insert) {
2334 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2335 }
2336 isActive = isUidActiveLocked(uid);
2337 }
2338 if (wasActive != isActive) {
2339 sp<SensorService> service = mService.promote();
2340 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002341 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08002342 }
2343 }
2344}
2345
2346bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2347 // Non-app UIDs are considered always active
2348 if (uid < FIRST_APPLICATION_UID) {
2349 return true;
2350 }
2351 Mutex::Autolock _l(mUidLock);
2352 return isUidActiveLocked(uid);
2353}
2354
2355bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2356 // Non-app UIDs are considered always active
2357 if (uid < FIRST_APPLICATION_UID) {
2358 return true;
2359 }
2360 auto it = mOverrideUids.find(uid);
2361 if (it != mOverrideUids.end()) {
2362 return it->second;
2363 }
2364 return mActiveUids.find(uid) != mActiveUids.end();
2365}
2366
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002367bool SensorService::isUidActive(uid_t uid) {
2368 return mUidPolicy->isUidActive(uid);
2369}
2370
Anh Phamaf91a912021-02-10 14:10:53 +01002371bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
2372 int targetSdk = getTargetSdkVersion(opPackageName);
Anh Phama5538232021-06-23 08:41:11 +02002373 bool hasSamplingRatePermission = checkPermission(sAccessHighSensorSamplingRatePermission,
2374 IPCThreadState::self()->getCallingPid(),
matthuang65794462022-03-24 16:02:57 +08002375 IPCThreadState::self()->getCallingUid(),
2376 /*logPermissionFailure=*/ false);
Anh Phamaf91a912021-02-10 14:10:53 +01002377 if (targetSdk < __ANDROID_API_S__ ||
2378 (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
2379 return false;
2380 }
2381 return true;
2382}
2383
Anh Pham3dae77f2021-06-11 16:24:37 +02002384/**
2385 * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS
2386 * permission.
2387 *
2388 * This needs to be kept in sync with the list defined on the Java side
2389 * in frameworks/base/core/java/android/hardware/SystemSensorManager.java
2390 */
Anh Phamaf91a912021-02-10 14:10:53 +01002391bool SensorService::isSensorInCappedSet(int sensorType) {
2392 return (sensorType == SENSOR_TYPE_ACCELEROMETER
2393 || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
2394 || sensorType == SENSOR_TYPE_GYROSCOPE
2395 || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
2396 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
2397 || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
2398}
2399
2400status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
2401 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002402 if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
2403 return OK;
2404 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002405 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002406 if (shouldCapBasedOnPermission) {
2407 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2408 if (isPackageDebuggable(opPackageName)) {
2409 return PERMISSION_DENIED;
2410 }
2411 return OK;
2412 }
Evan Severson4c197852022-01-27 10:44:27 -08002413 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002414 *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
2415 return OK;
2416 }
Anh Phamaf91a912021-02-10 14:10:53 +01002417 return OK;
2418}
2419
2420status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
2421 const String16& opPackageName) {
Anh Phamaf91a912021-02-10 14:10:53 +01002422 if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
2423 return OK;
2424 }
Arthur Ishiguro8a628522021-09-22 14:10:16 -07002425 bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
Anh Phamaf91a912021-02-10 14:10:53 +01002426 if (shouldCapBasedOnPermission) {
2427 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2428 if (isPackageDebuggable(opPackageName)) {
2429 return PERMISSION_DENIED;
2430 }
2431 return OK;
2432 }
Evan Severson4c197852022-01-27 10:44:27 -08002433 if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Anh Pham5198c992021-02-10 14:15:30 +01002434 *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
2435 return OK;
2436 }
Anh Phamaf91a912021-02-10 14:10:53 +01002437 return OK;
2438}
2439
Michael Groover5e1f60b2018-12-04 22:34:29 -08002440void SensorService::SensorPrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002441 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002442 SensorPrivacyManager spm;
2443 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2444 spm.addSensorPrivacyListener(this);
2445}
2446
2447void SensorService::SensorPrivacyPolicy::unregisterSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002448 AutoCallerClear acc;
Michael Groover5e1f60b2018-12-04 22:34:29 -08002449 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002450 spm.removeSensorPrivacyListener(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -08002451}
2452
2453bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2454 return mSensorPrivacyEnabled;
2455}
2456
Evan Severson4c197852022-01-27 10:44:27 -08002457binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2458 int sensor __unused, bool enabled) {
Michael Groover5e1f60b2018-12-04 22:34:29 -08002459 mSensorPrivacyEnabled = enabled;
2460 sp<SensorService> service = mService.promote();
Anh Pham5198c992021-02-10 14:15:30 +01002461
Michael Groover5e1f60b2018-12-04 22:34:29 -08002462 if (service != nullptr) {
Evan Severson4c197852022-01-27 10:44:27 -08002463 if (enabled) {
2464 service->disableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002465 } else {
Evan Severson4c197852022-01-27 10:44:27 -08002466 service->enableAllSensors();
Michael Groover5e1f60b2018-12-04 22:34:29 -08002467 }
2468 }
2469 return binder::Status::ok();
2470}
Brian Duddie967ce172019-06-10 11:08:27 -07002471
Evan Severson4c197852022-01-27 10:44:27 -08002472void SensorService::MicrophonePrivacyPolicy::registerSelf() {
Anh Phamb04658b2021-03-22 18:17:17 +01002473 AutoCallerClear acc;
Anh Pham5198c992021-02-10 14:15:30 +01002474 SensorPrivacyManager spm;
Evan Severson4c197852022-01-27 10:44:27 -08002475 mSensorPrivacyEnabled =
2476 spm.isToggleSensorPrivacyEnabled(
2477 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
2478 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE)
2479 || spm.isToggleSensorPrivacyEnabled(
2480 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE,
2481 SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE);
2482 spm.addToggleSensorPrivacyListener(this);
Anh Pham5198c992021-02-10 14:15:30 +01002483}
2484
Evan Severson4c197852022-01-27 10:44:27 -08002485void SensorService::MicrophonePrivacyPolicy::unregisterSelf() {
2486 AutoCallerClear acc;
2487 SensorPrivacyManager spm;
2488 spm.removeToggleSensorPrivacyListener(this);
2489}
2490
2491binder::Status SensorService::MicrophonePrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
2492 int sensor, bool enabled) {
2493 if (sensor != SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE) {
2494 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002495 }
Evan Severson4c197852022-01-27 10:44:27 -08002496 mSensorPrivacyEnabled = enabled;
2497 sp<SensorService> service = mService.promote();
2498
2499 if (service != nullptr) {
2500 if (enabled) {
2501 service->capRates();
2502 } else {
2503 service->uncapRates();
2504 }
2505 }
2506 return binder::Status::ok();
Anh Pham5198c992021-02-10 14:15:30 +01002507}
2508
Brian Duddie967ce172019-06-10 11:08:27 -07002509SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2510 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2511 : mConnectionHolder(holder), mAutolock(mutex) {}
2512
2513template<typename ConnectionType>
2514const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2515 const SortedVector<wp<ConnectionType>>& connectionList,
2516 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2517 referenceHolder->emplace_back();
2518 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2519 for (const wp<ConnectionType>& weakConnection : connectionList){
2520 sp<ConnectionType> connection = weakConnection.promote();
2521 if (connection != nullptr) {
2522 connections.push_back(std::move(connection));
2523 }
2524 }
2525 return connections;
2526}
2527
2528const std::vector<sp<SensorService::SensorEventConnection>>&
2529 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2530 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2531 &mReferencedActiveConnections);
2532}
2533
2534const std::vector<sp<SensorService::SensorDirectConnection>>&
2535 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2536 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2537 &mReferencedDirectConnections);
2538}
2539
2540void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2541 const sp<SensorService::SensorEventConnection>& connection) {
2542 if (mActiveConnections.indexOf(connection) < 0) {
2543 mActiveConnections.add(connection);
2544 }
2545}
2546
2547void SensorService::SensorConnectionHolder::removeEventConnection(
2548 const wp<SensorService::SensorEventConnection>& connection) {
2549 mActiveConnections.remove(connection);
2550}
2551
2552void SensorService::SensorConnectionHolder::addDirectConnection(
2553 const sp<SensorService::SensorDirectConnection>& connection) {
2554 mDirectConnections.add(connection);
2555}
2556
2557void SensorService::SensorConnectionHolder::removeDirectConnection(
2558 const wp<SensorService::SensorDirectConnection>& connection) {
2559 mDirectConnections.remove(connection);
2560}
2561
2562SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2563 return ConnectionSafeAutolock(*this, mutex);
2564}
2565
Anh Phamaf91a912021-02-10 14:10:53 +01002566bool SensorService::isPackageDebuggable(const String16& opPackageName) {
2567 bool debugMode = false;
2568 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
2569 if (binder != nullptr) {
2570 sp<content::pm::IPackageManagerNative> packageManager =
2571 interface_cast<content::pm::IPackageManagerNative>(binder);
2572 if (packageManager != nullptr) {
2573 binder::Status status = packageManager->isPackageDebuggable(
2574 opPackageName, &debugMode);
2575 }
2576 }
2577 return debugMode;
2578}
Brian Duddie967ce172019-06-10 11:08:27 -07002579} // namespace android