blob: 118d9281fcaf3b7e12fc025d527f4b1e69e29980 [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 */
16
17#ifndef ANDROID_SENSOR_SERVICE_H
18#define ANDROID_SENSOR_SERVICE_H
19
Brian Duddie967ce172019-06-10 11:08:27 -070020#include <android-base/macros.h>
Brian Stack793f4642019-04-18 17:21:34 -070021#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070022#include <binder/BinderService.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080023#include <binder/IUidObserver.h>
Peng Xu755c4512016-04-07 23:15:14 -070024#include <cutils/compiler.h>
Tanmay Patild33a1822019-04-11 18:38:55 -070025#include <cutils/multiuser.h>
Eric Laurente3f27df2022-01-05 19:20:32 +010026#include <private/android_filesystem_config.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080027#include <sensor/ISensorEventConnection.h>
Rocky Fangbeb0dff2023-12-15 01:59:46 +000028#include <sensor/ISensorServer.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080029#include <sensor/Sensor.h>
Rocky Fangbeb0dff2023-12-15 01:59:46 +000030#include <stdint.h>
31#include <sys/types.h>
Peng Xu755c4512016-04-07 23:15:14 -070032#include <utils/AndroidThreads.h>
33#include <utils/KeyedVector.h>
34#include <utils/Looper.h>
35#include <utils/SortedVector.h>
36#include <utils/String8.h>
37#include <utils/Vector.h>
38#include <utils/threads.h>
39
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +020040#include <condition_variable>
41#include <mutex>
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +020042#include <queue>
Peng Xu6a2d3a02015-12-21 12:00:23 -080043#include <unordered_map>
Peng Xu755c4512016-04-07 23:15:14 -070044#include <unordered_set>
Brian Duddie967ce172019-06-10 11:08:27 -070045#include <vector>
Mathias Agopianf001c922010-11-11 17:58:51 -080046
Rocky Fangbeb0dff2023-12-15 01:59:46 +000047#include "RecentEventLogger.h"
48#include "SensorList.h"
49#include "android/hardware/BnSensorPrivacyListener.h"
50
Bernhard Rosenkränzer72952ef2014-11-17 21:03:39 +010051#if __clang__
Peng Xueb4d6282015-12-10 18:02:41 -080052// Clang warns about SensorEventConnection::dump hiding BBinder::dump. The cause isn't fixable
53// without changing the API, so let's tell clang this is indeed intentional.
Bernhard Rosenkränzer72952ef2014-11-17 21:03:39 +010054#pragma clang diagnostic ignored "-Woverloaded-virtual"
55#endif
56
Mathias Agopianfc328812010-07-14 23:41:37 -070057// ---------------------------------------------------------------------------
Peng Xuf66684a2015-07-23 11:41:53 -070058#define IGNORE_HARDWARE_FUSION false
Rocky Fangbeb0dff2023-12-15 01:59:46 +000059#define DEBUG_CONNECTIONS false
Aravind Akella56ae4262014-07-10 16:01:10 -070060// Max size is 100 KB which is enough to accept a batch of about 1000 events.
Chih-Hung Hsieha389c7a2016-05-20 11:40:04 -070061#define MAX_SOCKET_BUFFER_SIZE_BATCHED (100 * 1024)
Aravind Akella56ae4262014-07-10 16:01:10 -070062// For older HALs which don't support batching, use a smaller socket buffer size.
Chih-Hung Hsieha389c7a2016-05-20 11:40:04 -070063#define SOCKET_BUFFER_SIZE_NON_BATCHED (4 * 1024)
Mathias Agopiana1b7db92011-05-27 16:23:58 -070064
Chris Kuiper1d1d5122023-06-20 16:43:37 -070065#define SENSOR_REGISTRATIONS_BUF_SIZE 500
Aravind Akella444f2672015-05-07 12:40:52 -070066
Anh Phamaf91a912021-02-10 14:10:53 +010067// Apps that targets S+ and do not have HIGH_SAMPLING_RATE_SENSORS permission will be capped
Anh Pham5198c992021-02-10 14:15:30 +010068// at 200 Hz. The cap also applies to all requests when the mic toggle is flipped to on, regardless
69// of their target SDKs and permission.
Anh Phamaf91a912021-02-10 14:10:53 +010070// Capped sampling periods for apps that have non-direct sensor connections.
71#define SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS (5 * 1000 * 1000)
72// Capped sampling rate level for apps that have direct sensor connections.
73// The enum SENSOR_DIRECT_RATE_NORMAL corresponds to a rate value of at most 110 Hz.
74#define SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL SENSOR_DIRECT_RATE_NORMAL
75
Mathias Agopianfc328812010-07-14 23:41:37 -070076namespace android {
77// ---------------------------------------------------------------------------
Peng Xu755c4512016-04-07 23:15:14 -070078class SensorInterface;
Mathias Agopianfc328812010-07-14 23:41:37 -070079
80class SensorService :
81 public BinderService<SensorService>,
82 public BnSensorServer,
83 protected Thread
84{
Peng Xueb4d6282015-12-10 18:02:41 -080085 // nested class/struct for internal use
86 class SensorEventConnection;
Peng Xue36e3472016-11-03 11:57:10 -070087 class SensorDirectConnection;
Peng Xueb4d6282015-12-10 18:02:41 -080088
89public:
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070090 enum UidState {
91 UID_STATE_ACTIVE = 0,
92 UID_STATE_IDLE,
93 };
94
Arthur Ishiguro5e3eaa82021-11-11 18:05:56 +000095 enum Mode {
96 // The regular operating mode where any application can register/unregister/call flush on
97 // sensors.
98 NORMAL = 0,
99 // This mode is only used for testing purposes. Not all HALs support this mode. In this mode,
100 // the HAL ignores the sensor data provided by physical sensors and accepts the data that is
101 // injected from the SensorService as if it were the real sensor data. This mode is primarily
102 // used for testing various algorithms like vendor provided SensorFusion, Step Counter and
103 // Step Detector etc. Typically in this mode, there will be a client (a
104 // SensorEventConnection) which will be injecting sensor data into the HAL. Normal apps can
105 // unregister and register for any sensor that supports injection. Registering to sensors
Anthony Stange9bb16702023-01-03 22:42:31 +0000106 // that do not support injection will give an error.
Arthur Ishiguro5e3eaa82021-11-11 18:05:56 +0000107 DATA_INJECTION = 1,
108 // This mode is used only for testing sensors. Each sensor can be tested in isolation with
109 // the required sampling_rate and maxReportLatency parameters without having to think about
110 // the data rates requested by other applications. End user devices are always expected to be
111 // in NORMAL mode. When this mode is first activated, all active sensors from all connections
112 // are disabled. Calling flush() will return an error. In this mode, only the requests from
113 // selected apps whose package names are allowlisted are allowed (typically CTS apps). Only
114 // these apps can register/unregister/call flush() on sensors. If SensorService switches to
115 // NORMAL mode again, all sensors that were previously registered to are activated with the
116 // corresponding parameters if the application hasn't unregistered for sensors in the mean
117 // time. NOTE: Non allowlisted app whose sensors were previously deactivated may still
118 // receive events if a allowlisted app requests data from the same sensor.
Anthony Stange9bb16702023-01-03 22:42:31 +0000119 RESTRICTED = 2,
120 // Mostly equivalent to DATA_INJECTION with the difference being that the injected data is
121 // delivered to all requesting apps rather than just the package allowed to inject data.
122 // This mode is only allowed to be used on development builds.
123 REPLAY_DATA_INJECTION = 3,
Mark Wheatley8f285d92023-07-07 20:07:18 +0000124 // Like REPLAY_DATA_INJECTION but injected data is not sent into the HAL. It is stored in a
125 // buffer in SensorDevice and played back to SensorService when SensorDevice::poll() is
126 // called. This is useful for playing back sensor data on the platform without relying on
127 // the HAL to support data injection.
128 HAL_BYPASS_REPLAY_DATA_INJECTION = 4,
Arthur Ishiguro5e3eaa82021-11-11 18:05:56 +0000129
130 // State Transitions supported.
Anthony Stange9bb16702023-01-03 22:42:31 +0000131 // RESTRICTED <--- NORMAL ---> DATA_INJECTION/REPLAY_DATA_INJECTION
Arthur Ishiguro5e3eaa82021-11-11 18:05:56 +0000132 // ---> <---
133
134 // Shell commands to switch modes in SensorService.
135 // 1) Put SensorService in RESTRICTED mode with packageName .cts. If it is already in
136 // restricted mode it is treated as a NO_OP (and packageName is NOT changed).
137 //
138 // $ adb shell dumpsys sensorservice restrict .cts.
139 //
140 // 2) Put SensorService in DATA_INJECTION mode with packageName .xts. If it is already in
141 // data_injection mode it is treated as a NO_OP (and packageName is NOT changed).
142 //
143 // $ adb shell dumpsys sensorservice data_injection .xts.
144 //
145 // 3) Reset sensorservice back to NORMAL mode.
146 // $ adb shell dumpsys sensorservice enable
147 };
148
Andrew Lehmer3a602572021-03-25 15:19:56 -0700149 class ProximityActiveListener : public virtual RefBase {
150 public:
151 // Note that the callback is invoked from an async thread and can interact with the
152 // SensorService directly.
153 virtual void onProximityActive(bool isActive) = 0;
154 };
155
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100156 class RuntimeSensorCallback : public virtual RefBase {
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200157 public:
158 // Note that the callback is invoked from an async thread and can interact with the
159 // SensorService directly.
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100160 virtual status_t onConfigurationChanged(int handle, bool enabled,
161 int64_t samplingPeriodNanos,
162 int64_t batchReportLatencyNanos) = 0;
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100163 virtual int onDirectChannelCreated(int fd) = 0;
164 virtual void onDirectChannelDestroyed(int channelHandle) = 0;
165 virtual int onDirectChannelConfigured(int channelHandle, int sensorHandle,
166 int rateLevel) = 0;
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200167 };
168
Andrew Lehmer3a602572021-03-25 15:19:56 -0700169 static char const* getServiceName() ANDROID_API { return "sensorservice"; }
170 SensorService() ANDROID_API;
171
Peng Xueb4d6282015-12-10 18:02:41 -0800172 void cleanupConnection(SensorEventConnection* connection);
Peng Xue36e3472016-11-03 11:57:10 -0700173 void cleanupConnection(SensorDirectConnection* c);
Peng Xueb4d6282015-12-10 18:02:41 -0800174
Andrew Lehmer3a602572021-03-25 15:19:56 -0700175 // Call with mLock held.
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700176 void checkAndReportProxStateChangeLocked();
177 void notifyProximityStateLocked(const bool isActive,
178 const std::vector<sp<ProximityActiveListener>>& listeners);
Andrew Lehmer3a602572021-03-25 15:19:56 -0700179
Peng Xueb4d6282015-12-10 18:02:41 -0800180 status_t enable(const sp<SensorEventConnection>& connection, int handle,
181 nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
182 const String16& opPackageName);
183
184 status_t disable(const sp<SensorEventConnection>& connection, int handle);
185
186 status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns,
187 const String16& opPackageName);
188
189 status_t flushSensor(const sp<SensorEventConnection>& connection,
190 const String16& opPackageName);
191
Andrew Lehmer3a602572021-03-25 15:19:56 -0700192 status_t addProximityActiveListener(const sp<ProximityActiveListener>& callback) ANDROID_API;
193 status_t removeProximityActiveListener(const sp<ProximityActiveListener>& callback) ANDROID_API;
194
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200195 int registerRuntimeSensor(const sensor_t& sensor, int deviceId,
Vladimir Komsiyskifafbe052023-02-10 10:23:59 +0100196 sp<RuntimeSensorCallback> callback) ANDROID_API;
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200197 status_t unregisterRuntimeSensor(int handle) ANDROID_API;
198 status_t sendRuntimeSensorEvent(const sensors_event_t& event) ANDROID_API;
199
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100200 int configureRuntimeSensorDirectChannel(int sensorHandle, const SensorDirectConnection* c,
201 const sensors_direct_cfg_t* config);
202
Anh Phamaf91a912021-02-10 14:10:53 +0100203 // Returns true if a sensor should be throttled according to our rate-throttling rules.
204 static bool isSensorInCappedSet(int sensorType);
Svet Ganove752a5c2018-01-15 17:14:20 -0800205
206 virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args);
207
Peng Xueb4d6282015-12-10 18:02:41 -0800208private:
Mathias Agopianb6df7d02013-05-09 14:53:35 -0700209 friend class BinderService<SensorService>;
Mathias Agopianfc328812010-07-14 23:41:37 -0700210
Peng Xueb4d6282015-12-10 18:02:41 -0800211 // nested class/struct for internal use
Brian Duddie967ce172019-06-10 11:08:27 -0700212 class ConnectionSafeAutolock;
213 class SensorConnectionHolder;
Peng Xueb4d6282015-12-10 18:02:41 -0800214 class SensorEventAckReceiver;
Brian Duddie967ce172019-06-10 11:08:27 -0700215 class SensorRecord;
Peng Xu51224682017-03-10 16:57:27 -0800216 class SensorRegistrationInfo;
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +0200217 class RuntimeSensorHandler;
Peng Xueb4d6282015-12-10 18:02:41 -0800218
Brian Duddie967ce172019-06-10 11:08:27 -0700219 // Promoting a SensorEventConnection or SensorDirectConnection from wp to sp must be done with
220 // mLock held, but destroying that sp must be done unlocked to avoid a race condition that
221 // causes a deadlock (remote dies while we hold a local sp, then our decStrong() call invokes
222 // the dtor -> cleanupConnection() tries to re-lock the mutex). This class ensures safe usage
223 // by wrapping a Mutex::Autolock on SensorService's mLock, plus vectors that hold promoted sp<>
224 // references until the lock is released, when they are safely destroyed.
225 // All read accesses to the connection lists in mConnectionHolder must be done via this class.
226 class ConnectionSafeAutolock final {
227 public:
228 // Returns a list of non-null promoted connection references
229 const std::vector<sp<SensorEventConnection>>& getActiveConnections();
230 const std::vector<sp<SensorDirectConnection>>& getDirectConnections();
231
232 private:
233 // Constructed via SensorConnectionHolder::lock()
234 friend class SensorConnectionHolder;
235 explicit ConnectionSafeAutolock(SensorConnectionHolder& holder, Mutex& mutex);
236 DISALLOW_IMPLICIT_CONSTRUCTORS(ConnectionSafeAutolock);
237
238 // NOTE: Order of these members is important, as the destructor for non-static members
239 // get invoked in the reverse order of their declaration. Here we are relying on the
240 // Autolock to be destroyed *before* the vectors, so the sp<> objects are destroyed without
241 // the lock held, which avoids the deadlock.
242 SensorConnectionHolder& mConnectionHolder;
243 std::vector<std::vector<sp<SensorEventConnection>>> mReferencedActiveConnections;
244 std::vector<std::vector<sp<SensorDirectConnection>>> mReferencedDirectConnections;
245 Mutex::Autolock mAutolock;
246
247 template<typename ConnectionType>
248 const std::vector<sp<ConnectionType>>& getConnectionsHelper(
249 const SortedVector<wp<ConnectionType>>& connectionList,
250 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder);
251 };
252
253 // Encapsulates the collection of active SensorEventConection and SensorDirectConnection
254 // references. Write access is done through this class with mLock held, but all read access
255 // must be routed through ConnectionSafeAutolock.
256 class SensorConnectionHolder {
257 public:
258 void addEventConnectionIfNotPresent(const sp<SensorEventConnection>& connection);
259 void removeEventConnection(const wp<SensorEventConnection>& connection);
260
261 void addDirectConnection(const sp<SensorDirectConnection>& connection);
262 void removeDirectConnection(const wp<SensorDirectConnection>& connection);
263
264 // Pass in the mutex that protects this connection holder; acquires the lock and returns an
265 // object that can be used to safely read the lists of connections
266 ConnectionSafeAutolock lock(Mutex& mutex);
267
268 private:
269 friend class ConnectionSafeAutolock;
270 SortedVector< wp<SensorEventConnection> > mActiveConnections;
271 SortedVector< wp<SensorDirectConnection> > mDirectConnections;
272 };
273
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +0200274 class RuntimeSensorHandler : public Thread {
275 sp<SensorService> const mService;
276 public:
277 virtual bool threadLoop();
278 explicit RuntimeSensorHandler(const sp<SensorService>& service) : mService(service) {
279 }
280 };
281
Svet Ganove752a5c2018-01-15 17:14:20 -0800282 // If accessing a sensor we need to make sure the UID has access to it. If
283 // the app UID is idle then it cannot access sensors and gets no trigger
284 // events, no on-change events, flush event behavior does not change, and
285 // recurring events are the same as the first one delivered in idle state
286 // emulating no sensor change. As soon as the app UID transitions to an
287 // active state we will start reporting events as usual and vise versa. This
288 // approach transparently handles observing sensors while the app UID transitions
289 // between idle/active state avoiding to get stuck in a state receiving sensor
290 // data while idle or not receiving sensor data while active.
291 class UidPolicy : public BnUidObserver {
292 public:
293 explicit UidPolicy(wp<SensorService> service)
294 : mService(service) {}
295 void registerSelf();
296 void unregisterSelf();
297
298 bool isUidActive(uid_t uid);
299
Austin Borger51442332022-02-17 00:26:18 +0000300 void onUidGone(uid_t uid, bool disabled) override;
301 void onUidActive(uid_t uid) override;
302 void onUidIdle(uid_t uid, bool disabled) override;
Eric Laurent05595892018-10-18 14:56:24 -0700303 void onUidStateChanged(uid_t uid __unused, int32_t procState __unused,
Austin Borger51442332022-02-17 00:26:18 +0000304 int64_t procStateSeq __unused,
305 int32_t capability __unused) override {}
Austin Borgerb557f7b2023-03-30 17:52:47 -0700306 void onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) override {}
Svet Ganove752a5c2018-01-15 17:14:20 -0800307
308 void addOverrideUid(uid_t uid, bool active);
309 void removeOverrideUid(uid_t uid);
310 private:
311 bool isUidActiveLocked(uid_t uid);
312 void updateOverrideUid(uid_t uid, bool active, bool insert);
313
314 Mutex mUidLock;
315 wp<SensorService> mService;
316 std::unordered_set<uid_t> mActiveUids;
317 std::unordered_map<uid_t, bool> mOverrideUids;
318 };
319
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700320 bool isUidActive(uid_t uid);
321
Michael Groover5e1f60b2018-12-04 22:34:29 -0800322 // Sensor privacy allows a user to disable access to all sensors on the device. When
323 // enabled sensor privacy will prevent all apps, including active apps, from accessing
324 // sensors, they will not receive trigger nor on-change events, flush event behavior
325 // does not change, and recurring events are the same as the first one delivered when
326 // sensor privacy was enabled. All sensor direct connections will be stopped as well
327 // and new direct connections will not be allowed while sensor privacy is enabled.
328 // Once sensor privacy is disabled access to sensors will be restored for active
329 // apps, previously stopped direct connections will be restarted, and new direct
330 // connections will be allowed again.
331 class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener {
332 public:
Greg Kaiser17067592021-02-17 22:05:25 -0800333 explicit SensorPrivacyPolicy(wp<SensorService> service)
Evan Severson4c197852022-01-27 10:44:27 -0800334 : mService(service) {}
Michael Groover5e1f60b2018-12-04 22:34:29 -0800335 void registerSelf();
336 void unregisterSelf();
337
338 bool isSensorPrivacyEnabled();
339
Evan Severson4c197852022-01-27 10:44:27 -0800340 binder::Status onSensorPrivacyChanged(int toggleType, int sensor,
341 bool enabled);
342
Jyoti Bhayana76256ad2024-02-11 13:19:29 +0000343 // This callback is used for additional automotive-specific states for sensor privacy
344 // such as AUTO_DRIVER_ASSISTANCE_APPS. The newly defined states will only be valid
345 // for camera privacy on automotive devices. onSensorPrivacyChanged() will still be
346 // invoked whenever the enabled status of a toggle changes.
347 binder::Status onSensorPrivacyStateChanged(int, int, int) {return binder::Status::ok();}
348
Evan Severson4c197852022-01-27 10:44:27 -0800349 protected:
350 std::atomic_bool mSensorPrivacyEnabled;
351 wp<SensorService> mService;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800352
353 private:
Anh Pham5198c992021-02-10 14:15:30 +0100354 Mutex mSensorPrivacyLock;
Evan Severson4c197852022-01-27 10:44:27 -0800355 };
356
357 class MicrophonePrivacyPolicy : public SensorPrivacyPolicy {
358 public:
359 explicit MicrophonePrivacyPolicy(wp<SensorService> service)
360 : SensorPrivacyPolicy(service) {}
361 void registerSelf();
362 void unregisterSelf();
363
364 binder::Status onSensorPrivacyChanged(int toggleType, int sensor,
365 bool enabled);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800366 };
367
Anh Phamb04658b2021-03-22 18:17:17 +0100368 // A class automatically clearing and restoring binder caller identity inside
369 // a code block (scoped variable).
370 // Declare one systematically before calling SensorPrivacyManager methods so that they are
371 // executed with the same level of privilege as the SensorService process.
372 class AutoCallerClear {
373 public:
374 AutoCallerClear() :
375 mToken(IPCThreadState::self()->clearCallingIdentity()) {}
376 ~AutoCallerClear() {
377 IPCThreadState::self()->restoreCallingIdentity(mToken);
378 }
379
380 private:
381 const int64_t mToken;
382 };
383
Mathias Agopianb6df7d02013-05-09 14:53:35 -0700384 static const char* WAKE_LOCK_NAME;
Mathias Agopianfc328812010-07-14 23:41:37 -0700385 virtual ~SensorService();
386
387 virtual void onFirstRef();
388
389 // Thread interface
390 virtual bool threadLoop();
391
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +0200392 void processRuntimeSensorEvents();
393
Mathias Agopianfc328812010-07-14 23:41:37 -0700394 // ISensorServer interface
Svetoslavb412f6e2015-04-29 16:50:41 -0700395 virtual Vector<Sensor> getSensorList(const String16& opPackageName);
Peng Xu2576cb62016-01-20 00:22:09 -0800396 virtual Vector<Sensor> getDynamicSensorList(const String16& opPackageName);
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200397 virtual Vector<Sensor> getRuntimeSensorList(const String16& opPackageName, int deviceId);
Peng Xueb4d6282015-12-10 18:02:41 -0800398 virtual sp<ISensorEventConnection> createSensorEventConnection(
399 const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -0800400 int requestedMode, const String16& opPackageName, const String16& attributionTag);
Aravind Akella5c538052015-06-29 12:37:48 -0700401 virtual int isDataInjectionEnabled();
Mark Wheatley8f285d92023-07-07 20:07:18 +0000402 virtual int isReplayDataInjectionEnabled();
403 virtual int isHalBypassReplayDataInjectionEnabled();
Peng Xue36e3472016-11-03 11:57:10 -0700404 virtual sp<ISensorEventConnection> createSensorDirectConnection(const String16& opPackageName,
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100405 int deviceId, uint32_t size, int32_t type, int32_t format,
406 const native_handle *resource);
Peng Xudd5c5cb2017-03-16 17:39:43 -0700407 virtual int setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -0700408 int32_t handle, int32_t type, const Vector<float> &floats, const Vector<int32_t> &ints);
Mathias Agopianfc328812010-07-14 23:41:37 -0700409 virtual status_t dump(int fd, const Vector<String16>& args);
Andrew Lehmer3a602572021-03-25 15:19:56 -0700410
Mike Ma24743862020-01-29 00:36:55 -0800411 status_t dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const;
Mathias Agopianf001c922010-11-11 17:58:51 -0800412 String8 getSensorName(int handle) const;
Arthur Ishiguro883748c2020-10-28 13:18:02 -0700413 String8 getSensorStringType(int handle) const;
Aravind Akellab4099e72013-10-15 15:43:10 -0700414 bool isVirtualSensor(int handle) const;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100415 std::shared_ptr<SensorInterface> getSensorInterfaceFromHandle(int handle) const;
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100416 int getDeviceIdFromHandle(int handle) const;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800417 bool isWakeUpSensor(int type) const;
Aravind Akella0ec20662014-09-14 17:29:48 -0700418 void recordLastValueLocked(sensors_event_t const* buffer, size_t count);
Mathias Agopianf001c922010-11-11 17:58:51 -0800419 static void sortEventBuffer(sensors_event_t* buffer, size_t count);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100420 bool registerSensor(std::shared_ptr<SensorInterface> sensor, bool isDebug = false,
421 bool isVirtual = false, int deviceId = RuntimeSensor::DEFAULT_DEVICE_ID);
422 bool registerVirtualSensor(std::shared_ptr<SensorInterface> sensor, bool isDebug = false);
423 bool registerDynamicSensorLocked(std::shared_ptr<SensorInterface> sensor, bool isDebug = false);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800424 bool unregisterDynamicSensorLocked(int handle);
Peng Xueb4d6282015-12-10 18:02:41 -0800425 status_t cleanupWithoutDisable(const sp<SensorEventConnection>& connection, int handle);
426 status_t cleanupWithoutDisableLocked(const sp<SensorEventConnection>& connection, int handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800427 void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Mathias Agopianb6df7d02013-05-09 14:53:35 -0700428 sensors_event_t const* buffer, const int count);
Brian Duddie4a4d0462022-05-09 16:49:49 -0700429 bool canAccessSensor(const Sensor& sensor, const char* operation,
Svetoslavb412f6e2015-04-29 16:50:41 -0700430 const String16& opPackageName);
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200431 void addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
432 Vector<Sensor>& accessibleSensorList);
Brian Stack793f4642019-04-18 17:21:34 -0700433 static bool hasPermissionForSensor(const Sensor& sensor);
434 static int getTargetSdkVersion(const String16& opPackageName);
Brian Duddie0d4ac562022-05-23 17:47:50 -0700435 static void resetTargetSdkVersionCache(const String16& opPackageName);
Anthony Stangec1608152023-01-06 21:14:46 +0000436 // Checks if the provided target operating mode is valid and returns the enum if it is.
437 static bool getTargetOperatingMode(const std::string &inputString, Mode *targetModeOut);
438 status_t changeOperatingMode(const Vector<String16>& args, Mode targetOperatingMode);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800439 // SensorService acquires a partial wakelock for delivering events from wake up sensors. This
440 // method checks whether all the events from these wake up sensors have been delivered to the
441 // corresponding applications, if yes the wakelock is released.
442 void checkWakeLockState();
Brian Duddie967ce172019-06-10 11:08:27 -0700443 void checkWakeLockStateLocked(ConnectionSafeAutolock* connLock);
Aravind Akellab4373ac2014-10-29 17:55:20 -0700444 bool isWakeLockAcquired();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800445 bool isWakeUpSensorEvent(const sensors_event_t& event) const;
Aravind Akella56ae4262014-07-10 16:01:10 -0700446
447 sp<Looper> getLooper() const;
448
Aravind Akellab4373ac2014-10-29 17:55:20 -0700449 // Reset mWakeLockRefCounts for all SensorEventConnections to zero. This may happen if
450 // SensorService did not receive any acknowledgements from apps which have registered for
451 // wake_up sensors.
452 void resetAllWakeLockRefCounts();
453
Peng Xueb4d6282015-12-10 18:02:41 -0800454 // Acquire or release wake_lock. If wake_lock is acquired, set the timeout in the looper to 5
455 // seconds and wake the looper.
Aravind Akellab4373ac2014-10-29 17:55:20 -0700456 void setWakeLockAcquiredLocked(bool acquire);
457
458 // Send events from the event cache for this particular connection.
459 void sendEventsFromCache(const sp<SensorEventConnection>& connection);
460
Rocky Fangbeb0dff2023-12-15 01:59:46 +0000461 // Send all events in the buffer to all clients.
462 void sendEventsToAllClients(
463 const std::vector<sp<SensorEventConnection>>& activeConnections,
464 ssize_t count);
465
Aravind Akella4949c502015-02-11 15:54:35 -0800466 // If SensorService is operating in RESTRICTED mode, only select whitelisted packages are
467 // allowed to register for or call flush on sensors. Typically only cts test packages are
468 // allowed.
Anthony Stangecd01ec12023-01-06 18:35:13 +0000469 bool isAllowListedPackage(const String8& packageName);
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700470
471 // Returns true if a connection with the specified opPackageName has no access to sensors
472 // in the RESTRICTED mode (i.e. the service is in RESTRICTED mode, and the package is not
473 // whitelisted). mLock must be held to invoke this method.
474 bool isOperationRestrictedLocked(const String16& opPackageName);
Aravind Akella4949c502015-02-11 15:54:35 -0800475
Anh Phamaf91a912021-02-10 14:10:53 +0100476 status_t adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
477 const String16& opPackageName);
478 status_t adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
479 const String16& opPackageName);
480 bool isRateCappedBasedOnPermission(const String16& opPackageName);
481 bool isPackageDebuggable(const String16& opPackageName);
482
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700483 // Reset the state of SensorService to NORMAL mode.
484 status_t resetToNormalMode();
485 status_t resetToNormalModeLocked();
486
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700487 // Transforms the UUIDs for all the sensors into proper IDs.
488 void makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const;
489 // Gets the appropriate ID from the given UUID.
490 int32_t getIdFromUuid(const Sensor::uuid_t &uuid) const;
491 // Either read from storage or create a new one.
492 static bool initializeHmacKey();
493
Peng Xu98d30f62016-08-01 18:12:11 -0700494 // Enable SCHED_FIFO priority for thread
495 void enableSchedFifoMode();
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700496
Svet Ganove752a5c2018-01-15 17:14:20 -0800497 // Sets whether the given UID can get sensor data
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700498 void onUidStateChanged(uid_t uid, UidState state);
Svet Ganove752a5c2018-01-15 17:14:20 -0800499
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700500 // Returns true if a connection with the given uid and opPackageName
501 // currently has access to sensors.
502 bool hasSensorAccess(uid_t uid, const String16& opPackageName);
503 // Same as hasSensorAccess but with mLock held.
504 bool hasSensorAccessLocked(uid_t uid, const String16& opPackageName);
505
Svet Ganove752a5c2018-01-15 17:14:20 -0800506 // Overrides the UID state as if it is idle
507 status_t handleSetUidState(Vector<String16>& args, int err);
508 // Clears the override for the UID state
509 status_t handleResetUidState(Vector<String16>& args, int err);
510 // Gets the UID state
511 status_t handleGetUidState(Vector<String16>& args, int out, int err);
512 // Prints the shell command help
513 status_t printHelp(int out);
514
Michael Groover5e1f60b2018-12-04 22:34:29 -0800515 // temporarily stops all active direct connections and disables all sensors
516 void disableAllSensors();
Brian Duddie967ce172019-06-10 11:08:27 -0700517 void disableAllSensorsLocked(ConnectionSafeAutolock* connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800518 // restarts the previously stopped direct connections and enables all sensors
519 void enableAllSensors();
Brian Duddie967ce172019-06-10 11:08:27 -0700520 void enableAllSensorsLocked(ConnectionSafeAutolock* connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800521
Anh Pham5198c992021-02-10 14:15:30 +0100522 // Caps active direct connections (when the mic toggle is flipped to on)
Evan Severson4c197852022-01-27 10:44:27 -0800523 void capRates();
Anh Pham5198c992021-02-10 14:15:30 +0100524 // Removes the capped rate on active direct connections (when the mic toggle is flipped to off)
Evan Severson4c197852022-01-27 10:44:27 -0800525 void uncapRates();
Anh Pham5198c992021-02-10 14:15:30 +0100526
Mark Wheatley8f285d92023-07-07 20:07:18 +0000527 bool isInjectionMode(int mode);
528
Rocky Fangbeb0dff2023-12-15 01:59:46 +0000529 void handleDeviceReconnection(SensorDevice& device);
530
531 // Removes a connected dynamic sensor and send the corresponding event to
532 // all connections.
533 void disconnectDynamicSensor(
534 int handle,
535 const std::vector<sp<SensorEventConnection>>& activeConnections);
536
Eric Laurente3f27df2022-01-05 19:20:32 +0100537 static inline bool isAudioServerOrSystemServerUid(uid_t uid) {
538 return multiuser_get_app_id(uid) == AID_SYSTEM || uid == AID_AUDIOSERVER;
539 }
540
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700541 static uint8_t sHmacGlobalKey[128];
542 static bool sHmacGlobalKeyIsValid;
543
Andrew Lehmer3a602572021-03-25 15:19:56 -0700544 static std::atomic_uint64_t curProxCallbackSeq;
545 static std::atomic_uint64_t completedCallbackSeq;
546
Brian Stack4baa5be2018-09-18 14:03:13 -0700547 SensorServiceUtil::SensorList mSensors;
Mathias Agopian50df2952010-07-19 19:09:10 -0700548 status_t mInitCheck;
Peng Xueb4d6282015-12-10 18:02:41 -0800549
Aravind Akella5466c3d2014-08-22 16:11:10 -0700550 // Socket buffersize used to initialize BitTube. This size depends on whether batching is
551 // supported or not.
Peng Xu755c4512016-04-07 23:15:14 -0700552 uint32_t mSocketBufferSize;
553 sp<Looper> mLooper;
554 sp<SensorEventAckReceiver> mAckReceiver;
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +0200555 sp<RuntimeSensorHandler> mRuntimeSensorHandler;
556 // Mutex and CV used to notify the mRuntimeSensorHandler thread that there are new events.
557 std::mutex mRutimeSensorThreadMutex;
558 std::condition_variable mRuntimeSensorsCv;
Mathias Agopianfc328812010-07-14 23:41:37 -0700559
560 // protected by mLock
561 mutable Mutex mLock;
Mathias Agopianfc328812010-07-14 23:41:37 -0700562 DefaultKeyedVector<int, SensorRecord*> mActiveSensors;
Peng Xu755c4512016-04-07 23:15:14 -0700563 std::unordered_set<int> mActiveVirtualSensors;
Brian Duddie967ce172019-06-10 11:08:27 -0700564 SensorConnectionHolder mConnectionHolder;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800565 bool mWakeLockAcquired;
Vladimir Komsiyski60ed8362023-06-16 10:03:16 +0200566 sensors_event_t *mSensorEventBuffer, *mSensorEventScratch, *mRuntimeSensorEventBuffer;
Brian Duddie967ce172019-06-10 11:08:27 -0700567 // WARNING: these SensorEventConnection instances must not be promoted to sp, except via
568 // modification to add support for them in ConnectionSafeAutolock
Peng Xuded526e2016-08-12 16:39:44 -0700569 wp<const SensorEventConnection> * mMapFlushEventsToConnections;
Brian Stack4baa5be2018-09-18 14:03:13 -0700570 std::unordered_map<int, SensorServiceUtil::RecentEventLogger*> mRecentEvent;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700571 Mode mCurrentOperatingMode;
Vladimir Komsiyskif76bba52022-10-23 10:56:06 +0200572 std::queue<sensors_event_t> mRuntimeSensorEventQueue;
Vladimir Komsiyski4871f092023-01-19 18:25:43 +0100573 std::unordered_map</*deviceId*/int, sp<RuntimeSensorCallback>> mRuntimeSensorCallbacks;
Peng Xueb4d6282015-12-10 18:02:41 -0800574
Brian Duddie4a4d0462022-05-09 16:49:49 -0700575 // true if the head tracker sensor type is currently restricted to system usage only
576 // (can only be unrestricted for testing, via shell cmd)
577 bool mHtRestricted = true;
578
Aravind Akella5c538052015-06-29 12:37:48 -0700579 // This packagaName is set when SensorService is in RESTRICTED or DATA_INJECTION mode. Only
580 // applications with this packageName are allowed to activate/deactivate or call flush on
581 // sensors. To run CTS this is can be set to ".cts." and only CTS tests will get access to
582 // sensors.
Anthony Stangecd01ec12023-01-06 18:35:13 +0000583 String8 mAllowListedPackage;
Aravind Akella8493b792014-09-08 15:45:47 -0700584
Aravind Akella18d6d512015-06-18 14:18:28 -0700585 int mNextSensorRegIndex;
586 Vector<SensorRegistrationInfo> mLastNSensorRegistrations;
Svet Ganove752a5c2018-01-15 17:14:20 -0800587
588 sp<UidPolicy> mUidPolicy;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800589 sp<SensorPrivacyPolicy> mSensorPrivacyPolicy;
Brian Stack793f4642019-04-18 17:21:34 -0700590
591 static AppOpsManager sAppOpsManager;
592 static std::map<String16, int> sPackageTargetVersion;
593 static Mutex sPackageTargetVersionLock;
Anthony Stange07eb4212020-08-28 14:50:28 -0400594 static String16 sSensorInterfaceDescriptorPrefix;
Anh Pham5198c992021-02-10 14:15:30 +0100595
Evan Severson4c197852022-01-27 10:44:27 -0800596 sp<MicrophonePrivacyPolicy> mMicSensorPrivacyPolicy;
Andrew Lehmer3a602572021-03-25 15:19:56 -0700597
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700598 // Keeps track of the handles of all proximity sensors in the system.
599 std::vector<int32_t> mProxSensorHandles;
600 // The last proximity sensor active state reported to listeners.
601 bool mLastReportedProxIsActive;
602 // Listeners subscribed to receive updates on the proximity sensor active state.
Andrew Lehmer3a602572021-03-25 15:19:56 -0700603 std::vector<sp<ProximityActiveListener>> mProximityActiveListeners;
Rocky Fangbeb0dff2023-12-15 01:59:46 +0000604
605 // Stores the handle of the dynamic_meta sensor to send clean up event once
606 // HAL crashes.
607 std::optional<int> mDynamicMetaSensorHandle;
Mathias Agopianfc328812010-07-14 23:41:37 -0700608};
609
Peng Xueb4d6282015-12-10 18:02:41 -0800610} // namespace android
Mathias Agopianfc328812010-07-14 23:41:37 -0700611#endif // ANDROID_SENSOR_SERVICE_H