blob: 29698390fbf99991b9057c8f8391046674ece168 [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;
Anthony Stange07eb4212020-08-28 14:50:28 -040082String16 SensorService::sSensorInterfaceDescriptorPrefix =
83 String16("android.frameworks.sensorservice@");
Brian Stack793f4642019-04-18 17:21:34 -070084AppOpsManager SensorService::sAppOpsManager;
Greg Kaiser53ca2e02016-06-21 16:11:14 -070085
86#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
87#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070088#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070089
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070090// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070091static const String16 sDumpPermission("android.permission.DUMP");
92static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080093static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070094
Mathias Agopianfc328812010-07-14 23:41:37 -070095SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070096 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070097 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +090098 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -080099 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700100}
101
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700102bool SensorService::initializeHmacKey() {
103 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
104 if (fd != -1) {
105 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
106 close(fd);
107 if (result == sizeof(sHmacGlobalKey)) {
108 return true;
109 }
110 ALOGW("Unable to read HMAC key; generating new one.");
111 }
112
113 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
114 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
115 return false;
116 }
117
118 // We need to make sure this is only readable to us.
119 bool wroteKey = false;
120 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
121 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
122 S_IRUSR|S_IWUSR);
123 if (fd != -1) {
124 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
125 close(fd);
126 wroteKey = (result == sizeof(sHmacGlobalKey));
127 }
128 if (wroteKey) {
129 ALOGI("Generated new HMAC key.");
130 } else {
131 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
132 "after reboot.");
133 }
134 // Even if we failed to write the key we return true, because we did
135 // initialize the HMAC key.
136 return true;
137}
138
Peng Xu98d30f62016-08-01 18:12:11 -0700139// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
140void SensorService::enableSchedFifoMode() {
141 struct sched_param param = {0};
142 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
143 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
144 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
145 }
146}
147
Peng Xu47e96012016-03-28 17:55:56 -0700148void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000149 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800150 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700151
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700152 sHmacGlobalKeyIsValid = initializeHmacKey();
153
Mathias Agopianf001c922010-11-11 17:58:51 -0800154 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800155 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700156 ssize_t count = dev.getSensorList(&list);
157 if (count > 0) {
158 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700159 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700160 uint32_t virtualSensorsNeeds =
161 (1<<SENSOR_TYPE_GRAVITY) |
162 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700163 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
164 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
165 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700166
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700167 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700168 bool useThisSensor=true;
169
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700170 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700171 case SENSOR_TYPE_ACCELEROMETER:
172 hasAccel = true;
173 break;
174 case SENSOR_TYPE_MAGNETIC_FIELD:
175 hasMag = true;
176 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700177 case SENSOR_TYPE_ORIENTATION:
178 orientationIndex = i;
179 break;
180 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700181 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700182 hasGyro = true;
183 break;
184 case SENSOR_TYPE_GRAVITY:
185 case SENSOR_TYPE_LINEAR_ACCELERATION:
186 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700187 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
188 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
189 if (IGNORE_HARDWARE_FUSION) {
190 useThisSensor = false;
191 } else {
192 virtualSensorsNeeds &= ~(1<<list[i].type);
193 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700194 break;
195 }
Peng Xuf66684a2015-07-23 11:41:53 -0700196 if (useThisSensor) {
197 registerSensor( new HardwareSensor(list[i]) );
198 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700199 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700200
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700201 // it's safe to instantiate the SensorFusion object here
202 // (it wants to be instantiated after h/w sensors have been
203 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700204 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700205
Aravind Akellaf5047892015-07-20 17:29:33 -0700206 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700207 // Add Android virtual sensors if they're not already
208 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700209 bool needRotationVector =
210 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700211
Peng Xu0cc8f802016-04-05 23:46:03 -0700212 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
213 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700214
Peng Xu0cc8f802016-04-05 23:46:03 -0700215 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700216 registerSensor( new CorrectedGyroSensor(list, count), true, true);
217 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700218 }
219
Peng Xuf66684a2015-07-23 11:41:53 -0700220 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700221 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
222 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700223
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800224 bool needLinearAcceleration =
225 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
226 registerSensor(new LinearAccelerationSensor(list, count),
227 !needLinearAcceleration, true);
228
Peng Xu0cc8f802016-04-05 23:46:03 -0700229 bool needGameRotationVector =
230 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
231 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700232 }
233
234 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700235 bool needGeoMagRotationVector =
236 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
237 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700238 }
239
Aravind Akella5466c3d2014-08-22 16:11:10 -0700240 // Check if the device really supports batching by looking at the FIFO event
241 // counts for each sensor.
242 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700243 mSensors.forEachSensor(
244 [&batchingSupported] (const Sensor& s) -> bool {
245 if (s.getFifoMaxEventCount() > 0) {
246 batchingSupported = true;
247 }
248 return !batchingSupported;
249 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700250
251 if (batchingSupported) {
252 // Increase socket buffer size to a max of 100 KB for batching capabilities.
253 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
254 } else {
255 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
256 }
257
258 // Compare the socketBufferSize value against the system limits and limit
259 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700260 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
261 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700262 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700263 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700264 size_t maxSystemSocketBufferSize;
265 sscanf(line, "%zu", &maxSystemSocketBufferSize);
266 if (mSocketBufferSize > maxSystemSocketBufferSize) {
267 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700268 }
269 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700270 if (fp) {
271 fclose(fp);
272 }
273
Aravind Akella9a844cf2014-02-11 18:58:52 -0800274 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700275 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700276 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
277 mSensorEventBuffer = new sensors_event_t[minBufferSize];
278 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700279 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700280 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700281
Aravind Akella18d6d512015-06-18 14:18:28 -0700282 mNextSensorRegIndex = 0;
283 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
284 mLastNSensorRegistrations.push();
285 }
286
287 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700288 mAckReceiver = new SensorEventAckReceiver(this);
289 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700290 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700291
292 // priority can only be changed after run
293 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800294
295 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800296 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800297
298 // Start watching sensor privacy changes
299 mSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800300 }
301 }
302}
303
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700304void SensorService::onUidStateChanged(uid_t uid, UidState state) {
305 SensorDevice& dev(SensorDevice::getInstance());
306
Brian Duddie967ce172019-06-10 11:08:27 -0700307 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700308 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700309 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700310 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700311 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700312 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700313
314 for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
315 if (conn->getUid() == uid) {
316 // Update sensor subscriptions if needed
317 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
318 conn->onSensorAccessChanged(hasAccess);
319 }
320 }
321}
322
323bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
324 Mutex::Autolock _l(mLock);
325 return hasSensorAccessLocked(uid, opPackageName);
326}
327
328bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
329 return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
330 && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -0700331}
332
Peng Xu0cc8f802016-04-05 23:46:03 -0700333const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
334 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800335 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700336 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700337 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700338 return s->getSensor();
339 } else {
340 return mSensors.getNonSensor();
341 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800342}
343
Peng Xu6a2d3a02015-12-21 12:00:23 -0800344const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700345 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800346}
347
Peng Xu6a2d3a02015-12-21 12:00:23 -0800348bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700349 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800350
351 const auto i = mRecentEvent.find(handle);
352 if (i != mRecentEvent.end()) {
353 delete i->second;
354 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800355 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700356 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800357}
358
Peng Xu0cc8f802016-04-05 23:46:03 -0700359const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
360 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700361}
362
Peng Xu47e96012016-03-28 17:55:56 -0700363SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800364 for (auto && entry : mRecentEvent) {
365 delete entry.second;
366 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800367 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800368 mSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700369}
370
371status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700372 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700373 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800374 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700375 IPCThreadState::self()->getCallingPid(),
376 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700377 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700378 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700379 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800380 return INVALID_OPERATION;
381 }
Brian Duddie967ce172019-06-10 11:08:27 -0700382 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800383 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700384 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700385 // If already in restricted mode. Ignore.
386 if (mCurrentOperatingMode == RESTRICTED) {
387 return status_t(NO_ERROR);
388 }
389 // If in any mode other than normal, ignore.
390 if (mCurrentOperatingMode != NORMAL) {
391 return INVALID_OPERATION;
392 }
Peng Xue36e3472016-11-03 11:57:10 -0700393
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700394 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800395 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700396 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700397 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700398 return status_t(NO_ERROR);
399 } else if (args.size() == 1 && args[0] == String16("enable")) {
400 // If currently in restricted mode, reset back to NORMAL mode else ignore.
401 if (mCurrentOperatingMode == RESTRICTED) {
402 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800403 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700404 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700405 }
Aravind Akella841a5922015-06-29 12:37:48 -0700406 if (mCurrentOperatingMode == DATA_INJECTION) {
407 resetToNormalModeLocked();
408 }
409 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700410 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700411 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
412 if (mCurrentOperatingMode == NORMAL) {
413 dev.disableAllSensors();
414 status_t err = dev.setMode(DATA_INJECTION);
415 if (err == NO_ERROR) {
416 mCurrentOperatingMode = DATA_INJECTION;
417 } else {
418 // Re-enable sensors.
419 dev.enableAllSensors();
420 }
421 mWhiteListedPackage.setTo(String8(args[1]));
422 return NO_ERROR;
423 } else if (mCurrentOperatingMode == DATA_INJECTION) {
424 // Already in DATA_INJECTION mode. Treat this as a no_op.
425 return NO_ERROR;
426 } else {
427 // Transition to data injection mode supported only from NORMAL mode.
428 return INVALID_OPERATION;
429 }
Mike Ma24743862020-01-29 00:36:55 -0800430 } else if (args.size() == 1 && args[0] == String16("--proto")) {
431 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700432 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700433 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700434 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700435 } else {
436 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700437 //
Brian Stack51498e62018-10-03 10:52:21 -0700438 timespec curTime;
439 clock_gettime(CLOCK_REALTIME, &curTime);
440 struct tm* timeinfo = localtime(&(curTime.tv_sec));
441 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
442 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800443 result.append("Sensor Device:\n");
444 result.append(SensorDevice::getInstance().dump().c_str());
445
446 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700447 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700448
Peng Xu6a2d3a02015-12-21 12:00:23 -0800449 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700450 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700451
Peng Xu0cc8f802016-04-05 23:46:03 -0700452 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800453 for (auto&& i : mRecentEvent) {
454 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700455 if (!i.second->isEmpty()) {
456 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
457 i.second->setFormat("normal");
458 } else {
459 i.second->setFormat("mask_data");
460 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800461 // if there is events and sensor does not need special permission.
462 result.appendFormat("%s: ", s->getSensor().getName().string());
463 result.append(i.second->dump().c_str());
464 }
465 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700466
Aravind Akella444f2672015-05-07 12:40:52 -0700467 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700468 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700469 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
470 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700471 if (dev.isSensorActive(handle)) {
472 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
473 getSensorName(handle).string(),
474 handle,
475 mActiveSensors.valueAt(i)->getNumConnections());
476 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700477 }
478
Andreas Gamped4036b62015-07-28 13:49:04 -0700479 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700480 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700481 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
482 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700483 result.appendFormat("Mode :");
484 switch(mCurrentOperatingMode) {
485 case NORMAL:
486 result.appendFormat(" NORMAL\n");
487 break;
488 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700489 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700490 break;
491 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700492 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700493 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800494 result.appendFormat("Sensor Privacy: %s\n",
495 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700496
Brian Duddie967ce172019-06-10 11:08:27 -0700497 const auto& activeConnections = connLock.getActiveConnections();
498 result.appendFormat("%zd active connections\n", activeConnections.size());
499 for (size_t i=0 ; i < activeConnections.size() ; i++) {
500 result.appendFormat("Connection Number: %zu \n", i);
501 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700502 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700503
Brian Duddie967ce172019-06-10 11:08:27 -0700504 const auto& directConnections = connLock.getDirectConnections();
505 result.appendFormat("%zd direct connections\n", directConnections.size());
506 for (size_t i = 0 ; i < directConnections.size() ; i++) {
507 result.appendFormat("Direct connection %zu:\n", i);
508 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700509 }
510
Aravind Akella18d6d512015-06-18 14:18:28 -0700511 result.appendFormat("Previous Registrations:\n");
512 // Log in the reverse chronological order.
513 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
514 SENSOR_REGISTRATIONS_BUF_SIZE;
515 const int startIndex = currentIndex;
516 do {
517 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
518 if (SensorRegistrationInfo::isSentinel(reg_info)) {
519 // Ignore sentinel, proceed to next item.
520 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
521 SENSOR_REGISTRATIONS_BUF_SIZE;
522 continue;
523 }
Peng Xu51224682017-03-10 16:57:27 -0800524 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700525 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
526 SENSOR_REGISTRATIONS_BUF_SIZE;
527 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700528 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700529 }
530 write(fd, result.string(), result.size());
531 return NO_ERROR;
532}
533
Mike Ma24743862020-01-29 00:36:55 -0800534/**
535 * Dump debugging information as android.service.SensorServiceProto protobuf message using
536 * ProtoOutputStream.
537 *
538 * See proto definition and some notes about ProtoOutputStream in
539 * frameworks/base/core/proto/android/service/sensor_service.proto
540 */
541status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
542 using namespace service::SensorServiceProto;
543 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800544 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
545 if (!mSensors.hasAnySensor()) {
546 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
547 }
Mike Ma24743862020-01-29 00:36:55 -0800548 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
549
550 timespec curTime;
551 clock_gettime(CLOCK_REALTIME, &curTime);
552 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
553
554 // Write SensorDeviceProto
555 uint64_t token = proto.start(SENSOR_DEVICE);
556 SensorDevice::getInstance().dump(&proto);
557 proto.end(token);
558
559 // Write SensorListProto
560 token = proto.start(SENSORS);
561 mSensors.dump(&proto);
562 proto.end(token);
563
564 // Write SensorFusionProto
565 token = proto.start(FUSION_STATE);
566 SensorFusion::getInstance().dump(&proto);
567 proto.end(token);
568
569 // Write SensorEventsProto
570 token = proto.start(SENSOR_EVENTS);
571 for (auto&& i : mRecentEvent) {
572 sp<SensorInterface> s = mSensors.getInterface(i.first);
573 if (!i.second->isEmpty()) {
574 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
575 "normal" : "mask_data");
576 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
577 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
578 std::string(s->getSensor().getName().string()));
579 i.second->dump(&proto);
580 proto.end(mToken);
581 }
582 }
583 proto.end(token);
584
585 // Write ActiveSensorProto
586 SensorDevice& dev = SensorDevice::getInstance();
587 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
588 int handle = mActiveSensors.keyAt(i);
589 if (dev.isSensorActive(handle)) {
590 token = proto.start(ACTIVE_SENSORS);
591 proto.write(service::ActiveSensorProto::NAME,
592 std::string(getSensorName(handle).string()));
593 proto.write(service::ActiveSensorProto::HANDLE, handle);
594 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
595 int(mActiveSensors.valueAt(i)->getNumConnections()));
596 proto.end(token);
597 }
598 }
599
600 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
601 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
602 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
603
604 switch(mCurrentOperatingMode) {
605 case NORMAL:
606 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
607 break;
608 case RESTRICTED:
609 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
610 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
611 break;
612 case DATA_INJECTION:
613 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
614 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
615 break;
616 default:
617 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
618 }
619 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
620
621 // Write repeated SensorEventConnectionProto
622 const auto& activeConnections = connLock->getActiveConnections();
623 for (size_t i = 0; i < activeConnections.size(); i++) {
624 token = proto.start(ACTIVE_CONNECTIONS);
625 activeConnections[i]->dump(&proto);
626 proto.end(token);
627 }
628
629 // Write repeated SensorDirectConnectionProto
630 const auto& directConnections = connLock->getDirectConnections();
631 for (size_t i = 0 ; i < directConnections.size() ; i++) {
632 token = proto.start(DIRECT_CONNECTIONS);
633 directConnections[i]->dump(&proto);
634 proto.end(token);
635 }
636
637 // Write repeated SensorRegistrationInfoProto
638 const int startIndex = mNextSensorRegIndex;
639 int curr = startIndex;
640 do {
641 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
642 if (SensorRegistrationInfo::isSentinel(reg_info)) {
643 // Ignore sentinel, proceed to next item.
644 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
645 continue;
646 }
647 token = proto.start(PREVIOUS_REGISTRATIONS);
648 reg_info.dump(&proto);
649 proto.end(token);
650 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
651 } while (startIndex != curr);
652
653 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
654}
655
Michael Groover5e1f60b2018-12-04 22:34:29 -0800656void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700657 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
658 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800659}
660
Brian Duddie967ce172019-06-10 11:08:27 -0700661void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800662 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700663 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
664 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
665 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800666 }
667 dev.disableAllSensors();
668 // Clear all pending flush connections for all active sensors. If one of the active
669 // connections has called flush() and the underlying sensor has been disabled before a
670 // flush complete event is returned, we need to remove the connection from this queue.
671 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
672 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
673 }
674}
675
676void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700677 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
678 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800679}
680
Brian Duddie967ce172019-06-10 11:08:27 -0700681void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800682 // sensors should only be enabled if the operating state is not restricted and sensor
683 // privacy is not enabled.
684 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
685 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
686 mCurrentOperatingMode,
687 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
688 return;
689 }
690 SensorDevice& dev(SensorDevice::getInstance());
691 dev.enableAllSensors();
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700692 for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
693 bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
694 conn->onSensorAccessChanged(hasAccess);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800695 }
696}
697
Brian Duddie967ce172019-06-10 11:08:27 -0700698
Svet Ganove752a5c2018-01-15 17:14:20 -0800699// NOTE: This is a remote API - make sure all args are validated
700status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
701 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
702 return PERMISSION_DENIED;
703 }
karthik bharadwaj1b386582020-05-19 18:32:36 -0700704 if (args.size() == 0) {
705 return BAD_INDEX;
706 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800707 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
708 return BAD_VALUE;
709 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700710 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800711 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700712 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800713 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700714 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800715 return handleGetUidState(args, out, err);
716 } else if (args.size() == 1 && args[0] == String16("help")) {
717 printHelp(out);
718 return NO_ERROR;
719 }
720 printHelp(err);
721 return BAD_VALUE;
722}
723
Tanmay Patild33a1822019-04-11 18:38:55 -0700724static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800725 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700726 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800727 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700728 ALOGE("Unknown package: '%s'", String8(packageName).string());
729 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800730 return BAD_VALUE;
731 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700732
733 if (userId < 0) {
734 ALOGE("Invalid user: %d", userId);
735 dprintf(err, "Invalid user: %d\n", userId);
736 return BAD_VALUE;
737 }
738
739 uid = multiuser_get_uid(userId, uid);
740 return NO_ERROR;
741}
742
743status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
744 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
745 if (!(args.size() == 3 || args.size() == 5)) {
746 printHelp(err);
747 return BAD_VALUE;
748 }
749
Svet Ganove752a5c2018-01-15 17:14:20 -0800750 bool active = false;
751 if (args[2] == String16("active")) {
752 active = true;
753 } else if ((args[2] != String16("idle"))) {
754 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
755 return BAD_VALUE;
756 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700757
758 int userId = 0;
759 if (args.size() == 5 && args[3] == String16("--user")) {
760 userId = atoi(String8(args[4]));
761 }
762
763 uid_t uid;
764 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
765 return BAD_VALUE;
766 }
767
Svet Ganove752a5c2018-01-15 17:14:20 -0800768 mUidPolicy->addOverrideUid(uid, active);
769 return NO_ERROR;
770}
771
772status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700773 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
774 if (!(args.size() == 2 || args.size() == 4)) {
775 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800776 return BAD_VALUE;
777 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700778
779 int userId = 0;
780 if (args.size() == 4 && args[2] == String16("--user")) {
781 userId = atoi(String8(args[3]));
782 }
783
784 uid_t uid;
785 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
786 return BAD_VALUE;
787 }
788
Svet Ganove752a5c2018-01-15 17:14:20 -0800789 mUidPolicy->removeOverrideUid(uid);
790 return NO_ERROR;
791}
792
793status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700794 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
795 if (!(args.size() == 2 || args.size() == 4)) {
796 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800797 return BAD_VALUE;
798 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700799
800 int userId = 0;
801 if (args.size() == 4 && args[2] == String16("--user")) {
802 userId = atoi(String8(args[3]));
803 }
804
805 uid_t uid;
806 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
807 return BAD_VALUE;
808 }
809
Svet Ganove752a5c2018-01-15 17:14:20 -0800810 if (mUidPolicy->isUidActive(uid)) {
811 return dprintf(out, "active\n");
812 } else {
813 return dprintf(out, "idle\n");
814 }
815}
816
817status_t SensorService::printHelp(int out) {
818 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700819 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
820 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
821 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800822 " help print this message\n");
823}
824
Peng Xu0cc8f802016-04-05 23:46:03 -0700825//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800826void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700827 sensors_event_t const* buffer, const int count) {
828 for (int i=0 ; i<count ; i++) {
829 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700830 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
831 handle = buffer[i].meta_data.sensor;
832 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700833 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700834 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700835 // If this buffer has an event from a one_shot sensor and this connection is registered
836 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700837 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700838 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
839 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800840 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700841 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700842
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700843 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700844 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700845}
846
Peng Xu47e96012016-03-28 17:55:56 -0700847bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000848 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700849
Peng Xueb4d6282015-12-10 18:02:41 -0800850 // each virtual sensor could generate an event per "real" event, that's why we need to size
851 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
852 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700853 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700854 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700855 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700856
Mathias Agopianf001c922010-11-11 17:58:51 -0800857 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700858
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700859 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700860 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700861 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
862 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700863 if(count == DEAD_OBJECT && device.isReconnecting()) {
864 device.reconnect();
865 continue;
866 } else {
867 ALOGE("sensor poll failed (%s)", strerror(-count));
868 break;
869 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700870 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700871
872 // Reset sensors_event_t.flags to zero for all events in the buffer.
873 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700874 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700875 }
Brian Duddie967ce172019-06-10 11:08:27 -0700876 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700877
Aravind Akella9a844cf2014-02-11 18:58:52 -0800878 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
879 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
880 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
881 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
882 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700883 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700884 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700885 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700886 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700887 }
888 }
889
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700890 if (wakeEvents > 0) {
891 if (!mWakeLockAcquired) {
892 setWakeLockAcquiredLocked(true);
893 }
894 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800895 }
Aravind Akella8493b792014-09-08 15:45:47 -0700896 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800897
Mathias Agopianf001c922010-11-11 17:58:51 -0800898 // handle virtual sensors
899 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700900 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700901 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800902 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700903 SensorFusion& fusion(SensorFusion::getInstance());
904 if (fusion.isEnabled()) {
905 for (size_t i=0 ; i<size_t(count) ; i++) {
906 fusion.process(event[i]);
907 }
908 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700909 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700910 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700911 if (count + k >= minBufferSize) {
912 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700913 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700914 count, k, minBufferSize);
915 break;
916 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800917 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700918 sp<SensorInterface> si = mSensors.getInterface(handle);
919 if (si == nullptr) {
920 ALOGE("handle %d is not an valid virtual sensor", handle);
921 continue;
922 }
923
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700924 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700925 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800926 k++;
927 }
928 }
929 }
930 if (k) {
931 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700932 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800933 count += k;
934 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700935 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700936 }
937 }
938 }
939
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700940 // handle backward compatibility for RotationVector sensor
941 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
942 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700943 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700944 // All the 4 components of the quaternion should be available
945 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700946 mSensorEventBuffer[i].data[4] = -1;
947 }
948 }
949 }
950
Brian Duddie967ce172019-06-10 11:08:27 -0700951 // Cache the list of active connections, since we use it in multiple places below but won't
952 // modify it here
953 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
954
Aravind Akella8493b792014-09-08 15:45:47 -0700955 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700956 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
957 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
958 // SensorEventConnection mapped to the corresponding flush_complete_event in
959 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700960 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700961 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
962 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
963 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700964 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700965 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
966 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700967 }
968 }
Peng Xu2576cb62016-01-20 00:22:09 -0800969
970 // handle dynamic sensor meta events, process registration and unregistration of dynamic
971 // sensor based on content of event.
972 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
973 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
974 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
975 const sensor_t& dynamicSensor =
976 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
977 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
978 handle, dynamicSensor.type, dynamicSensor.name);
979
Peng Xu0cc8f802016-04-05 23:46:03 -0700980 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800981 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700982 sensor_t s = dynamicSensor;
983 // make sure the dynamic sensor flag is set
984 s.flags |= DYNAMIC_SENSOR_MASK;
985 // force the handle to be consistent
986 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800987
988 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800989
Peng Xu0cc8f802016-04-05 23:46:03 -0700990 // This will release hold on dynamic sensor meta, so it should be called
991 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700992 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800993 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700994 } else {
995 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
996 }
Peng Xu2576cb62016-01-20 00:22:09 -0800997 } else {
998 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
999 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
1000
1001 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -08001002 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -08001003 ALOGE("Dynamic sensor release error.");
1004 }
1005
Brian Duddie967ce172019-06-10 11:08:27 -07001006 for (const sp<SensorEventConnection>& connection : activeConnections) {
1007 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001008 }
1009 }
1010 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001011 }
1012
Aravind Akella9a844cf2014-02-11 18:58:52 -08001013 // Send our events to clients. Check the state of wake lock for each client and release the
1014 // lock if none of the clients need it.
1015 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001016 for (const sp<SensorEventConnection>& connection : activeConnections) {
1017 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1018 mMapFlushEventsToConnections);
1019 needsWakeLock |= connection->needsWakeLock();
1020 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1021 // Early check for one-shot sensors.
1022 if (connection->hasOneShotSensors()) {
1023 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001024 }
1025 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001026
Aravind Akella9a844cf2014-02-11 18:58:52 -08001027 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001028 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001029 }
Aravind Akella8493b792014-09-08 15:45:47 -07001030 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001031
Steve Block3c20fbe2012-01-05 23:22:43 +00001032 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001033 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001034 return false;
1035}
1036
Aravind Akella56ae4262014-07-10 16:01:10 -07001037sp<Looper> SensorService::getLooper() const {
1038 return mLooper;
1039}
1040
Aravind Akellab4373ac2014-10-29 17:55:20 -07001041void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001042 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1043 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1044 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001045 }
Brian Duddie967ce172019-06-10 11:08:27 -07001046 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001047}
1048
1049void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1050 if (acquire) {
1051 if (!mWakeLockAcquired) {
1052 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1053 mWakeLockAcquired = true;
1054 }
1055 mLooper->wake();
1056 } else {
1057 if (mWakeLockAcquired) {
1058 release_wake_lock(WAKE_LOCK_NAME);
1059 mWakeLockAcquired = false;
1060 }
1061 }
1062}
1063
Aravind Akellab4373ac2014-10-29 17:55:20 -07001064bool SensorService::isWakeLockAcquired() {
1065 Mutex::Autolock _l(mLock);
1066 return mWakeLockAcquired;
1067}
1068
Aravind Akella56ae4262014-07-10 16:01:10 -07001069bool SensorService::SensorEventAckReceiver::threadLoop() {
1070 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001071 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001072 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001073 bool wakeLockAcquired = mService->isWakeLockAcquired();
1074 int timeout = -1;
1075 if (wakeLockAcquired) timeout = 5000;
1076 int ret = looper->pollOnce(timeout);
1077 if (ret == ALOOPER_POLL_TIMEOUT) {
1078 mService->resetAllWakeLockRefCounts();
1079 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001080 } while(!Thread::exitPending());
1081 return false;
1082}
1083
Aravind Akella9a844cf2014-02-11 18:58:52 -08001084void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001085 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001086 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001087 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1088 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001089 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001090 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001091 }
Peng Xu2576cb62016-01-20 00:22:09 -08001092
Peng Xu6a2d3a02015-12-21 12:00:23 -08001093 auto logger = mRecentEvent.find(buffer[i].sensor);
1094 if (logger != mRecentEvent.end()) {
1095 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001096 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001097 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001098}
1099
Peng Xu47e96012016-03-28 17:55:56 -07001100void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001101 struct compar {
1102 static int cmp(void const* lhs, void const* rhs) {
1103 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1104 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001105 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001106 }
1107 };
1108 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1109}
1110
Mathias Agopian5d270722010-07-19 15:20:39 -07001111String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001112 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001113}
1114
Aravind Akellab4099e72013-10-15 15:43:10 -07001115bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001116 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1117 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001118}
1119
Aravind Akella9a844cf2014-02-11 18:58:52 -08001120bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001121 int handle = event.sensor;
1122 if (event.type == SENSOR_TYPE_META_DATA) {
1123 handle = event.meta_data.sensor;
1124 }
Peng Xu755c4512016-04-07 23:15:14 -07001125 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1126 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001127}
1128
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001129int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1130 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1131 // UUID is not supported for this device.
1132 return 0;
1133 }
1134 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1135 // This sensor can be uniquely identified in the system by
1136 // the combination of its type and name.
1137 return -1;
1138 }
1139
1140 // We have a dynamic sensor.
1141
1142 if (!sHmacGlobalKeyIsValid) {
1143 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1144 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1145 return 0;
1146 }
1147
1148 // We want each app author/publisher to get a different ID, so that the
1149 // same dynamic sensor cannot be tracked across apps by multiple
1150 // authors/publishers. So we use both our UUID and our User ID.
1151 // Note potential confusion:
1152 // UUID => Universally Unique Identifier.
1153 // UID => User Identifier.
1154 // We refrain from using "uid" except as needed by API to try to
1155 // keep this distinction clear.
1156
1157 auto appUserId = IPCThreadState::self()->getCallingUid();
1158 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1159 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1160 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1161
1162 // Now we use our key on our UUID/app combo to get the hash.
1163 uint8_t hash[EVP_MAX_MD_SIZE];
1164 unsigned int hashLen;
1165 if (HMAC(EVP_sha256(),
1166 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1167 uuidAndApp, sizeof(uuidAndApp),
1168 hash, &hashLen) == nullptr) {
1169 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1170 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1171 return 0;
1172 }
1173
1174 int32_t id = 0;
1175 if (hashLen < sizeof(id)) {
1176 // We never expect this case, but out of paranoia, we handle it.
1177 // Our 'id' length is already quite small, we don't want the
1178 // effective length of it to be even smaller.
1179 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1180 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1181 return 0;
1182 }
1183
1184 // This is almost certainly less than all of 'hash', but it's as secure
1185 // as we can be with our current 'id' length.
1186 memcpy(&id, hash, sizeof(id));
1187
1188 // Note at the beginning of the function that we return the values of
1189 // 0 and -1 to represent special cases. As a result, we can't return
1190 // those as dynamic sensor IDs. If we happened to hash to one of those
1191 // values, we change 'id' so we report as a dynamic sensor, and not as
1192 // one of those special cases.
1193 if (id == -1) {
1194 id = -2;
1195 } else if (id == 0) {
1196 id = 1;
1197 }
1198 return id;
1199}
1200
1201void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1202 for (auto &sensor : sensorList) {
1203 int32_t id = getIdFromUuid(sensor.getUuid());
1204 sensor.setId(id);
1205 }
1206}
1207
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001208Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001209 char value[PROPERTY_VALUE_MAX];
1210 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001211 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001212 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001213 Vector<Sensor> accessibleSensorList;
1214 for (size_t i = 0; i < initialSensorList.size(); i++) {
1215 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001216 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001217 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001218 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001219 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001220}
1221
Peng Xu47e96012016-03-28 17:55:56 -07001222Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001223 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001224 mSensors.forEachSensor(
1225 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001226 if (sensor.isDynamicSensor()) {
1227 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1228 accessibleSensorList.add(sensor);
1229 } else {
1230 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1231 sensor.getName().string(),
1232 sensor.getRequiredPermission().string(),
1233 sensor.getRequiredAppOp());
1234 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001235 }
1236 return true;
1237 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001238 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001239 return accessibleSensorList;
1240}
1241
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001242sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001243 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001244 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1245 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001246 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001247 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001248
1249 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001250 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1251 // operating in DI mode.
1252 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001253 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1254 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001255 }
1256
Mathias Agopian5307d172012-09-18 17:02:43 -07001257 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001258 pid_t pid = IPCThreadState::self()->getCallingPid();
1259
1260 String8 connPackageName =
1261 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1262 String16 connOpPackageName =
1263 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1264 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001265 requestedMode == DATA_INJECTION, connOpPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001266 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001267 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001268 // Add the associated file descriptor to the Looper for polling whenever there is data to
1269 // be injected.
1270 result->updateLooperRegistration(mLooper);
1271 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001272 return result;
1273}
1274
Aravind Akella841a5922015-06-29 12:37:48 -07001275int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001276 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001277 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001278}
1279
Peng Xue36e3472016-11-03 11:57:10 -07001280sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1281 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1282 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001283 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001284
Michael Groover5e1f60b2018-12-04 22:34:29 -08001285 // No new direct connections are allowed when sensor privacy is enabled
1286 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1287 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1288 return nullptr;
1289 }
1290
Peng Xue36e3472016-11-03 11:57:10 -07001291 struct sensors_direct_mem_t mem = {
1292 .type = type,
1293 .format = format,
1294 .size = size,
1295 .handle = resource,
1296 };
1297 uid_t uid = IPCThreadState::self()->getCallingUid();
1298
1299 if (mem.handle == nullptr) {
1300 ALOGE("Failed to clone resource handle");
1301 return nullptr;
1302 }
1303
1304 // check format
1305 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1306 ALOGE("Direct channel format %d is unsupported!", format);
1307 return nullptr;
1308 }
1309
1310 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001311 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1312 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001313 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001314 return nullptr;
1315 }
1316 }
1317
1318 // check specific to memory type
1319 switch(type) {
1320 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001321 if (resource->numFds < 1) {
1322 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1323 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1324 return nullptr;
1325 }
Peng Xue36e3472016-11-03 11:57:10 -07001326 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001327 if (!ashmem_valid(fd)) {
1328 ALOGE("Supplied Ashmem memory region is invalid");
1329 return nullptr;
1330 }
1331
Peng Xue36e3472016-11-03 11:57:10 -07001332 int size2 = ashmem_get_size_region(fd);
1333 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001334 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001335 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1336 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001337 return nullptr;
1338 }
1339 break;
1340 }
1341 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001342 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001343 break;
1344 default:
1345 ALOGE("Unknown direct connection memory type %d", type);
1346 return nullptr;
1347 }
1348
1349 native_handle_t *clone = native_handle_clone(resource);
1350 if (!clone) {
1351 return nullptr;
1352 }
1353
Brian Duddie967ce172019-06-10 11:08:27 -07001354 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001355 SensorDevice& dev(SensorDevice::getInstance());
1356 int channelHandle = dev.registerDirectChannel(&mem);
1357
1358 if (channelHandle <= 0) {
1359 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1360 } else {
1361 mem.handle = clone;
1362 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1363 }
1364
1365 if (conn == nullptr) {
1366 native_handle_close(clone);
1367 native_handle_delete(clone);
1368 } else {
1369 // add to list of direct connections
1370 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001371 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001372 }
1373 return conn;
1374}
1375
Peng Xudd5c5cb2017-03-16 17:39:43 -07001376int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001377 int32_t handle, int32_t type,
1378 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001379 Mutex::Autolock _l(mLock);
1380
Alexey Polyudov88711e82017-05-23 19:54:04 -07001381 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001382 return PERMISSION_DENIED;
1383 }
1384
1385 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001386 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001387 size_t expectSize = INT32_MAX;
1388 switch (type) {
1389 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1390 isFloat = true;
1391 expectSize = 3;
1392 break;
1393 case AINFO_LOCAL_GRAVITY:
1394 isFloat = true;
1395 expectSize = 1;
1396 break;
1397 case AINFO_DOCK_STATE:
1398 case AINFO_HIGH_PERFORMANCE_MODE:
1399 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1400 isFloat = false;
1401 expectSize = 1;
1402 break;
1403 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001404 // CUSTOM events must only contain float data; it may have variable size
1405 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1406 ints.size() ||
1407 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1408 handle < 0) {
1409 return BAD_VALUE;
1410 }
1411 isFloat = true;
1412 isCustom = true;
1413 expectSize = floats.size();
1414 break;
1415 }
1416
1417 if (!isCustom && handle != -1) {
1418 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001419 }
1420
1421 // three events: first one is begin tag, last one is end tag, the one in the middle
1422 // is the payload.
1423 sensors_event_t event[3];
1424 int64_t timestamp = elapsedRealtimeNano();
1425 for (sensors_event_t* i = event; i < event + 3; i++) {
1426 *i = (sensors_event_t) {
1427 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001428 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001429 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1430 .timestamp = timestamp++,
1431 .additional_info = (additional_info_event_t) {
1432 .serial = 0
1433 }
1434 };
1435 }
1436
1437 event[0].additional_info.type = AINFO_BEGIN;
1438 event[1].additional_info.type = type;
1439 event[2].additional_info.type = AINFO_END;
1440
1441 if (isFloat) {
1442 if (floats.size() != expectSize) {
1443 return BAD_VALUE;
1444 }
1445 for (size_t i = 0; i < expectSize; ++i) {
1446 event[1].additional_info.data_float[i] = floats[i];
1447 }
1448 } else {
1449 if (ints.size() != expectSize) {
1450 return BAD_VALUE;
1451 }
1452 for (size_t i = 0; i < expectSize; ++i) {
1453 event[1].additional_info.data_int32[i] = ints[i];
1454 }
1455 }
1456
1457 SensorDevice& dev(SensorDevice::getInstance());
1458 for (sensors_event_t* i = event; i < event + 3; i++) {
1459 int ret = dev.injectSensorData(i);
1460 if (ret != NO_ERROR) {
1461 return ret;
1462 }
1463 }
1464 return NO_ERROR;
1465}
1466
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001467status_t SensorService::resetToNormalMode() {
1468 Mutex::Autolock _l(mLock);
1469 return resetToNormalModeLocked();
1470}
1471
1472status_t SensorService::resetToNormalModeLocked() {
1473 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001474 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301475 if (err == NO_ERROR) {
1476 mCurrentOperatingMode = NORMAL;
1477 dev.enableAllSensors();
1478 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001479 return err;
1480}
1481
Peng Xu47e96012016-03-28 17:55:56 -07001482void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001483 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001484 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001485 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001486 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001487 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001488 int handle = mActiveSensors.keyAt(i);
1489 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001490 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001491 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1492 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001493 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001494 } else {
1495 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001496 }
Aravind Akella8a969552014-09-28 17:52:41 -07001497 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001498 }
1499 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001500 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001501 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001502 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001503 c, i, handle);
1504
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001505 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001506 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001507 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001508 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001509 delete rec;
1510 size--;
1511 } else {
1512 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001513 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001514 }
Aravind Akella8a969552014-09-28 17:52:41 -07001515 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001516 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001517 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001518 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001519 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001520 }
Peng Xu4f707f82016-09-26 11:28:32 -07001521
Brian Stack793f4642019-04-18 17:21:34 -07001522 {
1523 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1524 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1525 if (iter != sPackageTargetVersion.end()) {
1526 sPackageTargetVersion.erase(iter);
1527 }
1528 }
1529
Peng Xu4f707f82016-09-26 11:28:32 -07001530 SensorDevice& dev(SensorDevice::getInstance());
1531 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001532}
1533
Peng Xue36e3472016-11-03 11:57:10 -07001534void SensorService::cleanupConnection(SensorDirectConnection* c) {
1535 Mutex::Autolock _l(mLock);
1536
1537 SensorDevice& dev(SensorDevice::getInstance());
1538 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001539 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001540}
1541
Peng Xu755c4512016-04-07 23:15:14 -07001542sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001543 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001544}
1545
Mathias Agopianfc328812010-07-14 23:41:37 -07001546status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001547 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001548 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001549 if (mInitCheck != NO_ERROR)
1550 return mInitCheck;
1551
Peng Xu755c4512016-04-07 23:15:14 -07001552 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1553 if (sensor == nullptr ||
1554 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001555 return BAD_VALUE;
1556 }
1557
Brian Duddie967ce172019-06-10 11:08:27 -07001558 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001559 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001560 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001561 return INVALID_OPERATION;
1562 }
1563
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001564 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001565 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001566 rec = new SensorRecord(connection);
1567 mActiveSensors.add(handle, rec);
1568 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001569 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001570 }
Brian Stack26029ee2019-04-22 17:25:49 -07001571
1572 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1573 // the recent event as stale to ensure that the previous event is not sent to a client. This
1574 // ensures on-change events that were generated during a previous sensor activation are not
1575 // erroneously sent to newly connected clients, especially if a second client registers for
1576 // an on-change sensor before the first client receives the updated event. Once an updated
1577 // event is received, the recent events will be marked as current, and any new clients will
1578 // immediately receive the most recent event.
1579 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1580 auto logger = mRecentEvent.find(handle);
1581 if (logger != mRecentEvent.end()) {
1582 logger->second->setLastEventStale();
1583 }
1584 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001585 } else {
1586 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001587 // this sensor is already activated, but we are adding a connection that uses it.
1588 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001589 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001590 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001591 // NOTE: The wake_up flag of this event may get set to
1592 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001593
1594 auto logger = mRecentEvent.find(handle);
1595 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001596 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001597 // Verify that the last sensor event was generated from the current activation
1598 // of the sensor. If not, it is possible for an on-change sensor to receive a
1599 // sensor event that is stale if two clients re-activate the sensor
1600 // simultaneously.
1601 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001602 event.sensor = handle;
1603 if (event.version == sizeof(sensors_event_t)) {
1604 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1605 setWakeLockAcquiredLocked(true);
1606 }
Yi Kong8f313e32018-07-17 14:13:29 -07001607 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001608 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001609 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001610 }
1611 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001612 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001613 }
1614 }
1615 }
1616 }
1617
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001618 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001619 BatteryService::enableSensor(connection->getUid(), handle);
1620 // the sensor was added (which means it wasn't already there)
1621 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001622 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001623 } else {
1624 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1625 handle, connection.get());
1626 }
1627
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301628 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001629 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301630 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1631 samplingPeriodNs = maxDelayNs;
1632 }
1633
Aravind Akella724d91d2013-06-27 12:04:23 -07001634 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1635 if (samplingPeriodNs < minDelayNs) {
1636 samplingPeriodNs = minDelayNs;
1637 }
1638
Aravind Akella6c2664a2014-08-13 12:24:50 -07001639 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1640 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001641 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1642
Aravind Akella4949c502015-02-11 15:54:35 -08001643 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001644 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001645
Peng Xu20483c42015-10-26 15:14:43 -07001646 // Call flush() before calling activate() on the sensor. Wait for a first
1647 // flush complete event before sending events on this connection. Ignore
1648 // one-shot sensors which don't support flush(). Ignore on-change sensors
1649 // to maintain the on-change logic (any on-change events except the initial
1650 // one should be trigger by a change in value). Also if this sensor isn't
1651 // already active, don't call flush().
1652 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001653 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001654 rec->getNumConnections() > 1) {
1655 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001656 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001657 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001658 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001659 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001660 } else {
1661 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001662 }
1663 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001664
1665 if (err == NO_ERROR) {
1666 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1667 err = sensor->activate(connection.get(), true);
1668 }
1669
Aravind Akella8a969552014-09-28 17:52:41 -07001670 if (err == NO_ERROR) {
1671 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001672
Brian Stack240d1d62019-05-17 09:49:39 -07001673 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1674 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001675 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1676 }
1677
Peng Xu51224682017-03-10 16:57:27 -08001678 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1679 SensorRegistrationInfo(handle, connection->getPackageName(),
1680 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001681 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001682 }
1683
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001684 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001685 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001686 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001687 }
1688 return err;
1689}
1690
Peng Xu47e96012016-03-28 17:55:56 -07001691status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001692 if (mInitCheck != NO_ERROR)
1693 return mInitCheck;
1694
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001695 Mutex::Autolock _l(mLock);
1696 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001697 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001698 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1699 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001700
1701 }
1702 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001703 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1704 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001705 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001706 }
1707 return err;
1708}
1709
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001710status_t SensorService::cleanupWithoutDisable(
1711 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001712 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001713 return cleanupWithoutDisableLocked(connection, handle);
1714}
1715
1716status_t SensorService::cleanupWithoutDisableLocked(
1717 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001718 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001719 if (rec) {
1720 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001721 if (connection->removeSensor(handle)) {
1722 BatteryService::disableSensor(connection->getUid(), handle);
1723 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001724 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001725 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001726 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001727 }
1728 // see if this sensor becomes inactive
1729 if (rec->removeConnection(connection)) {
1730 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001731 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001732 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001733 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001734 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001735 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001736 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001737}
1738
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001739status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001740 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001741 if (mInitCheck != NO_ERROR)
1742 return mInitCheck;
1743
Peng Xu755c4512016-04-07 23:15:14 -07001744 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1745 if (sensor == nullptr ||
1746 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001747 return BAD_VALUE;
1748 }
1749
Mathias Agopian1cd70002010-07-21 15:59:50 -07001750 if (ns < 0)
1751 return BAD_VALUE;
1752
Mathias Agopian62569ec2011-11-07 21:21:47 -08001753 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1754 if (ns < minDelayNs) {
1755 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001756 }
1757
Mathias Agopianf001c922010-11-11 17:58:51 -08001758 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001759}
1760
Svetoslavb412f6e2015-04-29 16:50:41 -07001761status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1762 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001763 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001764 SensorDevice& dev(SensorDevice::getInstance());
1765 const int halVersion = dev.getHalDeviceVersion();
1766 status_t err(NO_ERROR);
1767 Mutex::Autolock _l(mLock);
1768 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07001769 for (int handle : connection->getActiveSensorHandles()) {
Peng Xu755c4512016-04-07 23:15:14 -07001770 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1771 if (sensor == nullptr) {
1772 continue;
1773 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001774 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1775 ALOGE("flush called on a one-shot sensor");
1776 err = INVALID_OPERATION;
1777 continue;
1778 }
Aravind Akella8493b792014-09-08 15:45:47 -07001779 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001780 // For older devices just increment pending flush count which will send a trivial
1781 // flush complete event.
Stan Rokita29adc8c2020-07-06 17:38:03 -07001782 if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
1783 ALOGE("flush called on an inaccessible sensor");
1784 err = INVALID_OPERATION;
1785 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001786 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001787 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1788 err = INVALID_OPERATION;
1789 continue;
1790 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001791 status_t err_flush = sensor->flush(connection.get(), handle);
1792 if (err_flush == NO_ERROR) {
1793 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001794 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001795 }
1796 err = (err_flush != NO_ERROR) ? err_flush : err;
1797 }
Aravind Akella70018042014-04-07 22:52:37 +00001798 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07001799 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001800}
Aravind Akella70018042014-04-07 22:52:37 +00001801
Svetoslavb412f6e2015-04-29 16:50:41 -07001802bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1803 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001804 // Check if a permission is required for this sensor
1805 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001806 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001807 }
1808
Brian Stack793f4642019-04-18 17:21:34 -07001809 const int32_t opCode = sensor.getRequiredAppOp();
1810 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1811 IPCThreadState::self()->getCallingUid(), opPackageName);
Brian Stack6a700f92019-05-08 17:02:53 -07001812 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
Brian Duddie457e6392020-06-19 11:38:29 -07001813 int targetSdkVersion = getTargetSdkVersion(opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -07001814
Brian Stack793f4642019-04-18 17:21:34 -07001815 bool canAccess = false;
Brian Duddie457e6392020-06-19 11:38:29 -07001816 if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
1817 (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1818 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
1819 // Allow access to step sensors if the application targets pre-Q, which is before the
1820 // requirement to hold the AR permission to access Step Counter and Step Detector events
1821 // was introduced.
1822 canAccess = true;
1823 } else if (hasPermissionForSensor(sensor)) {
Brian Stack6a700f92019-05-08 17:02:53 -07001824 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1825 if (opCode < 0 || appOpAllowed) {
Brian Stack793f4642019-04-18 17:21:34 -07001826 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001827 }
Brian Stack793f4642019-04-18 17:21:34 -07001828 }
1829
1830 if (canAccess) {
1831 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1832 } else {
Brian Duddie457e6392020-06-19 11:38:29 -07001833 ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
1834 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Brian Stack793f4642019-04-18 17:21:34 -07001835 }
1836
1837 return canAccess;
1838}
1839
1840bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001841 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001842 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001843
1844 // Runtime permissions can't use the cache as they may change.
1845 if (sensor.isRequiredPermissionRuntime()) {
1846 hasPermission = checkPermission(String16(requiredPermission),
1847 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001848 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001849 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1850 }
Brian Stack793f4642019-04-18 17:21:34 -07001851 return hasPermission;
1852}
Svetoslavb412f6e2015-04-29 16:50:41 -07001853
Brian Stack793f4642019-04-18 17:21:34 -07001854int SensorService::getTargetSdkVersion(const String16& opPackageName) {
Anthony Stange07eb4212020-08-28 14:50:28 -04001855 // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
1856 // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
1857 // give it elevated privileges.
1858 if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
1859 return -1;
1860 }
1861
Brian Stack793f4642019-04-18 17:21:34 -07001862 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1863 int targetSdkVersion = -1;
1864 auto entry = sPackageTargetVersion.find(opPackageName);
1865 if (entry != sPackageTargetVersion.end()) {
1866 targetSdkVersion = entry->second;
1867 } else {
1868 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1869 if (binder != nullptr) {
1870 sp<content::pm::IPackageManagerNative> packageManager =
1871 interface_cast<content::pm::IPackageManagerNative>(binder);
1872 if (packageManager != nullptr) {
1873 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1874 opPackageName, &targetSdkVersion);
1875 if (!status.isOk()) {
1876 targetSdkVersion = -1;
1877 }
1878 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001879 }
Brian Stack793f4642019-04-18 17:21:34 -07001880 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001881 }
Brian Stack793f4642019-04-18 17:21:34 -07001882 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001883}
1884
Aravind Akella9a844cf2014-02-11 18:58:52 -08001885void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001886 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1887 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001888}
1889
Brian Duddie967ce172019-06-10 11:08:27 -07001890void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001891 if (!mWakeLockAcquired) {
1892 return;
1893 }
1894 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001895 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1896 if (connection->needsWakeLock()) {
1897 releaseLock = false;
1898 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001899 }
1900 }
1901 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001902 setWakeLockAcquiredLocked(false);
1903 }
1904}
1905
1906void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1907 Mutex::Autolock _l(mLock);
1908 connection->writeToSocketFromCache();
1909 if (connection->needsWakeLock()) {
1910 setWakeLockAcquiredLocked(true);
1911 }
1912}
1913
Aravind Akella4949c502015-02-11 15:54:35 -08001914bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001915 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001916}
1917
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001918bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
Brian Stack5180e462019-03-08 17:15:19 -08001919 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001920 String8 package(opPackageName);
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001921 return !isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001922 }
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -07001923 return false;
Peng Xue36e3472016-11-03 11:57:10 -07001924}
1925
Svet Ganove752a5c2018-01-15 17:14:20 -08001926void SensorService::UidPolicy::registerSelf() {
1927 ActivityManager am;
1928 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1929 | ActivityManager::UID_OBSERVER_IDLE
1930 | ActivityManager::UID_OBSERVER_ACTIVE,
1931 ActivityManager::PROCESS_STATE_UNKNOWN,
1932 String16("android"));
1933}
1934
1935void SensorService::UidPolicy::unregisterSelf() {
1936 ActivityManager am;
1937 am.unregisterUidObserver(this);
1938}
1939
1940void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1941 onUidIdle(uid, disabled);
1942}
1943
1944void SensorService::UidPolicy::onUidActive(uid_t uid) {
1945 {
1946 Mutex::Autolock _l(mUidLock);
1947 mActiveUids.insert(uid);
1948 }
1949 sp<SensorService> service = mService.promote();
1950 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001951 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001952 }
1953}
1954
1955void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1956 bool deleted = false;
1957 {
1958 Mutex::Autolock _l(mUidLock);
1959 if (mActiveUids.erase(uid) > 0) {
1960 deleted = true;
1961 }
1962 }
1963 if (deleted) {
1964 sp<SensorService> service = mService.promote();
1965 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001966 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001967 }
1968 }
1969}
1970
1971void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1972 updateOverrideUid(uid, active, true);
1973}
1974
1975void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1976 updateOverrideUid(uid, false, false);
1977}
1978
1979void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1980 bool wasActive = false;
1981 bool isActive = false;
1982 {
1983 Mutex::Autolock _l(mUidLock);
1984 wasActive = isUidActiveLocked(uid);
1985 mOverrideUids.erase(uid);
1986 if (insert) {
1987 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1988 }
1989 isActive = isUidActiveLocked(uid);
1990 }
1991 if (wasActive != isActive) {
1992 sp<SensorService> service = mService.promote();
1993 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001994 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001995 }
1996 }
1997}
1998
1999bool SensorService::UidPolicy::isUidActive(uid_t uid) {
2000 // Non-app UIDs are considered always active
2001 if (uid < FIRST_APPLICATION_UID) {
2002 return true;
2003 }
2004 Mutex::Autolock _l(mUidLock);
2005 return isUidActiveLocked(uid);
2006}
2007
2008bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2009 // Non-app UIDs are considered always active
2010 if (uid < FIRST_APPLICATION_UID) {
2011 return true;
2012 }
2013 auto it = mOverrideUids.find(uid);
2014 if (it != mOverrideUids.end()) {
2015 return it->second;
2016 }
2017 return mActiveUids.find(uid) != mActiveUids.end();
2018}
2019
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07002020bool SensorService::isUidActive(uid_t uid) {
2021 return mUidPolicy->isUidActive(uid);
2022}
2023
Michael Groover5e1f60b2018-12-04 22:34:29 -08002024void SensorService::SensorPrivacyPolicy::registerSelf() {
2025 SensorPrivacyManager spm;
2026 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2027 spm.addSensorPrivacyListener(this);
2028}
2029
2030void SensorService::SensorPrivacyPolicy::unregisterSelf() {
2031 SensorPrivacyManager spm;
2032 spm.removeSensorPrivacyListener(this);
2033}
2034
2035bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2036 return mSensorPrivacyEnabled;
2037}
2038
2039binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2040 mSensorPrivacyEnabled = enabled;
2041 sp<SensorService> service = mService.promote();
2042 if (service != nullptr) {
2043 if (enabled) {
2044 service->disableAllSensors();
2045 } else {
2046 service->enableAllSensors();
2047 }
2048 }
2049 return binder::Status::ok();
2050}
Brian Duddie967ce172019-06-10 11:08:27 -07002051
2052SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2053 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2054 : mConnectionHolder(holder), mAutolock(mutex) {}
2055
2056template<typename ConnectionType>
2057const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2058 const SortedVector<wp<ConnectionType>>& connectionList,
2059 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2060 referenceHolder->emplace_back();
2061 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2062 for (const wp<ConnectionType>& weakConnection : connectionList){
2063 sp<ConnectionType> connection = weakConnection.promote();
2064 if (connection != nullptr) {
2065 connections.push_back(std::move(connection));
2066 }
2067 }
2068 return connections;
2069}
2070
2071const std::vector<sp<SensorService::SensorEventConnection>>&
2072 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2073 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2074 &mReferencedActiveConnections);
2075}
2076
2077const std::vector<sp<SensorService::SensorDirectConnection>>&
2078 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2079 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2080 &mReferencedDirectConnections);
2081}
2082
2083void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2084 const sp<SensorService::SensorEventConnection>& connection) {
2085 if (mActiveConnections.indexOf(connection) < 0) {
2086 mActiveConnections.add(connection);
2087 }
2088}
2089
2090void SensorService::SensorConnectionHolder::removeEventConnection(
2091 const wp<SensorService::SensorEventConnection>& connection) {
2092 mActiveConnections.remove(connection);
2093}
2094
2095void SensorService::SensorConnectionHolder::addDirectConnection(
2096 const sp<SensorService::SensorDirectConnection>& connection) {
2097 mDirectConnections.add(connection);
2098}
2099
2100void SensorService::SensorConnectionHolder::removeDirectConnection(
2101 const wp<SensorService::SensorDirectConnection>& connection) {
2102 mDirectConnections.remove(connection);
2103}
2104
2105SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2106 return ConnectionSafeAutolock(*this, mutex);
2107}
2108
2109} // namespace android