blob: 60f9cd90c845eb384a2f81cabcd2153e2b9e3c8e [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 */
Brian Stack793f4642019-04-18 17:21:34 -070016#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080017#include <android/util/ProtoOutputStream.h>
18#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080019#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070021#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070022#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080023#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070024#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080025#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070026#include <cutils/properties.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070027#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070028#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080029#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070030#include <openssl/digest.h>
31#include <openssl/hmac.h>
32#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070033#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080034#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070035#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070036
Mathias Agopian787ac1b2012-09-18 18:49:18 -070037#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070038#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080039#include "GravitySensor.h"
40#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070041#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080042#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070043#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070044#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080045
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070047#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080049#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080050#include "SensorRecord.h"
51#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080052
Brian Stack51498e62018-10-03 10:52:21 -070053#include <ctime>
Peng Xueb4d6282015-12-10 18:02:41 -080054#include <inttypes.h>
55#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070056#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080057#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080058#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070059#include <sys/stat.h>
60#include <sys/types.h>
61#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070062
Svet Ganove752a5c2018-01-15 17:14:20 -080063#include <private/android_filesystem_config.h>
64
Mathias Agopianfc328812010-07-14 23:41:37 -070065namespace android {
66// ---------------------------------------------------------------------------
67
Mathias Agopian33015422011-05-27 18:18:13 -070068/*
69 * Notes:
70 *
71 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070072 * - run mag sensor from time to time to force calibration
73 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
74 *
75 */
76
Aravind Akella8ef3c892015-07-10 11:24:28 -070077const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070078uint8_t SensorService::sHmacGlobalKey[128] = {};
79bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070080std::map<String16, int> SensorService::sPackageTargetVersion;
81Mutex SensorService::sPackageTargetVersionLock;
82AppOpsManager SensorService::sAppOpsManager;
Greg Kaiser53ca2e02016-06-21 16:11:14 -070083
84#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
85#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070086#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070087
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070088// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070089static const String16 sDumpPermission("android.permission.DUMP");
90static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080091static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070092
Mathias Agopianfc328812010-07-14 23:41:37 -070093SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070094 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070095 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +090096 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -080097 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -070098}
99
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700100bool SensorService::initializeHmacKey() {
101 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
102 if (fd != -1) {
103 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
104 close(fd);
105 if (result == sizeof(sHmacGlobalKey)) {
106 return true;
107 }
108 ALOGW("Unable to read HMAC key; generating new one.");
109 }
110
111 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
112 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
113 return false;
114 }
115
116 // We need to make sure this is only readable to us.
117 bool wroteKey = false;
118 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
119 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
120 S_IRUSR|S_IWUSR);
121 if (fd != -1) {
122 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
123 close(fd);
124 wroteKey = (result == sizeof(sHmacGlobalKey));
125 }
126 if (wroteKey) {
127 ALOGI("Generated new HMAC key.");
128 } else {
129 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
130 "after reboot.");
131 }
132 // Even if we failed to write the key we return true, because we did
133 // initialize the HMAC key.
134 return true;
135}
136
Peng Xu98d30f62016-08-01 18:12:11 -0700137// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
138void SensorService::enableSchedFifoMode() {
139 struct sched_param param = {0};
140 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
141 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
142 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
143 }
144}
145
Peng Xu47e96012016-03-28 17:55:56 -0700146void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000147 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800148 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700149
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700150 sHmacGlobalKeyIsValid = initializeHmacKey();
151
Mathias Agopianf001c922010-11-11 17:58:51 -0800152 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800153 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700154 ssize_t count = dev.getSensorList(&list);
155 if (count > 0) {
156 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700157 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700158 uint32_t virtualSensorsNeeds =
159 (1<<SENSOR_TYPE_GRAVITY) |
160 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700161 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
162 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
163 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700164
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700165 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700166 bool useThisSensor=true;
167
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700168 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700169 case SENSOR_TYPE_ACCELEROMETER:
170 hasAccel = true;
171 break;
172 case SENSOR_TYPE_MAGNETIC_FIELD:
173 hasMag = true;
174 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700175 case SENSOR_TYPE_ORIENTATION:
176 orientationIndex = i;
177 break;
178 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700179 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700180 hasGyro = true;
181 break;
182 case SENSOR_TYPE_GRAVITY:
183 case SENSOR_TYPE_LINEAR_ACCELERATION:
184 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700185 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
186 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
187 if (IGNORE_HARDWARE_FUSION) {
188 useThisSensor = false;
189 } else {
190 virtualSensorsNeeds &= ~(1<<list[i].type);
191 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700192 break;
193 }
Peng Xuf66684a2015-07-23 11:41:53 -0700194 if (useThisSensor) {
195 registerSensor( new HardwareSensor(list[i]) );
196 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700197 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700198
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700199 // it's safe to instantiate the SensorFusion object here
200 // (it wants to be instantiated after h/w sensors have been
201 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700202 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700203
Aravind Akellaf5047892015-07-20 17:29:33 -0700204 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700205 // Add Android virtual sensors if they're not already
206 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700207 bool needRotationVector =
208 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700209
Peng Xu0cc8f802016-04-05 23:46:03 -0700210 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
211 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700212
Peng Xu0cc8f802016-04-05 23:46:03 -0700213 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700214 registerSensor( new CorrectedGyroSensor(list, count), true, true);
215 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700216 }
217
Peng Xuf66684a2015-07-23 11:41:53 -0700218 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700219 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
220 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700221
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800222 bool needLinearAcceleration =
223 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
224 registerSensor(new LinearAccelerationSensor(list, count),
225 !needLinearAcceleration, true);
226
Peng Xu0cc8f802016-04-05 23:46:03 -0700227 bool needGameRotationVector =
228 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
229 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700230 }
231
232 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700233 bool needGeoMagRotationVector =
234 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
235 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700236 }
237
Aravind Akella5466c3d2014-08-22 16:11:10 -0700238 // Check if the device really supports batching by looking at the FIFO event
239 // counts for each sensor.
240 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700241 mSensors.forEachSensor(
242 [&batchingSupported] (const Sensor& s) -> bool {
243 if (s.getFifoMaxEventCount() > 0) {
244 batchingSupported = true;
245 }
246 return !batchingSupported;
247 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700248
249 if (batchingSupported) {
250 // Increase socket buffer size to a max of 100 KB for batching capabilities.
251 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
252 } else {
253 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
254 }
255
256 // Compare the socketBufferSize value against the system limits and limit
257 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700258 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
259 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700260 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700261 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700262 size_t maxSystemSocketBufferSize;
263 sscanf(line, "%zu", &maxSystemSocketBufferSize);
264 if (mSocketBufferSize > maxSystemSocketBufferSize) {
265 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700266 }
267 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700268 if (fp) {
269 fclose(fp);
270 }
271
Aravind Akella9a844cf2014-02-11 18:58:52 -0800272 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700273 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700274 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
275 mSensorEventBuffer = new sensors_event_t[minBufferSize];
276 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700277 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700278 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700279
Aravind Akella18d6d512015-06-18 14:18:28 -0700280 mNextSensorRegIndex = 0;
281 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
282 mLastNSensorRegistrations.push();
283 }
284
285 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700286 mAckReceiver = new SensorEventAckReceiver(this);
287 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700288 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700289
290 // priority can only be changed after run
291 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800292
293 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800294 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800295
296 // Start watching sensor privacy changes
297 mSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800298 }
299 }
300}
301
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700302void SensorService::onUidStateChanged(uid_t uid, UidState state) {
303 SensorDevice& dev(SensorDevice::getInstance());
304
Brian Duddie967ce172019-06-10 11:08:27 -0700305 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700306 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700307 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700308 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700309 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700310 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700311
312 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
313 if (conn->getUid() == uid) {
314 // Update sensor subscriptions if needed
315 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
316 conn->onSensorAccessChanged(hasAccess);
317 }
318 }
319}
320
321bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
322 Mutex::Autolock _l(mLock);
323 return hasSensorAccessLocked(uid, opPackageName);
324}
325
326bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
327 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
328 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700329}
330
Peng Xu0cc8f802016-04-05 23:46:03 -0700331const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
332 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800333 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700334 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700335 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700336 return s->getSensor();
337 } else {
338 return mSensors.getNonSensor();
339 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800340}
341
Peng Xu6a2d3a02015-12-21 12:00:23 -0800342const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700343 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800344}
345
Peng Xu6a2d3a02015-12-21 12:00:23 -0800346bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700347 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800348
349 const auto i = mRecentEvent.find(handle);
350 if (i != mRecentEvent.end()) {
351 delete i->second;
352 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800353 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700354 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800355}
356
Peng Xu0cc8f802016-04-05 23:46:03 -0700357const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
358 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700359}
360
Peng Xu47e96012016-03-28 17:55:56 -0700361SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800362 for (auto && entry : mRecentEvent) {
363 delete entry.second;
364 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800365 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800366 mSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700367}
368
369status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700370 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700371 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800372 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700373 IPCThreadState::self()->getCallingPid(),
374 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700375 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700376 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700377 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800378 return INVALID_OPERATION;
379 }
Brian Duddie967ce172019-06-10 11:08:27 -0700380 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800381 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700382 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700383 // If already in restricted mode. Ignore.
384 if (mCurrentOperatingMode == RESTRICTED) {
385 return status_t(NO_ERROR);
386 }
387 // If in any mode other than normal, ignore.
388 if (mCurrentOperatingMode != NORMAL) {
389 return INVALID_OPERATION;
390 }
Peng Xue36e3472016-11-03 11:57:10 -0700391
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700392 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800393 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700394 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700395 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700396 return status_t(NO_ERROR);
397 } else if (args.size() == 1 && args[0] == String16("enable")) {
398 // If currently in restricted mode, reset back to NORMAL mode else ignore.
399 if (mCurrentOperatingMode == RESTRICTED) {
400 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800401 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700402 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700403 }
Aravind Akella841a5922015-06-29 12:37:48 -0700404 if (mCurrentOperatingMode == DATA_INJECTION) {
405 resetToNormalModeLocked();
406 }
407 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700408 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700409 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
410 if (mCurrentOperatingMode == NORMAL) {
411 dev.disableAllSensors();
412 status_t err = dev.setMode(DATA_INJECTION);
413 if (err == NO_ERROR) {
414 mCurrentOperatingMode = DATA_INJECTION;
415 } else {
416 // Re-enable sensors.
417 dev.enableAllSensors();
418 }
419 mWhiteListedPackage.setTo(String8(args[1]));
420 return NO_ERROR;
421 } else if (mCurrentOperatingMode == DATA_INJECTION) {
422 // Already in DATA_INJECTION mode. Treat this as a no_op.
423 return NO_ERROR;
424 } else {
425 // Transition to data injection mode supported only from NORMAL mode.
426 return INVALID_OPERATION;
427 }
Mike Ma24743862020-01-29 00:36:55 -0800428 } else if (args.size() == 1 && args[0] == String16("--proto")) {
429 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700430 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700431 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700432 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700433 } else {
434 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700435 //
Brian Stack51498e62018-10-03 10:52:21 -0700436 timespec curTime;
437 clock_gettime(CLOCK_REALTIME, &curTime);
438 struct tm* timeinfo = localtime(&(curTime.tv_sec));
439 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
440 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800441 result.append("Sensor Device:\n");
442 result.append(SensorDevice::getInstance().dump().c_str());
443
444 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700445 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700446
Peng Xu6a2d3a02015-12-21 12:00:23 -0800447 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700448 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700449
Peng Xu0cc8f802016-04-05 23:46:03 -0700450 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800451 for (auto&& i : mRecentEvent) {
452 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700453 if (!i.second->isEmpty()) {
454 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
455 i.second->setFormat("normal");
456 } else {
457 i.second->setFormat("mask_data");
458 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800459 // if there is events and sensor does not need special permission.
460 result.appendFormat("%s: ", s->getSensor().getName().string());
461 result.append(i.second->dump().c_str());
462 }
463 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700464
Aravind Akella444f2672015-05-07 12:40:52 -0700465 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700466 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700467 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
468 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700469 if (dev.isSensorActive(handle)) {
470 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
471 getSensorName(handle).string(),
472 handle,
473 mActiveSensors.valueAt(i)->getNumConnections());
474 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700475 }
476
Andreas Gamped4036b62015-07-28 13:49:04 -0700477 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700478 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700479 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
480 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700481 result.appendFormat("Mode :");
482 switch(mCurrentOperatingMode) {
483 case NORMAL:
484 result.appendFormat(" NORMAL\n");
485 break;
486 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700487 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700488 break;
489 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700490 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700491 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800492 result.appendFormat("Sensor Privacy: %s\n",
493 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700494
Brian Duddie967ce172019-06-10 11:08:27 -0700495 const auto& activeConnections = connLock.getActiveConnections();
496 result.appendFormat("%zd active connections\n", activeConnections.size());
497 for (size_t i=0 ; i < activeConnections.size() ; i++) {
498 result.appendFormat("Connection Number: %zu \n", i);
499 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700500 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700501
Brian Duddie967ce172019-06-10 11:08:27 -0700502 const auto& directConnections = connLock.getDirectConnections();
503 result.appendFormat("%zd direct connections\n", directConnections.size());
504 for (size_t i = 0 ; i < directConnections.size() ; i++) {
505 result.appendFormat("Direct connection %zu:\n", i);
506 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700507 }
508
Aravind Akella18d6d512015-06-18 14:18:28 -0700509 result.appendFormat("Previous Registrations:\n");
510 // Log in the reverse chronological order.
511 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
512 SENSOR_REGISTRATIONS_BUF_SIZE;
513 const int startIndex = currentIndex;
514 do {
515 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
516 if (SensorRegistrationInfo::isSentinel(reg_info)) {
517 // Ignore sentinel, proceed to next item.
518 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
519 SENSOR_REGISTRATIONS_BUF_SIZE;
520 continue;
521 }
Peng Xu51224682017-03-10 16:57:27 -0800522 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700523 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
524 SENSOR_REGISTRATIONS_BUF_SIZE;
525 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700526 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700527 }
528 write(fd, result.string(), result.size());
529 return NO_ERROR;
530}
531
Mike Ma24743862020-01-29 00:36:55 -0800532/**
533 * Dump debugging information as android.service.SensorServiceProto protobuf message using
534 * ProtoOutputStream.
535 *
536 * See proto definition and some notes about ProtoOutputStream in
537 * frameworks/base/core/proto/android/service/sensor_service.proto
538 */
539status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
540 using namespace service::SensorServiceProto;
541 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800542 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
543 if (!mSensors.hasAnySensor()) {
544 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
545 }
Mike Ma24743862020-01-29 00:36:55 -0800546 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
547
548 timespec curTime;
549 clock_gettime(CLOCK_REALTIME, &curTime);
550 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
551
552 // Write SensorDeviceProto
553 uint64_t token = proto.start(SENSOR_DEVICE);
554 SensorDevice::getInstance().dump(&proto);
555 proto.end(token);
556
557 // Write SensorListProto
558 token = proto.start(SENSORS);
559 mSensors.dump(&proto);
560 proto.end(token);
561
562 // Write SensorFusionProto
563 token = proto.start(FUSION_STATE);
564 SensorFusion::getInstance().dump(&proto);
565 proto.end(token);
566
567 // Write SensorEventsProto
568 token = proto.start(SENSOR_EVENTS);
569 for (auto&& i : mRecentEvent) {
570 sp<SensorInterface> s = mSensors.getInterface(i.first);
571 if (!i.second->isEmpty()) {
572 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
573 "normal" : "mask_data");
574 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
575 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
576 std::string(s->getSensor().getName().string()));
577 i.second->dump(&proto);
578 proto.end(mToken);
579 }
580 }
581 proto.end(token);
582
583 // Write ActiveSensorProto
584 SensorDevice& dev = SensorDevice::getInstance();
585 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
586 int handle = mActiveSensors.keyAt(i);
587 if (dev.isSensorActive(handle)) {
588 token = proto.start(ACTIVE_SENSORS);
589 proto.write(service::ActiveSensorProto::NAME,
590 std::string(getSensorName(handle).string()));
591 proto.write(service::ActiveSensorProto::HANDLE, handle);
592 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
593 int(mActiveSensors.valueAt(i)->getNumConnections()));
594 proto.end(token);
595 }
596 }
597
598 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
599 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
600 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
601
602 switch(mCurrentOperatingMode) {
603 case NORMAL:
604 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
605 break;
606 case RESTRICTED:
607 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
608 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
609 break;
610 case DATA_INJECTION:
611 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
612 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
613 break;
614 default:
615 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
616 }
617 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
618
619 // Write repeated SensorEventConnectionProto
620 const auto& activeConnections = connLock->getActiveConnections();
621 for (size_t i = 0; i < activeConnections.size(); i++) {
622 token = proto.start(ACTIVE_CONNECTIONS);
623 activeConnections[i]->dump(&proto);
624 proto.end(token);
625 }
626
627 // Write repeated SensorDirectConnectionProto
628 const auto& directConnections = connLock->getDirectConnections();
629 for (size_t i = 0 ; i < directConnections.size() ; i++) {
630 token = proto.start(DIRECT_CONNECTIONS);
631 directConnections[i]->dump(&proto);
632 proto.end(token);
633 }
634
635 // Write repeated SensorRegistrationInfoProto
636 const int startIndex = mNextSensorRegIndex;
637 int curr = startIndex;
638 do {
639 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
640 if (SensorRegistrationInfo::isSentinel(reg_info)) {
641 // Ignore sentinel, proceed to next item.
642 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
643 continue;
644 }
645 token = proto.start(PREVIOUS_REGISTRATIONS);
646 reg_info.dump(&proto);
647 proto.end(token);
648 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
649 } while (startIndex != curr);
650
651 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
652}
653
Michael Groover5e1f60b2018-12-04 22:34:29 -0800654void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700655 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
656 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800657}
658
Brian Duddie967ce172019-06-10 11:08:27 -0700659void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800660 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700661 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
662 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
663 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800664 }
665 dev.disableAllSensors();
666 // Clear all pending flush connections for all active sensors. If one of the active
667 // connections has called flush() and the underlying sensor has been disabled before a
668 // flush complete event is returned, we need to remove the connection from this queue.
669 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
670 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
671 }
672}
673
674void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700675 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
676 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800677}
678
Brian Duddie967ce172019-06-10 11:08:27 -0700679void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800680 // sensors should only be enabled if the operating state is not restricted and sensor
681 // privacy is not enabled.
682 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
683 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
684 mCurrentOperatingMode,
685 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
686 return;
687 }
688 SensorDevice& dev(SensorDevice::getInstance());
689 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700690 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
691 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
692 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800693 }
694}
695
Brian Duddie967ce172019-06-10 11:08:27 -0700696
Svet Ganove752a5c2018-01-15 17:14:20 -0800697// NOTE: This is a remote API - make sure all args are validated
698status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
699 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
700 return PERMISSION_DENIED;
701 }
702 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
703 return BAD_VALUE;
704 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700705 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800706 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700707 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800708 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700709 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800710 return handleGetUidState(args, out, err);
711 } else if (args.size() == 1 && args[0] == String16("help")) {
712 printHelp(out);
713 return NO_ERROR;
714 }
715 printHelp(err);
716 return BAD_VALUE;
717}
718
Tanmay Patild33a1822019-04-11 18:38:55 -0700719static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800720 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700721 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800722 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700723 ALOGE("Unknown package: '%s'", String8(packageName).string());
724 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800725 return BAD_VALUE;
726 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700727
728 if (userId < 0) {
729 ALOGE("Invalid user: %d", userId);
730 dprintf(err, "Invalid user: %d\n", userId);
731 return BAD_VALUE;
732 }
733
734 uid = multiuser_get_uid(userId, uid);
735 return NO_ERROR;
736}
737
738status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
739 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
740 if (!(args.size() == 3 || args.size() == 5)) {
741 printHelp(err);
742 return BAD_VALUE;
743 }
744
Svet Ganove752a5c2018-01-15 17:14:20 -0800745 bool active = false;
746 if (args[2] == String16("active")) {
747 active = true;
748 } else if ((args[2] != String16("idle"))) {
749 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
750 return BAD_VALUE;
751 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700752
753 int userId = 0;
754 if (args.size() == 5 && args[3] == String16("--user")) {
755 userId = atoi(String8(args[4]));
756 }
757
758 uid_t uid;
759 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
760 return BAD_VALUE;
761 }
762
Svet Ganove752a5c2018-01-15 17:14:20 -0800763 mUidPolicy->addOverrideUid(uid, active);
764 return NO_ERROR;
765}
766
767status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700768 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
769 if (!(args.size() == 2 || args.size() == 4)) {
770 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800771 return BAD_VALUE;
772 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700773
774 int userId = 0;
775 if (args.size() == 4 && args[2] == String16("--user")) {
776 userId = atoi(String8(args[3]));
777 }
778
779 uid_t uid;
780 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
781 return BAD_VALUE;
782 }
783
Svet Ganove752a5c2018-01-15 17:14:20 -0800784 mUidPolicy->removeOverrideUid(uid);
785 return NO_ERROR;
786}
787
788status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700789 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
790 if (!(args.size() == 2 || args.size() == 4)) {
791 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800792 return BAD_VALUE;
793 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700794
795 int userId = 0;
796 if (args.size() == 4 && args[2] == String16("--user")) {
797 userId = atoi(String8(args[3]));
798 }
799
800 uid_t uid;
801 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
802 return BAD_VALUE;
803 }
804
Svet Ganove752a5c2018-01-15 17:14:20 -0800805 if (mUidPolicy->isUidActive(uid)) {
806 return dprintf(out, "active\n");
807 } else {
808 return dprintf(out, "idle\n");
809 }
810}
811
812status_t SensorService::printHelp(int out) {
813 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700814 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
815 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
816 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800817 " help print this message\n");
818}
819
Peng Xu0cc8f802016-04-05 23:46:03 -0700820//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800821void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700822 sensors_event_t const* buffer, const int count) {
823 for (int i=0 ; i<count ; i++) {
824 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700825 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
826 handle = buffer[i].meta_data.sensor;
827 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700828 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700829 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700830 // If this buffer has an event from a one_shot sensor and this connection is registered
831 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700832 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700833 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
834 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800835 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700836 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700837
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700838 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700839 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700840}
841
Peng Xu47e96012016-03-28 17:55:56 -0700842bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000843 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700844
Peng Xueb4d6282015-12-10 18:02:41 -0800845 // each virtual sensor could generate an event per "real" event, that's why we need to size
846 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
847 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700848 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700849 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700850 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700851
Mathias Agopianf001c922010-11-11 17:58:51 -0800852 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700853
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700854 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700855 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700856 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
857 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700858 if(count == DEAD_OBJECT && device.isReconnecting()) {
859 device.reconnect();
860 continue;
861 } else {
862 ALOGE("sensor poll failed (%s)", strerror(-count));
863 break;
864 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700865 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700866
867 // Reset sensors_event_t.flags to zero for all events in the buffer.
868 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700869 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700870 }
Brian Duddie967ce172019-06-10 11:08:27 -0700871 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700872
Aravind Akella9a844cf2014-02-11 18:58:52 -0800873 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
874 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
875 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
876 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
877 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700878 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700879 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700880 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700881 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700882 }
883 }
884
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700885 if (wakeEvents > 0) {
886 if (!mWakeLockAcquired) {
887 setWakeLockAcquiredLocked(true);
888 }
889 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800890 }
Aravind Akella8493b792014-09-08 15:45:47 -0700891 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800892
Mathias Agopianf001c922010-11-11 17:58:51 -0800893 // handle virtual sensors
894 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700895 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700896 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800897 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700898 SensorFusion& fusion(SensorFusion::getInstance());
899 if (fusion.isEnabled()) {
900 for (size_t i=0 ; i<size_t(count) ; i++) {
901 fusion.process(event[i]);
902 }
903 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700904 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700905 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700906 if (count + k >= minBufferSize) {
907 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700908 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700909 count, k, minBufferSize);
910 break;
911 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800912 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700913 sp<SensorInterface> si = mSensors.getInterface(handle);
914 if (si == nullptr) {
915 ALOGE("handle %d is not an valid virtual sensor", handle);
916 continue;
917 }
918
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700919 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700920 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800921 k++;
922 }
923 }
924 }
925 if (k) {
926 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700927 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800928 count += k;
929 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700930 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700931 }
932 }
933 }
934
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700935 // handle backward compatibility for RotationVector sensor
936 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
937 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700938 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700939 // All the 4 components of the quaternion should be available
940 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700941 mSensorEventBuffer[i].data[4] = -1;
942 }
943 }
944 }
945
Brian Duddie967ce172019-06-10 11:08:27 -0700946 // Cache the list of active connections, since we use it in multiple places below but won't
947 // modify it here
948 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
949
Aravind Akella8493b792014-09-08 15:45:47 -0700950 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700951 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
952 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
953 // SensorEventConnection mapped to the corresponding flush_complete_event in
954 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700955 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700956 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
957 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
958 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700959 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700960 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
961 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700962 }
963 }
Peng Xu2576cb62016-01-20 00:22:09 -0800964
965 // handle dynamic sensor meta events, process registration and unregistration of dynamic
966 // sensor based on content of event.
967 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
968 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
969 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
970 const sensor_t& dynamicSensor =
971 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
972 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
973 handle, dynamicSensor.type, dynamicSensor.name);
974
Peng Xu0cc8f802016-04-05 23:46:03 -0700975 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800976 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700977 sensor_t s = dynamicSensor;
978 // make sure the dynamic sensor flag is set
979 s.flags |= DYNAMIC_SENSOR_MASK;
980 // force the handle to be consistent
981 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800982
983 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800984
Peng Xu0cc8f802016-04-05 23:46:03 -0700985 // This will release hold on dynamic sensor meta, so it should be called
986 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700987 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800988 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700989 } else {
990 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
991 }
Peng Xu2576cb62016-01-20 00:22:09 -0800992 } else {
993 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
994 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
995
996 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800997 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800998 ALOGE("Dynamic sensor release error.");
999 }
1000
Brian Duddie967ce172019-06-10 11:08:27 -07001001 for (const sp<SensorEventConnection>& connection : activeConnections) {
1002 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001003 }
1004 }
1005 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001006 }
1007
Aravind Akella9a844cf2014-02-11 18:58:52 -08001008 // Send our events to clients. Check the state of wake lock for each client and release the
1009 // lock if none of the clients need it.
1010 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001011 for (const sp<SensorEventConnection>& connection : activeConnections) {
1012 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1013 mMapFlushEventsToConnections);
1014 needsWakeLock |= connection->needsWakeLock();
1015 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1016 // Early check for one-shot sensors.
1017 if (connection->hasOneShotSensors()) {
1018 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001019 }
1020 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001021
Aravind Akella9a844cf2014-02-11 18:58:52 -08001022 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001023 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001024 }
Aravind Akella8493b792014-09-08 15:45:47 -07001025 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001026
Steve Block3c20fbe2012-01-05 23:22:43 +00001027 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001028 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001029 return false;
1030}
1031
Aravind Akella56ae4262014-07-10 16:01:10 -07001032sp<Looper> SensorService::getLooper() const {
1033 return mLooper;
1034}
1035
Aravind Akellab4373ac2014-10-29 17:55:20 -07001036void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001037 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1038 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1039 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001040 }
Brian Duddie967ce172019-06-10 11:08:27 -07001041 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001042}
1043
1044void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1045 if (acquire) {
1046 if (!mWakeLockAcquired) {
1047 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1048 mWakeLockAcquired = true;
1049 }
1050 mLooper->wake();
1051 } else {
1052 if (mWakeLockAcquired) {
1053 release_wake_lock(WAKE_LOCK_NAME);
1054 mWakeLockAcquired = false;
1055 }
1056 }
1057}
1058
Aravind Akellab4373ac2014-10-29 17:55:20 -07001059bool SensorService::isWakeLockAcquired() {
1060 Mutex::Autolock _l(mLock);
1061 return mWakeLockAcquired;
1062}
1063
Aravind Akella56ae4262014-07-10 16:01:10 -07001064bool SensorService::SensorEventAckReceiver::threadLoop() {
1065 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001066 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001067 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001068 bool wakeLockAcquired = mService->isWakeLockAcquired();
1069 int timeout = -1;
1070 if (wakeLockAcquired) timeout = 5000;
1071 int ret = looper->pollOnce(timeout);
1072 if (ret == ALOOPER_POLL_TIMEOUT) {
1073 mService->resetAllWakeLockRefCounts();
1074 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001075 } while(!Thread::exitPending());
1076 return false;
1077}
1078
Aravind Akella9a844cf2014-02-11 18:58:52 -08001079void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001080 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001081 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001082 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1083 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001084 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001085 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001086 }
Peng Xu2576cb62016-01-20 00:22:09 -08001087
Peng Xu6a2d3a02015-12-21 12:00:23 -08001088 auto logger = mRecentEvent.find(buffer[i].sensor);
1089 if (logger != mRecentEvent.end()) {
1090 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001091 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001092 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001093}
1094
Peng Xu47e96012016-03-28 17:55:56 -07001095void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001096 struct compar {
1097 static int cmp(void const* lhs, void const* rhs) {
1098 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1099 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001100 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001101 }
1102 };
1103 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1104}
1105
Mathias Agopian5d270722010-07-19 15:20:39 -07001106String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001107 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001108}
1109
Aravind Akellab4099e72013-10-15 15:43:10 -07001110bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001111 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1112 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001113}
1114
Aravind Akella9a844cf2014-02-11 18:58:52 -08001115bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001116 int handle = event.sensor;
1117 if (event.type == SENSOR_TYPE_META_DATA) {
1118 handle = event.meta_data.sensor;
1119 }
Peng Xu755c4512016-04-07 23:15:14 -07001120 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1121 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001122}
1123
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001124int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1125 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1126 // UUID is not supported for this device.
1127 return 0;
1128 }
1129 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1130 // This sensor can be uniquely identified in the system by
1131 // the combination of its type and name.
1132 return -1;
1133 }
1134
1135 // We have a dynamic sensor.
1136
1137 if (!sHmacGlobalKeyIsValid) {
1138 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1139 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1140 return 0;
1141 }
1142
1143 // We want each app author/publisher to get a different ID, so that the
1144 // same dynamic sensor cannot be tracked across apps by multiple
1145 // authors/publishers. So we use both our UUID and our User ID.
1146 // Note potential confusion:
1147 // UUID => Universally Unique Identifier.
1148 // UID => User Identifier.
1149 // We refrain from using "uid" except as needed by API to try to
1150 // keep this distinction clear.
1151
1152 auto appUserId = IPCThreadState::self()->getCallingUid();
1153 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1154 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1155 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1156
1157 // Now we use our key on our UUID/app combo to get the hash.
1158 uint8_t hash[EVP_MAX_MD_SIZE];
1159 unsigned int hashLen;
1160 if (HMAC(EVP_sha256(),
1161 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1162 uuidAndApp, sizeof(uuidAndApp),
1163 hash, &hashLen) == nullptr) {
1164 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1165 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1166 return 0;
1167 }
1168
1169 int32_t id = 0;
1170 if (hashLen < sizeof(id)) {
1171 // We never expect this case, but out of paranoia, we handle it.
1172 // Our 'id' length is already quite small, we don't want the
1173 // effective length of it to be even smaller.
1174 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1175 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1176 return 0;
1177 }
1178
1179 // This is almost certainly less than all of 'hash', but it's as secure
1180 // as we can be with our current 'id' length.
1181 memcpy(&id, hash, sizeof(id));
1182
1183 // Note at the beginning of the function that we return the values of
1184 // 0 and -1 to represent special cases. As a result, we can't return
1185 // those as dynamic sensor IDs. If we happened to hash to one of those
1186 // values, we change 'id' so we report as a dynamic sensor, and not as
1187 // one of those special cases.
1188 if (id == -1) {
1189 id = -2;
1190 } else if (id == 0) {
1191 id = 1;
1192 }
1193 return id;
1194}
1195
1196void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1197 for (auto &sensor : sensorList) {
1198 int32_t id = getIdFromUuid(sensor.getUuid());
1199 sensor.setId(id);
1200 }
1201}
1202
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001203Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001204 char value[PROPERTY_VALUE_MAX];
1205 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001206 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001207 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001208 Vector<Sensor> accessibleSensorList;
1209 for (size_t i = 0; i < initialSensorList.size(); i++) {
1210 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001211 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001212 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001213 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001214 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001215}
1216
Peng Xu47e96012016-03-28 17:55:56 -07001217Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001218 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001219 mSensors.forEachSensor(
1220 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001221 if (sensor.isDynamicSensor()) {
1222 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1223 accessibleSensorList.add(sensor);
1224 } else {
1225 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1226 sensor.getName().string(),
1227 sensor.getRequiredPermission().string(),
1228 sensor.getRequiredAppOp());
1229 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001230 }
1231 return true;
1232 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001233 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001234 return accessibleSensorList;
1235}
1236
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001237sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001238 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001239 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1240 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001241 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001242 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001243
1244 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001245 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1246 // operating in DI mode.
1247 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001248 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1249 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001250 }
1251
Mathias Agopian5307d172012-09-18 17:02:43 -07001252 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001253 pid_t pid = IPCThreadState::self()->getCallingPid();
1254
1255 String8 connPackageName =
1256 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1257 String16 connOpPackageName =
1258 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1259 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001260 requestedMode == DATA_INJECTION, connOpPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001261 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001262 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001263 // Add the associated file descriptor to the Looper for polling whenever there is data to
1264 // be injected.
1265 result->updateLooperRegistration(mLooper);
1266 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001267 return result;
1268}
1269
Aravind Akella841a5922015-06-29 12:37:48 -07001270int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001271 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001272 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001273}
1274
Peng Xue36e3472016-11-03 11:57:10 -07001275sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1276 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1277 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001278 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001279
Michael Groover5e1f60b2018-12-04 22:34:29 -08001280 // No new direct connections are allowed when sensor privacy is enabled
1281 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1282 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1283 return nullptr;
1284 }
1285
Peng Xue36e3472016-11-03 11:57:10 -07001286 struct sensors_direct_mem_t mem = {
1287 .type = type,
1288 .format = format,
1289 .size = size,
1290 .handle = resource,
1291 };
1292 uid_t uid = IPCThreadState::self()->getCallingUid();
1293
1294 if (mem.handle == nullptr) {
1295 ALOGE("Failed to clone resource handle");
1296 return nullptr;
1297 }
1298
1299 // check format
1300 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1301 ALOGE("Direct channel format %d is unsupported!", format);
1302 return nullptr;
1303 }
1304
1305 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001306 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1307 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001308 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001309 return nullptr;
1310 }
1311 }
1312
1313 // check specific to memory type
1314 switch(type) {
1315 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001316 if (resource->numFds < 1) {
1317 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1318 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1319 return nullptr;
1320 }
Peng Xue36e3472016-11-03 11:57:10 -07001321 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001322 if (!ashmem_valid(fd)) {
1323 ALOGE("Supplied Ashmem memory region is invalid");
1324 return nullptr;
1325 }
1326
Peng Xue36e3472016-11-03 11:57:10 -07001327 int size2 = ashmem_get_size_region(fd);
1328 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001329 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001330 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1331 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001332 return nullptr;
1333 }
1334 break;
1335 }
1336 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001337 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001338 break;
1339 default:
1340 ALOGE("Unknown direct connection memory type %d", type);
1341 return nullptr;
1342 }
1343
1344 native_handle_t *clone = native_handle_clone(resource);
1345 if (!clone) {
1346 return nullptr;
1347 }
1348
Brian Duddie967ce172019-06-10 11:08:27 -07001349 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001350 SensorDevice& dev(SensorDevice::getInstance());
1351 int channelHandle = dev.registerDirectChannel(&mem);
1352
1353 if (channelHandle <= 0) {
1354 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1355 } else {
1356 mem.handle = clone;
1357 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1358 }
1359
1360 if (conn == nullptr) {
1361 native_handle_close(clone);
1362 native_handle_delete(clone);
1363 } else {
1364 // add to list of direct connections
1365 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001366 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001367 }
1368 return conn;
1369}
1370
Peng Xudd5c5cb2017-03-16 17:39:43 -07001371int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001372 int32_t handle, int32_t type,
1373 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001374 Mutex::Autolock _l(mLock);
1375
Alexey Polyudov88711e82017-05-23 19:54:04 -07001376 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001377 return PERMISSION_DENIED;
1378 }
1379
1380 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001381 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001382 size_t expectSize = INT32_MAX;
1383 switch (type) {
1384 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1385 isFloat = true;
1386 expectSize = 3;
1387 break;
1388 case AINFO_LOCAL_GRAVITY:
1389 isFloat = true;
1390 expectSize = 1;
1391 break;
1392 case AINFO_DOCK_STATE:
1393 case AINFO_HIGH_PERFORMANCE_MODE:
1394 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1395 isFloat = false;
1396 expectSize = 1;
1397 break;
1398 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001399 // CUSTOM events must only contain float data; it may have variable size
1400 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1401 ints.size() ||
1402 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1403 handle < 0) {
1404 return BAD_VALUE;
1405 }
1406 isFloat = true;
1407 isCustom = true;
1408 expectSize = floats.size();
1409 break;
1410 }
1411
1412 if (!isCustom && handle != -1) {
1413 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001414 }
1415
1416 // three events: first one is begin tag, last one is end tag, the one in the middle
1417 // is the payload.
1418 sensors_event_t event[3];
1419 int64_t timestamp = elapsedRealtimeNano();
1420 for (sensors_event_t* i = event; i < event + 3; i++) {
1421 *i = (sensors_event_t) {
1422 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001423 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001424 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1425 .timestamp = timestamp++,
1426 .additional_info = (additional_info_event_t) {
1427 .serial = 0
1428 }
1429 };
1430 }
1431
1432 event[0].additional_info.type = AINFO_BEGIN;
1433 event[1].additional_info.type = type;
1434 event[2].additional_info.type = AINFO_END;
1435
1436 if (isFloat) {
1437 if (floats.size() != expectSize) {
1438 return BAD_VALUE;
1439 }
1440 for (size_t i = 0; i < expectSize; ++i) {
1441 event[1].additional_info.data_float[i] = floats[i];
1442 }
1443 } else {
1444 if (ints.size() != expectSize) {
1445 return BAD_VALUE;
1446 }
1447 for (size_t i = 0; i < expectSize; ++i) {
1448 event[1].additional_info.data_int32[i] = ints[i];
1449 }
1450 }
1451
1452 SensorDevice& dev(SensorDevice::getInstance());
1453 for (sensors_event_t* i = event; i < event + 3; i++) {
1454 int ret = dev.injectSensorData(i);
1455 if (ret != NO_ERROR) {
1456 return ret;
1457 }
1458 }
1459 return NO_ERROR;
1460}
1461
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001462status_t SensorService::resetToNormalMode() {
1463 Mutex::Autolock _l(mLock);
1464 return resetToNormalModeLocked();
1465}
1466
1467status_t SensorService::resetToNormalModeLocked() {
1468 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001469 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301470 if (err == NO_ERROR) {
1471 mCurrentOperatingMode = NORMAL;
1472 dev.enableAllSensors();
1473 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001474 return err;
1475}
1476
Peng Xu47e96012016-03-28 17:55:56 -07001477void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001478 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001479 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001480 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001481 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001482 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001483 int handle = mActiveSensors.keyAt(i);
1484 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001485 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001486 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1487 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001488 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001489 } else {
1490 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001491 }
Aravind Akella8a969552014-09-28 17:52:41 -07001492 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001493 }
1494 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001495 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001496 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001497 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001498 c, i, handle);
1499
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001500 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001501 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001502 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001503 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001504 delete rec;
1505 size--;
1506 } else {
1507 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001508 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001509 }
Aravind Akella8a969552014-09-28 17:52:41 -07001510 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001511 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001512 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001513 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001514 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001515 }
Peng Xu4f707f82016-09-26 11:28:32 -07001516
Brian Stack793f4642019-04-18 17:21:34 -07001517 {
1518 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1519 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1520 if (iter != sPackageTargetVersion.end()) {
1521 sPackageTargetVersion.erase(iter);
1522 }
1523 }
1524
Peng Xu4f707f82016-09-26 11:28:32 -07001525 SensorDevice& dev(SensorDevice::getInstance());
1526 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001527}
1528
Peng Xue36e3472016-11-03 11:57:10 -07001529void SensorService::cleanupConnection(SensorDirectConnection* c) {
1530 Mutex::Autolock _l(mLock);
1531
1532 SensorDevice& dev(SensorDevice::getInstance());
1533 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001534 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001535}
1536
Peng Xu755c4512016-04-07 23:15:14 -07001537sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001538 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001539}
1540
Mathias Agopianfc328812010-07-14 23:41:37 -07001541status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001542 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001543 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001544 if (mInitCheck != NO_ERROR)
1545 return mInitCheck;
1546
Peng Xu755c4512016-04-07 23:15:14 -07001547 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1548 if (sensor == nullptr ||
1549 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001550 return BAD_VALUE;
1551 }
1552
Brian Duddie967ce172019-06-10 11:08:27 -07001553 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001554 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001555 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001556 return INVALID_OPERATION;
1557 }
1558
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001559 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001560 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001561 rec = new SensorRecord(connection);
1562 mActiveSensors.add(handle, rec);
1563 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001564 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001565 }
Brian Stack26029ee2019-04-22 17:25:49 -07001566
1567 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1568 // the recent event as stale to ensure that the previous event is not sent to a client. This
1569 // ensures on-change events that were generated during a previous sensor activation are not
1570 // erroneously sent to newly connected clients, especially if a second client registers for
1571 // an on-change sensor before the first client receives the updated event. Once an updated
1572 // event is received, the recent events will be marked as current, and any new clients will
1573 // immediately receive the most recent event.
1574 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1575 auto logger = mRecentEvent.find(handle);
1576 if (logger != mRecentEvent.end()) {
1577 logger->second->setLastEventStale();
1578 }
1579 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001580 } else {
1581 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001582 // this sensor is already activated, but we are adding a connection that uses it.
1583 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001584 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001585 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001586 // NOTE: The wake_up flag of this event may get set to
1587 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001588
1589 auto logger = mRecentEvent.find(handle);
1590 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001591 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001592 // Verify that the last sensor event was generated from the current activation
1593 // of the sensor. If not, it is possible for an on-change sensor to receive a
1594 // sensor event that is stale if two clients re-activate the sensor
1595 // simultaneously.
1596 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001597 event.sensor = handle;
1598 if (event.version == sizeof(sensors_event_t)) {
1599 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1600 setWakeLockAcquiredLocked(true);
1601 }
Yi Kong8f313e32018-07-17 14:13:29 -07001602 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001603 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001604 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001605 }
1606 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001607 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001608 }
1609 }
1610 }
1611 }
1612
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001613 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001614 BatteryService::enableSensor(connection->getUid(), handle);
1615 // the sensor was added (which means it wasn't already there)
1616 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001617 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001618 } else {
1619 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1620 handle, connection.get());
1621 }
1622
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301623 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001624 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301625 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1626 samplingPeriodNs = maxDelayNs;
1627 }
1628
Aravind Akella724d91d2013-06-27 12:04:23 -07001629 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1630 if (samplingPeriodNs < minDelayNs) {
1631 samplingPeriodNs = minDelayNs;
1632 }
1633
Aravind Akella6c2664a2014-08-13 12:24:50 -07001634 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1635 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001636 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1637
Aravind Akella4949c502015-02-11 15:54:35 -08001638 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001639 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001640
Peng Xu20483c42015-10-26 15:14:43 -07001641 // Call flush() before calling activate() on the sensor. Wait for a first
1642 // flush complete event before sending events on this connection. Ignore
1643 // one-shot sensors which don't support flush(). Ignore on-change sensors
1644 // to maintain the on-change logic (any on-change events except the initial
1645 // one should be trigger by a change in value). Also if this sensor isn't
1646 // already active, don't call flush().
1647 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001648 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001649 rec->getNumConnections() > 1) {
1650 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001651 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001652 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001653 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001654 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001655 } else {
1656 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001657 }
1658 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001659
1660 if (err == NO_ERROR) {
1661 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1662 err = sensor->activate(connection.get(), true);
1663 }
1664
Aravind Akella8a969552014-09-28 17:52:41 -07001665 if (err == NO_ERROR) {
1666 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001667
Brian Stack240d1d62019-05-17 09:49:39 -07001668 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1669 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001670 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1671 }
1672
Peng Xu51224682017-03-10 16:57:27 -08001673 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1674 SensorRegistrationInfo(handle, connection->getPackageName(),
1675 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001676 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001677 }
1678
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001679 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001680 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001681 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001682 }
1683 return err;
1684}
1685
Peng Xu47e96012016-03-28 17:55:56 -07001686status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001687 if (mInitCheck != NO_ERROR)
1688 return mInitCheck;
1689
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001690 Mutex::Autolock _l(mLock);
1691 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001692 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001693 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1694 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001695
1696 }
1697 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001698 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1699 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001700 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001701 }
1702 return err;
1703}
1704
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001705status_t SensorService::cleanupWithoutDisable(
1706 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001707 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001708 return cleanupWithoutDisableLocked(connection, handle);
1709}
1710
1711status_t SensorService::cleanupWithoutDisableLocked(
1712 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001713 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001714 if (rec) {
1715 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001716 if (connection->removeSensor(handle)) {
1717 BatteryService::disableSensor(connection->getUid(), handle);
1718 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001719 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001720 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001721 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001722 }
1723 // see if this sensor becomes inactive
1724 if (rec->removeConnection(connection)) {
1725 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001726 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001727 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001728 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001729 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001730 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001731 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001732}
1733
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001734status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001735 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001736 if (mInitCheck != NO_ERROR)
1737 return mInitCheck;
1738
Peng Xu755c4512016-04-07 23:15:14 -07001739 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1740 if (sensor == nullptr ||
1741 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001742 return BAD_VALUE;
1743 }
1744
Mathias Agopian1cd70002010-07-21 15:59:50 -07001745 if (ns < 0)
1746 return BAD_VALUE;
1747
Mathias Agopian62569ec2011-11-07 21:21:47 -08001748 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1749 if (ns < minDelayNs) {
1750 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001751 }
1752
Mathias Agopianf001c922010-11-11 17:58:51 -08001753 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001754}
1755
Svetoslavb412f6e2015-04-29 16:50:41 -07001756status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1757 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001758 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001759 SensorDevice& dev(SensorDevice::getInstance());
1760 const int halVersion = dev.getHalDeviceVersion();
1761 status_t err(NO_ERROR);
1762 Mutex::Autolock _l(mLock);
1763 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07001764 for (int handle : connection->getActiveSensorHandles()) {
Peng Xu755c4512016-04-07 23:15:14 -07001765 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1766 if (sensor == nullptr) {
1767 continue;
1768 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001769 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1770 ALOGE("flush called on a one-shot sensor");
1771 err = INVALID_OPERATION;
1772 continue;
1773 }
Aravind Akella8493b792014-09-08 15:45:47 -07001774 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001775 // For older devices just increment pending flush count which will send a trivial
1776 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07001777 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
1778 ALOGE("flush called on an inaccessible sensor");
1779 err = INVALID_OPERATION;
1780 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001781 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001782 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1783 err = INVALID_OPERATION;
1784 continue;
1785 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001786 status_t err_flush = sensor->flush(connection.get(), handle);
1787 if (err_flush == NO_ERROR) {
1788 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001789 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001790 }
1791 err = (err_flush != NO_ERROR) ? err_flush : err;
1792 }
Aravind Akella70018042014-04-07 22:52:37 +00001793 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07001794 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001795}
Aravind Akella70018042014-04-07 22:52:37 +00001796
Svetoslavb412f6e2015-04-29 16:50:41 -07001797bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1798 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001799 // Check if a permission is required for this sensor
1800 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001801 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001802 }
1803
Brian Stack793f4642019-04-18 17:21:34 -07001804 const int32_t opCode = sensor.getRequiredAppOp();
1805 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1806 IPCThreadState::self()->getCallingUid(), opPackageName);
Brian Stack6a700f92019-05-08 17:02:53 -07001807 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
Brian Duddie457e6392020-06-19 11:38:29 -07001808 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07001809
Brian Stack793f4642019-04-18 17:21:34 -07001810 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07001811 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
1812 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1813 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
1814 // Allow access to step sensors if the application targets pre-Q, which is before the
1815 // requirement to hold the AR permission to access Step Counter and Step Detector events
1816 // was introduced.
1817 canAccess = true;
1818 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07001819 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1820 if (opCode < 0 || appOpAllowed) {
Brian Stack793f4642019-04-18 17:21:34 -07001821 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001822 }
Brian Stack793f4642019-04-18 17:21:34 -07001823 }
1824
1825 if (canAccess) {
1826 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1827 } else {
Brian Duddie457e6392020-06-19 11:38:29 -07001828 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
1829 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07001830 }
1831
1832 return canAccess;
1833}
1834
1835bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001836 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001837 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001838
1839 // Runtime permissions can't use the cache as they may change.
1840 if (sensor.isRequiredPermissionRuntime()) {
1841 hasPermission = checkPermission(String16(requiredPermission),
1842 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001843 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001844 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1845 }
Brian Stack793f4642019-04-18 17:21:34 -07001846 return hasPermission;
1847}
Svetoslavb412f6e2015-04-29 16:50:41 -07001848
Brian Stack793f4642019-04-18 17:21:34 -07001849int SensorService::getTargetSdkVersion(const String16& opPackageName) {
1850 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1851 int targetSdkVersion = -1;
1852 auto entry = sPackageTargetVersion.find(opPackageName);
1853 if (entry != sPackageTargetVersion.end()) {
1854 targetSdkVersion = entry->second;
1855 } else {
1856 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1857 if (binder != nullptr) {
1858 sp<content::pm::IPackageManagerNative> packageManager =
1859 interface_cast<content::pm::IPackageManagerNative>(binder);
1860 if (packageManager != nullptr) {
1861 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1862 opPackageName, &targetSdkVersion);
1863 if (!status.isOk()) {
1864 targetSdkVersion = -1;
1865 }
1866 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001867 }
Brian Stack793f4642019-04-18 17:21:34 -07001868 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001869 }
Brian Stack793f4642019-04-18 17:21:34 -07001870 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001871}
1872
Aravind Akella9a844cf2014-02-11 18:58:52 -08001873void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001874 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1875 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001876}
1877
Brian Duddie967ce172019-06-10 11:08:27 -07001878void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001879 if (!mWakeLockAcquired) {
1880 return;
1881 }
1882 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001883 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1884 if (connection->needsWakeLock()) {
1885 releaseLock = false;
1886 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001887 }
1888 }
1889 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001890 setWakeLockAcquiredLocked(false);
1891 }
1892}
1893
1894void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1895 Mutex::Autolock _l(mLock);
1896 connection->writeToSocketFromCache();
1897 if (connection->needsWakeLock()) {
1898 setWakeLockAcquiredLocked(true);
1899 }
1900}
1901
Aravind Akella4949c502015-02-11 15:54:35 -08001902bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001903 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001904}
1905
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001906bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08001907 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001908 String8 package(opPackageName);
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001909 return !isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001910 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001911 return false;
Peng Xue36e3472016-11-03 11:57:10 -07001912}
1913
Svet Ganove752a5c2018-01-15 17:14:20 -08001914void SensorService::UidPolicy::registerSelf() {
1915 ActivityManager am;
1916 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1917 | ActivityManager::UID_OBSERVER_IDLE
1918 | ActivityManager::UID_OBSERVER_ACTIVE,
1919 ActivityManager::PROCESS_STATE_UNKNOWN,
1920 String16("android"));
1921}
1922
1923void SensorService::UidPolicy::unregisterSelf() {
1924 ActivityManager am;
1925 am.unregisterUidObserver(this);
1926}
1927
1928void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1929 onUidIdle(uid, disabled);
1930}
1931
1932void SensorService::UidPolicy::onUidActive(uid_t uid) {
1933 {
1934 Mutex::Autolock _l(mUidLock);
1935 mActiveUids.insert(uid);
1936 }
1937 sp<SensorService> service = mService.promote();
1938 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001939 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001940 }
1941}
1942
1943void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1944 bool deleted = false;
1945 {
1946 Mutex::Autolock _l(mUidLock);
1947 if (mActiveUids.erase(uid) > 0) {
1948 deleted = true;
1949 }
1950 }
1951 if (deleted) {
1952 sp<SensorService> service = mService.promote();
1953 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001954 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001955 }
1956 }
1957}
1958
1959void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1960 updateOverrideUid(uid, active, true);
1961}
1962
1963void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1964 updateOverrideUid(uid, false, false);
1965}
1966
1967void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1968 bool wasActive = false;
1969 bool isActive = false;
1970 {
1971 Mutex::Autolock _l(mUidLock);
1972 wasActive = isUidActiveLocked(uid);
1973 mOverrideUids.erase(uid);
1974 if (insert) {
1975 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1976 }
1977 isActive = isUidActiveLocked(uid);
1978 }
1979 if (wasActive != isActive) {
1980 sp<SensorService> service = mService.promote();
1981 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001982 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001983 }
1984 }
1985}
1986
1987bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1988 // Non-app UIDs are considered always active
1989 if (uid < FIRST_APPLICATION_UID) {
1990 return true;
1991 }
1992 Mutex::Autolock _l(mUidLock);
1993 return isUidActiveLocked(uid);
1994}
1995
1996bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1997 // Non-app UIDs are considered always active
1998 if (uid < FIRST_APPLICATION_UID) {
1999 return true;
2000 }
2001 auto it = mOverrideUids.find(uid);
2002 if (it != mOverrideUids.end()) {
2003 return it->second;
2004 }
2005 return mActiveUids.find(uid) != mActiveUids.end();
2006}
2007
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002008bool SensorService::isUidActive(uid_t uid) {
2009 return mUidPolicy->isUidActive(uid);
2010}
2011
Michael Groover5e1f60b2018-12-04 22:34:29 -08002012void SensorService::SensorPrivacyPolicy::registerSelf() {
2013 SensorPrivacyManager spm;
2014 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2015 spm.addSensorPrivacyListener(this);
2016}
2017
2018void SensorService::SensorPrivacyPolicy::unregisterSelf() {
2019 SensorPrivacyManager spm;
2020 spm.removeSensorPrivacyListener(this);
2021}
2022
2023bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2024 return mSensorPrivacyEnabled;
2025}
2026
2027binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2028 mSensorPrivacyEnabled = enabled;
2029 sp<SensorService> service = mService.promote();
2030 if (service != nullptr) {
2031 if (enabled) {
2032 service->disableAllSensors();
2033 } else {
2034 service->enableAllSensors();
2035 }
2036 }
2037 return binder::Status::ok();
2038}
Brian Duddie967ce172019-06-10 11:08:27 -07002039
2040SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2041 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2042 : mConnectionHolder(holder), mAutolock(mutex) {}
2043
2044template<typename ConnectionType>
2045const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2046 const SortedVector<wp<ConnectionType>>& connectionList,
2047 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2048 referenceHolder->emplace_back();
2049 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2050 for (const wp<ConnectionType>& weakConnection : connectionList){
2051 sp<ConnectionType> connection = weakConnection.promote();
2052 if (connection != nullptr) {
2053 connections.push_back(std::move(connection));
2054 }
2055 }
2056 return connections;
2057}
2058
2059const std::vector<sp<SensorService::SensorEventConnection>>&
2060 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2061 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2062 &mReferencedActiveConnections);
2063}
2064
2065const std::vector<sp<SensorService::SensorDirectConnection>>&
2066 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2067 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2068 &mReferencedDirectConnections);
2069}
2070
2071void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2072 const sp<SensorService::SensorEventConnection>& connection) {
2073 if (mActiveConnections.indexOf(connection) < 0) {
2074 mActiveConnections.add(connection);
2075 }
2076}
2077
2078void SensorService::SensorConnectionHolder::removeEventConnection(
2079 const wp<SensorService::SensorEventConnection>& connection) {
2080 mActiveConnections.remove(connection);
2081}
2082
2083void SensorService::SensorConnectionHolder::addDirectConnection(
2084 const sp<SensorService::SensorDirectConnection>& connection) {
2085 mDirectConnections.add(connection);
2086}
2087
2088void SensorService::SensorConnectionHolder::removeDirectConnection(
2089 const wp<SensorService::SensorDirectConnection>& connection) {
2090 mDirectConnections.remove(connection);
2091}
2092
2093SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2094 return ConnectionSafeAutolock(*this, mutex);
2095}
2096
2097} // namespace android