• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "SensorList.h"
21 #include "RecentEventLogger.h"
22 
23 #include <android-base/macros.h>
24 #include <binder/AppOpsManager.h>
25 #include <binder/BinderService.h>
26 #include <binder/IUidObserver.h>
27 #include <cutils/compiler.h>
28 #include <cutils/multiuser.h>
29 #include <private/android_filesystem_config.h>
30 #include <sensor/ISensorServer.h>
31 #include <sensor/ISensorEventConnection.h>
32 #include <sensor/Sensor.h>
33 #include "android/hardware/BnSensorPrivacyListener.h"
34 
35 #include <utils/AndroidThreads.h>
36 #include <utils/KeyedVector.h>
37 #include <utils/Looper.h>
38 #include <utils/SortedVector.h>
39 #include <utils/String8.h>
40 #include <utils/Vector.h>
41 #include <utils/threads.h>
42 
43 #include <stdint.h>
44 #include <sys/types.h>
45 #include <queue>
46 #include <unordered_map>
47 #include <unordered_set>
48 #include <vector>
49 
50 #if __clang__
51 // Clang warns about SensorEventConnection::dump hiding BBinder::dump. The cause isn't fixable
52 // without changing the API, so let's tell clang this is indeed intentional.
53 #pragma clang diagnostic ignored "-Woverloaded-virtual"
54 #endif
55 
56 // ---------------------------------------------------------------------------
57 #define IGNORE_HARDWARE_FUSION  false
58 #define DEBUG_CONNECTIONS   false
59 // Max size is 100 KB which is enough to accept a batch of about 1000 events.
60 #define MAX_SOCKET_BUFFER_SIZE_BATCHED (100 * 1024)
61 // For older HALs which don't support batching, use a smaller socket buffer size.
62 #define SOCKET_BUFFER_SIZE_NON_BATCHED (4 * 1024)
63 
64 #define SENSOR_REGISTRATIONS_BUF_SIZE 500
65 
66 // Apps that targets S+ and do not have HIGH_SAMPLING_RATE_SENSORS permission will be capped
67 // at 200 Hz. The cap also applies to all requests when the mic toggle is flipped to on, regardless
68 // of their target SDKs and permission.
69 // Capped sampling periods for apps that have non-direct sensor connections.
70 #define SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS (5 * 1000 * 1000)
71 // Capped sampling rate level for apps that have direct sensor connections.
72 // The enum SENSOR_DIRECT_RATE_NORMAL corresponds to a rate value of at most 110 Hz.
73 #define SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL SENSOR_DIRECT_RATE_NORMAL
74 
75 namespace android {
76 // ---------------------------------------------------------------------------
77 class SensorInterface;
78 
79 class SensorService :
80         public BinderService<SensorService>,
81         public BnSensorServer,
82         protected Thread
83 {
84     // nested class/struct for internal use
85     class SensorEventConnection;
86     class SensorDirectConnection;
87 
88 public:
89     enum UidState {
90       UID_STATE_ACTIVE = 0,
91       UID_STATE_IDLE,
92     };
93 
94     enum Mode {
95        // The regular operating mode where any application can register/unregister/call flush on
96        // sensors.
97        NORMAL = 0,
98        // This mode is only used for testing purposes. Not all HALs support this mode. In this mode,
99        // the HAL ignores the sensor data provided by physical sensors and accepts the data that is
100        // injected from the SensorService as if it were the real sensor data. This mode is primarily
101        // used for testing various algorithms like vendor provided SensorFusion, Step Counter and
102        // Step Detector etc. Typically in this mode, there will be a client (a
103        // SensorEventConnection) which will be injecting sensor data into the HAL. Normal apps can
104        // unregister and register for any sensor that supports injection. Registering to sensors
105        // that do not support injection will give an error.
106        DATA_INJECTION = 1,
107        // This mode is used only for testing sensors. Each sensor can be tested in isolation with
108        // the required sampling_rate and maxReportLatency parameters without having to think about
109        // the data rates requested by other applications. End user devices are always expected to be
110        // in NORMAL mode. When this mode is first activated, all active sensors from all connections
111        // are disabled. Calling flush() will return an error. In this mode, only the requests from
112        // selected apps whose package names are allowlisted are allowed (typically CTS apps).  Only
113        // these apps can register/unregister/call flush() on sensors. If SensorService switches to
114        // NORMAL mode again, all sensors that were previously registered to are activated with the
115        // corresponding parameters if the application hasn't unregistered for sensors in the mean
116        // time.  NOTE: Non allowlisted app whose sensors were previously deactivated may still
117        // receive events if a allowlisted app requests data from the same sensor.
118        RESTRICTED = 2,
119        // Mostly equivalent to DATA_INJECTION with the difference being that the injected data is
120        // delivered to all requesting apps rather than just the package allowed to inject data.
121        // This mode is only allowed to be used on development builds.
122        REPLAY_DATA_INJECTION = 3,
123 
124       // State Transitions supported.
125       //     RESTRICTED   <---  NORMAL   ---> DATA_INJECTION/REPLAY_DATA_INJECTION
126       //                  --->           <---
127 
128       // Shell commands to switch modes in SensorService.
129       // 1) Put SensorService in RESTRICTED mode with packageName .cts. If it is already in
130       // restricted mode it is treated as a NO_OP (and packageName is NOT changed).
131       //
132       //     $ adb shell dumpsys sensorservice restrict .cts.
133       //
134       // 2) Put SensorService in DATA_INJECTION mode with packageName .xts. If it is already in
135       // data_injection mode it is treated as a NO_OP (and packageName is NOT changed).
136       //
137       //     $ adb shell dumpsys sensorservice data_injection .xts.
138       //
139       // 3) Reset sensorservice back to NORMAL mode.
140       //     $ adb shell dumpsys sensorservice enable
141     };
142 
143     class ProximityActiveListener : public virtual RefBase {
144     public:
145         // Note that the callback is invoked from an async thread and can interact with the
146         // SensorService directly.
147         virtual void onProximityActive(bool isActive) = 0;
148     };
149 
150     class RuntimeSensorCallback : public virtual RefBase {
151     public:
152         // Note that the callback is invoked from an async thread and can interact with the
153         // SensorService directly.
154         virtual status_t onConfigurationChanged(int handle, bool enabled,
155                                                 int64_t samplingPeriodNanos,
156                                                 int64_t batchReportLatencyNanos) = 0;
157         virtual int onDirectChannelCreated(int fd) = 0;
158         virtual void onDirectChannelDestroyed(int channelHandle) = 0;
159         virtual int onDirectChannelConfigured(int channelHandle, int sensorHandle,
160                                               int rateLevel) = 0;
161     };
162 
getServiceName()163     static char const* getServiceName() ANDROID_API { return "sensorservice"; }
164     SensorService() ANDROID_API;
165 
166     void cleanupConnection(SensorEventConnection* connection);
167     void cleanupConnection(SensorDirectConnection* c);
168 
169     // Call with mLock held.
170     void checkAndReportProxStateChangeLocked();
171     void notifyProximityStateLocked(const bool isActive,
172                                     const std::vector<sp<ProximityActiveListener>>& listeners);
173 
174     status_t enable(const sp<SensorEventConnection>& connection, int handle,
175                     nsecs_t samplingPeriodNs,  nsecs_t maxBatchReportLatencyNs, int reservedFlags,
176                     const String16& opPackageName);
177 
178     status_t disable(const sp<SensorEventConnection>& connection, int handle);
179 
180     status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns,
181                           const String16& opPackageName);
182 
183     status_t flushSensor(const sp<SensorEventConnection>& connection,
184                          const String16& opPackageName);
185 
186     status_t addProximityActiveListener(const sp<ProximityActiveListener>& callback) ANDROID_API;
187     status_t removeProximityActiveListener(const sp<ProximityActiveListener>& callback) ANDROID_API;
188 
189     int registerRuntimeSensor(const sensor_t& sensor, int deviceId,
190                               sp<RuntimeSensorCallback> callback) ANDROID_API;
191     status_t unregisterRuntimeSensor(int handle) ANDROID_API;
192     status_t sendRuntimeSensorEvent(const sensors_event_t& event) ANDROID_API;
193 
194     int configureRuntimeSensorDirectChannel(int sensorHandle, const SensorDirectConnection* c,
195                                             const sensors_direct_cfg_t* config);
196 
197     // Returns true if a sensor should be throttled according to our rate-throttling rules.
198     static bool isSensorInCappedSet(int sensorType);
199 
200     virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args);
201 
202 private:
203     friend class BinderService<SensorService>;
204 
205     // nested class/struct for internal use
206     class ConnectionSafeAutolock;
207     class SensorConnectionHolder;
208     class SensorEventAckReceiver;
209     class SensorRecord;
210     class SensorRegistrationInfo;
211 
212     // Promoting a SensorEventConnection or SensorDirectConnection from wp to sp must be done with
213     // mLock held, but destroying that sp must be done unlocked to avoid a race condition that
214     // causes a deadlock (remote dies while we hold a local sp, then our decStrong() call invokes
215     // the dtor -> cleanupConnection() tries to re-lock the mutex). This class ensures safe usage
216     // by wrapping a Mutex::Autolock on SensorService's mLock, plus vectors that hold promoted sp<>
217     // references until the lock is released, when they are safely destroyed.
218     // All read accesses to the connection lists in mConnectionHolder must be done via this class.
219     class ConnectionSafeAutolock final {
220     public:
221         // Returns a list of non-null promoted connection references
222         const std::vector<sp<SensorEventConnection>>& getActiveConnections();
223         const std::vector<sp<SensorDirectConnection>>& getDirectConnections();
224 
225     private:
226         // Constructed via SensorConnectionHolder::lock()
227         friend class SensorConnectionHolder;
228         explicit ConnectionSafeAutolock(SensorConnectionHolder& holder, Mutex& mutex);
229         DISALLOW_IMPLICIT_CONSTRUCTORS(ConnectionSafeAutolock);
230 
231         // NOTE: Order of these members is important, as the destructor for non-static members
232         // get invoked in the reverse order of their declaration. Here we are relying on the
233         // Autolock to be destroyed *before* the vectors, so the sp<> objects are destroyed without
234         // the lock held, which avoids the deadlock.
235         SensorConnectionHolder& mConnectionHolder;
236         std::vector<std::vector<sp<SensorEventConnection>>> mReferencedActiveConnections;
237         std::vector<std::vector<sp<SensorDirectConnection>>> mReferencedDirectConnections;
238         Mutex::Autolock mAutolock;
239 
240         template<typename ConnectionType>
241         const std::vector<sp<ConnectionType>>& getConnectionsHelper(
242                 const SortedVector<wp<ConnectionType>>& connectionList,
243                 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder);
244     };
245 
246     // Encapsulates the collection of active SensorEventConection and SensorDirectConnection
247     // references. Write access is done through this class with mLock held, but all read access
248     // must be routed through ConnectionSafeAutolock.
249     class SensorConnectionHolder {
250     public:
251         void addEventConnectionIfNotPresent(const sp<SensorEventConnection>& connection);
252         void removeEventConnection(const wp<SensorEventConnection>& connection);
253 
254         void addDirectConnection(const sp<SensorDirectConnection>& connection);
255         void removeDirectConnection(const wp<SensorDirectConnection>& connection);
256 
257         // Pass in the mutex that protects this connection holder; acquires the lock and returns an
258         // object that can be used to safely read the lists of connections
259         ConnectionSafeAutolock lock(Mutex& mutex);
260 
261     private:
262         friend class ConnectionSafeAutolock;
263         SortedVector< wp<SensorEventConnection> > mActiveConnections;
264         SortedVector< wp<SensorDirectConnection> > mDirectConnections;
265     };
266 
267     // If accessing a sensor we need to make sure the UID has access to it. If
268     // the app UID is idle then it cannot access sensors and gets no trigger
269     // events, no on-change events, flush event behavior does not change, and
270     // recurring events are the same as the first one delivered in idle state
271     // emulating no sensor change. As soon as the app UID transitions to an
272     // active state we will start reporting events as usual and vise versa. This
273     // approach transparently handles observing sensors while the app UID transitions
274     // between idle/active state avoiding to get stuck in a state receiving sensor
275     // data while idle or not receiving sensor data while active.
276     class UidPolicy : public BnUidObserver {
277         public:
UidPolicy(wp<SensorService> service)278             explicit UidPolicy(wp<SensorService> service)
279                     : mService(service) {}
280             void registerSelf();
281             void unregisterSelf();
282 
283             bool isUidActive(uid_t uid);
284 
285             void onUidGone(uid_t uid, bool disabled) override;
286             void onUidActive(uid_t uid) override;
287             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)288             void onUidStateChanged(uid_t uid __unused, int32_t procState __unused,
289                                    int64_t procStateSeq __unused,
290                                    int32_t capability __unused) override {}
onUidProcAdjChanged(uid_t uid __unused,int32_t adj __unused)291             void onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) override {}
292 
293             void addOverrideUid(uid_t uid, bool active);
294             void removeOverrideUid(uid_t uid);
295         private:
296             bool isUidActiveLocked(uid_t uid);
297             void updateOverrideUid(uid_t uid, bool active, bool insert);
298 
299             Mutex mUidLock;
300             wp<SensorService> mService;
301             std::unordered_set<uid_t> mActiveUids;
302             std::unordered_map<uid_t, bool> mOverrideUids;
303     };
304 
305     bool isUidActive(uid_t uid);
306 
307     // Sensor privacy allows a user to disable access to all sensors on the device. When
308     // enabled sensor privacy will prevent all apps, including active apps, from accessing
309     // sensors, they will not receive trigger nor on-change events, flush event behavior
310     // does not change, and recurring events are the same as the first one delivered when
311     // sensor privacy was enabled. All sensor direct connections will be stopped as well
312     // and new direct connections will not be allowed while sensor privacy is enabled.
313     // Once sensor privacy is disabled access to sensors will be restored for active
314     // apps, previously stopped direct connections will be restarted, and new direct
315     // connections will be allowed again.
316     class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener {
317         public:
SensorPrivacyPolicy(wp<SensorService> service)318             explicit SensorPrivacyPolicy(wp<SensorService> service)
319                     : mService(service) {}
320             void registerSelf();
321             void unregisterSelf();
322 
323             bool isSensorPrivacyEnabled();
324 
325             binder::Status onSensorPrivacyChanged(int toggleType, int sensor,
326                                                   bool enabled);
327 
328         protected:
329             std::atomic_bool mSensorPrivacyEnabled;
330             wp<SensorService> mService;
331 
332         private:
333             Mutex mSensorPrivacyLock;
334     };
335 
336     class MicrophonePrivacyPolicy : public SensorPrivacyPolicy {
337         public:
MicrophonePrivacyPolicy(wp<SensorService> service)338             explicit MicrophonePrivacyPolicy(wp<SensorService> service)
339                     : SensorPrivacyPolicy(service) {}
340             void registerSelf();
341             void unregisterSelf();
342 
343             binder::Status onSensorPrivacyChanged(int toggleType, int sensor,
344                                                   bool enabled);
345     };
346 
347     // A class automatically clearing and restoring binder caller identity inside
348     // a code block (scoped variable).
349     // Declare one systematically before calling SensorPrivacyManager methods so that they are
350     // executed with the same level of privilege as the SensorService process.
351     class AutoCallerClear {
352         public:
AutoCallerClear()353             AutoCallerClear() :
354                 mToken(IPCThreadState::self()->clearCallingIdentity()) {}
~AutoCallerClear()355             ~AutoCallerClear() {
356                 IPCThreadState::self()->restoreCallingIdentity(mToken);
357             }
358 
359         private:
360             const int64_t mToken;
361     };
362 
363     static const char* WAKE_LOCK_NAME;
364     virtual ~SensorService();
365 
366     virtual void onFirstRef();
367 
368     // Thread interface
369     virtual bool threadLoop();
370 
371     // ISensorServer interface
372     virtual Vector<Sensor> getSensorList(const String16& opPackageName);
373     virtual Vector<Sensor> getDynamicSensorList(const String16& opPackageName);
374     virtual Vector<Sensor> getRuntimeSensorList(const String16& opPackageName, int deviceId);
375     virtual sp<ISensorEventConnection> createSensorEventConnection(
376             const String8& packageName,
377             int requestedMode, const String16& opPackageName, const String16& attributionTag);
378     virtual int isDataInjectionEnabled();
379     virtual sp<ISensorEventConnection> createSensorDirectConnection(const String16& opPackageName,
380             int deviceId, uint32_t size, int32_t type, int32_t format,
381             const native_handle *resource);
382     virtual int setOperationParameter(
383             int32_t handle, int32_t type, const Vector<float> &floats, const Vector<int32_t> &ints);
384     virtual status_t dump(int fd, const Vector<String16>& args);
385 
386     status_t dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const;
387     String8 getSensorName(int handle) const;
388     String8 getSensorStringType(int handle) const;
389     bool isVirtualSensor(int handle) const;
390     std::shared_ptr<SensorInterface> getSensorInterfaceFromHandle(int handle) const;
391     int getDeviceIdFromHandle(int handle) const;
392     bool isWakeUpSensor(int type) const;
393     void recordLastValueLocked(sensors_event_t const* buffer, size_t count);
394     static void sortEventBuffer(sensors_event_t* buffer, size_t count);
395     bool registerSensor(std::shared_ptr<SensorInterface> sensor, bool isDebug = false,
396                         bool isVirtual = false, int deviceId = RuntimeSensor::DEFAULT_DEVICE_ID);
397     bool registerVirtualSensor(std::shared_ptr<SensorInterface> sensor, bool isDebug = false);
398     bool registerDynamicSensorLocked(std::shared_ptr<SensorInterface> sensor, bool isDebug = false);
399     bool unregisterDynamicSensorLocked(int handle);
400     status_t cleanupWithoutDisable(const sp<SensorEventConnection>& connection, int handle);
401     status_t cleanupWithoutDisableLocked(const sp<SensorEventConnection>& connection, int handle);
402     void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
403             sensors_event_t const* buffer, const int count);
404     bool canAccessSensor(const Sensor& sensor, const char* operation,
405             const String16& opPackageName);
406     void addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
407             Vector<Sensor>& accessibleSensorList);
408     static bool hasPermissionForSensor(const Sensor& sensor);
409     static int getTargetSdkVersion(const String16& opPackageName);
410     static void resetTargetSdkVersionCache(const String16& opPackageName);
411     // Checks if the provided target operating mode is valid and returns the enum if it is.
412     static bool getTargetOperatingMode(const std::string &inputString, Mode *targetModeOut);
413     status_t changeOperatingMode(const Vector<String16>& args, Mode targetOperatingMode);
414     // SensorService acquires a partial wakelock for delivering events from wake up sensors. This
415     // method checks whether all the events from these wake up sensors have been delivered to the
416     // corresponding applications, if yes the wakelock is released.
417     void checkWakeLockState();
418     void checkWakeLockStateLocked(ConnectionSafeAutolock* connLock);
419     bool isWakeLockAcquired();
420     bool isWakeUpSensorEvent(const sensors_event_t& event) const;
421 
422     sp<Looper> getLooper() const;
423 
424     // Reset mWakeLockRefCounts for all SensorEventConnections to zero. This may happen if
425     // SensorService did not receive any acknowledgements from apps which have registered for
426     // wake_up sensors.
427     void resetAllWakeLockRefCounts();
428 
429     // Acquire or release wake_lock. If wake_lock is acquired, set the timeout in the looper to 5
430     // seconds and wake the looper.
431     void setWakeLockAcquiredLocked(bool acquire);
432 
433     // Send events from the event cache for this particular connection.
434     void sendEventsFromCache(const sp<SensorEventConnection>& connection);
435 
436     // If SensorService is operating in RESTRICTED mode, only select whitelisted packages are
437     // allowed to register for or call flush on sensors. Typically only cts test packages are
438     // allowed.
439     bool isAllowListedPackage(const String8& packageName);
440 
441     // Returns true if a connection with the specified opPackageName has no access to sensors
442     // in the RESTRICTED mode (i.e. the service is in RESTRICTED mode, and the package is not
443     // whitelisted). mLock must be held to invoke this method.
444     bool isOperationRestrictedLocked(const String16& opPackageName);
445 
446     status_t adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
447                                                     const String16& opPackageName);
448     status_t adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
449                                               const String16& opPackageName);
450     bool isRateCappedBasedOnPermission(const String16& opPackageName);
451     bool isPackageDebuggable(const String16& opPackageName);
452 
453     // Reset the state of SensorService to NORMAL mode.
454     status_t resetToNormalMode();
455     status_t resetToNormalModeLocked();
456 
457     // Transforms the UUIDs for all the sensors into proper IDs.
458     void makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const;
459     // Gets the appropriate ID from the given UUID.
460     int32_t getIdFromUuid(const Sensor::uuid_t &uuid) const;
461     // Either read from storage or create a new one.
462     static bool initializeHmacKey();
463 
464     // Enable SCHED_FIFO priority for thread
465     void enableSchedFifoMode();
466 
467     // Sets whether the given UID can get sensor data
468     void onUidStateChanged(uid_t uid, UidState state);
469 
470     // Returns true if a connection with the given uid and opPackageName
471     // currently has access to sensors.
472     bool hasSensorAccess(uid_t uid, const String16& opPackageName);
473     // Same as hasSensorAccess but with mLock held.
474     bool hasSensorAccessLocked(uid_t uid, const String16& opPackageName);
475 
476     // Overrides the UID state as if it is idle
477     status_t handleSetUidState(Vector<String16>& args, int err);
478     // Clears the override for the UID state
479     status_t handleResetUidState(Vector<String16>& args, int err);
480     // Gets the UID state
481     status_t handleGetUidState(Vector<String16>& args, int out, int err);
482     // Prints the shell command help
483     status_t printHelp(int out);
484 
485     // temporarily stops all active direct connections and disables all sensors
486     void disableAllSensors();
487     void disableAllSensorsLocked(ConnectionSafeAutolock* connLock);
488     // restarts the previously stopped direct connections and enables all sensors
489     void enableAllSensors();
490     void enableAllSensorsLocked(ConnectionSafeAutolock* connLock);
491 
492     // Caps active direct connections (when the mic toggle is flipped to on)
493     void capRates();
494     // Removes the capped rate on active direct connections (when the mic toggle is flipped to off)
495     void uncapRates();
496 
isAudioServerOrSystemServerUid(uid_t uid)497     static inline bool isAudioServerOrSystemServerUid(uid_t uid) {
498         return multiuser_get_app_id(uid) == AID_SYSTEM || uid == AID_AUDIOSERVER;
499     }
500 
501     static uint8_t sHmacGlobalKey[128];
502     static bool sHmacGlobalKeyIsValid;
503 
504     static std::atomic_uint64_t curProxCallbackSeq;
505     static std::atomic_uint64_t completedCallbackSeq;
506 
507     SensorServiceUtil::SensorList mSensors;
508     status_t mInitCheck;
509 
510     // Socket buffersize used to initialize BitTube. This size depends on whether batching is
511     // supported or not.
512     uint32_t mSocketBufferSize;
513     sp<Looper> mLooper;
514     sp<SensorEventAckReceiver> mAckReceiver;
515 
516     // protected by mLock
517     mutable Mutex mLock;
518     DefaultKeyedVector<int, SensorRecord*> mActiveSensors;
519     std::unordered_set<int> mActiveVirtualSensors;
520     SensorConnectionHolder mConnectionHolder;
521     bool mWakeLockAcquired;
522     sensors_event_t *mSensorEventBuffer, *mSensorEventScratch;
523     // WARNING: these SensorEventConnection instances must not be promoted to sp, except via
524     // modification to add support for them in ConnectionSafeAutolock
525     wp<const SensorEventConnection> * mMapFlushEventsToConnections;
526     std::unordered_map<int, SensorServiceUtil::RecentEventLogger*> mRecentEvent;
527     Mode mCurrentOperatingMode;
528     std::queue<sensors_event_t> mRuntimeSensorEventQueue;
529     std::unordered_map</*deviceId*/int, sp<RuntimeSensorCallback>> mRuntimeSensorCallbacks;
530 
531     // true if the head tracker sensor type is currently restricted to system usage only
532     // (can only be unrestricted for testing, via shell cmd)
533     bool mHtRestricted = true;
534 
535     // This packagaName is set when SensorService is in RESTRICTED or DATA_INJECTION mode. Only
536     // applications with this packageName are allowed to activate/deactivate or call flush on
537     // sensors. To run CTS this is can be set to ".cts." and only CTS tests will get access to
538     // sensors.
539     String8 mAllowListedPackage;
540 
541     int mNextSensorRegIndex;
542     Vector<SensorRegistrationInfo> mLastNSensorRegistrations;
543 
544     sp<UidPolicy> mUidPolicy;
545     sp<SensorPrivacyPolicy> mSensorPrivacyPolicy;
546 
547     static AppOpsManager sAppOpsManager;
548     static std::map<String16, int> sPackageTargetVersion;
549     static Mutex sPackageTargetVersionLock;
550     static String16 sSensorInterfaceDescriptorPrefix;
551 
552     sp<MicrophonePrivacyPolicy> mMicSensorPrivacyPolicy;
553 
554     // Keeps track of the handles of all proximity sensors in the system.
555     std::vector<int32_t> mProxSensorHandles;
556     // The last proximity sensor active state reported to listeners.
557     bool mLastReportedProxIsActive;
558     // Listeners subscribed to receive updates on the proximity sensor active state.
559     std::vector<sp<ProximityActiveListener>> mProximityActiveListeners;
560 };
561 
562 } // namespace android
563 #endif // ANDROID_SENSOR_SERVICE_H
564