1 /*
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 
20 #include <android-base/macros.h>
21 #include <binder/AppOpsManager.h>
22 #include <binder/BinderService.h>
23 #include <binder/IUidObserver.h>
24 #include <cutils/compiler.h>
25 #include <cutils/multiuser.h>
26 #include <private/android_filesystem_config.h>
27 #include <sensor/ISensorEventConnection.h>
28 #include <sensor/ISensorServer.h>
29 #include <sensor/Sensor.h>
30 #include <stdint.h>
31 #include <sys/types.h>
32 #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 
40 #include <condition_variable>
41 #include <mutex>
42 #include <queue>
43 #include <unordered_map>
44 #include <unordered_set>
45 #include <vector>
46 
47 #include "RecentEventLogger.h"
48 #include "SensorList.h"
49 #include "android/hardware/BnSensorPrivacyListener.h"
50 
51 #if __clang__
52 // 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.
54 #pragma clang diagnostic ignored "-Woverloaded-virtual"
55 #endif
56 
57 // ---------------------------------------------------------------------------
58 #define IGNORE_HARDWARE_FUSION  false
59 #define DEBUG_CONNECTIONS false
60 // Max size is 100 KB which is enough to accept a batch of about 1000 events.
61 #define MAX_SOCKET_BUFFER_SIZE_BATCHED (100 * 1024)
62 // For older HALs which don't support batching, use a smaller socket buffer size.
63 #define SOCKET_BUFFER_SIZE_NON_BATCHED (4 * 1024)
64 
65 #define SENSOR_REGISTRATIONS_BUF_SIZE 500
66 
67 // Apps that targets S+ and do not have HIGH_SAMPLING_RATE_SENSORS permission will be capped
68 // 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.
70 // 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 
76 namespace android {
77 // ---------------------------------------------------------------------------
78 class SensorInterface;
79 
80 class SensorService :
81         public BinderService<SensorService>,
82         public BnSensorServer,
83         protected Thread
84 {
85     // nested class/struct for internal use
86     class SensorEventConnection;
87     class SensorDirectConnection;
88 
89 public:
90     enum UidState {
91       UID_STATE_ACTIVE = 0,
92       UID_STATE_IDLE,
93     };
94 
95     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
106        // that do not support injection will give an error.
107        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.
119        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,
124        // 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,
129 
130       // State Transitions supported.
131       //     RESTRICTED   <---  NORMAL   ---> DATA_INJECTION/REPLAY_DATA_INJECTION
132       //                  --->           <---
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 
149     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 
156     class RuntimeSensorCallback : public virtual RefBase {
157     public:
158         // Note that the callback is invoked from an async thread and can interact with the
159         // SensorService directly.
160         virtual status_t onConfigurationChanged(int handle, bool enabled,
161                                                 int64_t samplingPeriodNanos,
162                                                 int64_t batchReportLatencyNanos) = 0;
163         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;
167     };
168 
getServiceName()169     static char const* getServiceName() ANDROID_API { return "sensorservice"; }
170     SensorService() ANDROID_API;
171 
172     void cleanupConnection(SensorEventConnection* connection);
173     void cleanupConnection(SensorDirectConnection* c);
174 
175     // Call with mLock held.
176     void checkAndReportProxStateChangeLocked();
177     void notifyProximityStateLocked(const bool isActive,
178                                     const std::vector<sp<ProximityActiveListener>>& listeners);
179 
180     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 
192     status_t addProximityActiveListener(const sp<ProximityActiveListener>& callback) ANDROID_API;
193     status_t removeProximityActiveListener(const sp<ProximityActiveListener>& callback) ANDROID_API;
194 
195     int registerRuntimeSensor(const sensor_t& sensor, int deviceId,
196                               sp<RuntimeSensorCallback> callback) ANDROID_API;
197     status_t unregisterRuntimeSensor(int handle) ANDROID_API;
198     status_t sendRuntimeSensorEvent(const sensors_event_t& event) ANDROID_API;
199 
200     int configureRuntimeSensorDirectChannel(int sensorHandle, const SensorDirectConnection* c,
201                                             const sensors_direct_cfg_t* config);
202 
203     // Returns true if a sensor should be throttled according to our rate-throttling rules.
204     static bool isSensorInCappedSet(int sensorType);
205 
206     virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args);
207 
208 private:
209     friend class BinderService<SensorService>;
210 
211     // nested class/struct for internal use
212     class ConnectionSafeAutolock;
213     class SensorConnectionHolder;
214     class SensorEventAckReceiver;
215     class SensorRecord;
216     class SensorRegistrationInfo;
217     class RuntimeSensorHandler;
218 
219     // 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 
274     class RuntimeSensorHandler : public Thread {
275         sp<SensorService> const mService;
276     public:
277         virtual bool threadLoop();
RuntimeSensorHandler(const sp<SensorService> & service)278         explicit RuntimeSensorHandler(const sp<SensorService>& service) : mService(service) {
279         }
280     };
281 
282     // 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:
UidPolicy(wp<SensorService> service)293             explicit UidPolicy(wp<SensorService> service)
294                     : mService(service) {}
295             void registerSelf();
296             void unregisterSelf();
297 
298             bool isUidActive(uid_t uid);
299 
300             void onUidGone(uid_t uid, bool disabled) override;
301             void onUidActive(uid_t uid) override;
302             void onUidIdle(uid_t uid, bool disabled) override;
onUidStateChanged(uid_t uid __unused,int32_t procState __unused,int64_t procStateSeq __unused,int32_t capability __unused)303             void onUidStateChanged(uid_t uid __unused, int32_t procState __unused,
304                                    int64_t procStateSeq __unused,
305                                    int32_t capability __unused) override {}
onUidProcAdjChanged(uid_t uid __unused,int32_t adj __unused)306             void onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) override {}
307 
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 
320     bool isUidActive(uid_t uid);
321 
322     // 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:
SensorPrivacyPolicy(wp<SensorService> service)333             explicit SensorPrivacyPolicy(wp<SensorService> service)
334                     : mService(service) {}
335             void registerSelf();
336             void unregisterSelf();
337 
338             bool isSensorPrivacyEnabled();
339 
340             binder::Status onSensorPrivacyChanged(int toggleType, int sensor,
341                                                   bool enabled);
342 
343             // This callback is used for additional automotive-specific state for sensor privacy
344             // such as ENABLED_EXCEPT_ALLOWLISTED_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.
onSensorPrivacyStateChanged(int,int,int)347             binder::Status onSensorPrivacyStateChanged(int, int, int) {return binder::Status::ok();}
348 
349         protected:
350             std::atomic_bool mSensorPrivacyEnabled;
351             wp<SensorService> mService;
352 
353         private:
354             Mutex mSensorPrivacyLock;
355     };
356 
357     class MicrophonePrivacyPolicy : public SensorPrivacyPolicy {
358         public:
MicrophonePrivacyPolicy(wp<SensorService> service)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);
366     };
367 
368     // 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:
AutoCallerClear()374             AutoCallerClear() :
375                 mToken(IPCThreadState::self()->clearCallingIdentity()) {}
~AutoCallerClear()376             ~AutoCallerClear() {
377                 IPCThreadState::self()->restoreCallingIdentity(mToken);
378             }
379 
380         private:
381             const int64_t mToken;
382     };
383 
384     static const char* WAKE_LOCK_NAME;
385     virtual ~SensorService();
386 
387     virtual void onFirstRef();
388 
389     // Thread interface
390     virtual bool threadLoop();
391 
392     void processRuntimeSensorEvents();
393 
394     // ISensorServer interface
395     virtual Vector<Sensor> getSensorList(const String16& opPackageName);
396     virtual Vector<Sensor> getDynamicSensorList(const String16& opPackageName);
397     virtual Vector<Sensor> getRuntimeSensorList(const String16& opPackageName, int deviceId);
398     virtual sp<ISensorEventConnection> createSensorEventConnection(
399             const String8& packageName,
400             int requestedMode, const String16& opPackageName, const String16& attributionTag);
401     virtual int isDataInjectionEnabled();
402     virtual int isReplayDataInjectionEnabled();
403     virtual int isHalBypassReplayDataInjectionEnabled();
404     virtual sp<ISensorEventConnection> createSensorDirectConnection(const String16& opPackageName,
405             int deviceId, uint32_t size, int32_t type, int32_t format,
406             const native_handle *resource);
407     virtual int setOperationParameter(
408             int32_t handle, int32_t type, const Vector<float> &floats, const Vector<int32_t> &ints);
409     virtual status_t dump(int fd, const Vector<String16>& args);
410 
411     status_t dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const;
412     String8 getSensorName(int handle) const;
413     String8 getSensorStringType(int handle) const;
414     bool isVirtualSensor(int handle) const;
415     std::shared_ptr<SensorInterface> getSensorInterfaceFromHandle(int handle) const;
416     int getDeviceIdFromHandle(int handle) const;
417     bool isWakeUpSensor(int type) const;
418     void recordLastValueLocked(sensors_event_t const* buffer, size_t count);
419     static void sortEventBuffer(sensors_event_t* buffer, size_t count);
420     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);
424     bool unregisterDynamicSensorLocked(int handle);
425     status_t cleanupWithoutDisable(const sp<SensorEventConnection>& connection, int handle);
426     status_t cleanupWithoutDisableLocked(const sp<SensorEventConnection>& connection, int handle);
427     void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
428             sensors_event_t const* buffer, const int count);
429     bool canAccessSensor(const Sensor& sensor, const char* operation,
430             const String16& opPackageName);
431     void addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
432             Vector<Sensor>& accessibleSensorList);
433     static bool hasPermissionForSensor(const Sensor& sensor);
434     static int getTargetSdkVersion(const String16& opPackageName);
435     static void resetTargetSdkVersionCache(const String16& opPackageName);
436     // 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);
439     // 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();
443     void checkWakeLockStateLocked(ConnectionSafeAutolock* connLock);
444     bool isWakeLockAcquired();
445     bool isWakeUpSensorEvent(const sensors_event_t& event) const;
446 
447     sp<Looper> getLooper() const;
448 
449     // 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 
454     // Acquire or release wake_lock. If wake_lock is acquired, set the timeout in the looper to 5
455     // seconds and wake the looper.
456     void setWakeLockAcquiredLocked(bool acquire);
457 
458     // Send events from the event cache for this particular connection.
459     void sendEventsFromCache(const sp<SensorEventConnection>& connection);
460 
461     // Send all events in the buffer to all clients.
462     void sendEventsToAllClients(
463         const std::vector<sp<SensorEventConnection>>& activeConnections,
464         ssize_t count);
465 
466     // 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.
469     bool isAllowListedPackage(const String8& packageName);
470 
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);
475 
476     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 
483     // Reset the state of SensorService to NORMAL mode.
484     status_t resetToNormalMode();
485     status_t resetToNormalModeLocked();
486 
487     // 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 
494     // Enable SCHED_FIFO priority for thread
495     void enableSchedFifoMode();
496 
497     // Sets whether the given UID can get sensor data
498     void onUidStateChanged(uid_t uid, UidState state);
499 
500     // 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 
506     // 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 
515     // temporarily stops all active direct connections and disables all sensors
516     void disableAllSensors();
517     void disableAllSensorsLocked(ConnectionSafeAutolock* connLock);
518     // restarts the previously stopped direct connections and enables all sensors
519     void enableAllSensors();
520     void enableAllSensorsLocked(ConnectionSafeAutolock* connLock);
521 
522     // Caps active direct connections (when the mic toggle is flipped to on)
523     void capRates();
524     // Removes the capped rate on active direct connections (when the mic toggle is flipped to off)
525     void uncapRates();
526 
527     bool isInjectionMode(int mode);
528 
529     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 
isAudioServerOrSystemServerUid(uid_t uid)537     static inline bool isAudioServerOrSystemServerUid(uid_t uid) {
538         return multiuser_get_app_id(uid) == AID_SYSTEM || uid == AID_AUDIOSERVER;
539     }
540 
541     static uint8_t sHmacGlobalKey[128];
542     static bool sHmacGlobalKeyIsValid;
543 
544     static std::atomic_uint64_t curProxCallbackSeq;
545     static std::atomic_uint64_t completedCallbackSeq;
546 
547     SensorServiceUtil::SensorList mSensors;
548     status_t mInitCheck;
549 
550     // Socket buffersize used to initialize BitTube. This size depends on whether batching is
551     // supported or not.
552     uint32_t mSocketBufferSize;
553     sp<Looper> mLooper;
554     sp<SensorEventAckReceiver> mAckReceiver;
555     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;
559 
560     // protected by mLock
561     mutable Mutex mLock;
562     DefaultKeyedVector<int, SensorRecord*> mActiveSensors;
563     std::unordered_set<int> mActiveVirtualSensors;
564     SensorConnectionHolder mConnectionHolder;
565     bool mWakeLockAcquired;
566     sensors_event_t *mSensorEventBuffer, *mSensorEventScratch, *mRuntimeSensorEventBuffer;
567     // WARNING: these SensorEventConnection instances must not be promoted to sp, except via
568     // modification to add support for them in ConnectionSafeAutolock
569     wp<const SensorEventConnection> * mMapFlushEventsToConnections;
570     std::unordered_map<int, SensorServiceUtil::RecentEventLogger*> mRecentEvent;
571     Mode mCurrentOperatingMode;
572     std::queue<sensors_event_t> mRuntimeSensorEventQueue;
573     std::unordered_map</*deviceId*/int, sp<RuntimeSensorCallback>> mRuntimeSensorCallbacks;
574 
575     // 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 
579     // 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.
583     String8 mAllowListedPackage;
584 
585     int mNextSensorRegIndex;
586     Vector<SensorRegistrationInfo> mLastNSensorRegistrations;
587 
588     sp<UidPolicy> mUidPolicy;
589     sp<SensorPrivacyPolicy> mSensorPrivacyPolicy;
590 
591     static AppOpsManager sAppOpsManager;
592     static std::map<String16, int> sPackageTargetVersion;
593     static Mutex sPackageTargetVersionLock;
594     static String16 sSensorInterfaceDescriptorPrefix;
595 
596     sp<MicrophonePrivacyPolicy> mMicSensorPrivacyPolicy;
597 
598     // 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.
603     std::vector<sp<ProximityActiveListener>> mProximityActiveListeners;
604 
605     // Stores the handle of the dynamic_meta sensor to send clean up event once
606     // HAL crashes.
607     std::optional<int> mDynamicMetaSensorHandle;
608 };
609 
610 } // namespace android
611 #endif // ANDROID_SENSOR_SERVICE_H
612