blob: 29df82582f0fbba52458f49e7cfcdfb462ef5cbf [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Stack793f4642019-04-18 17:21:34 -070016#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080017#include <android/util/ProtoOutputStream.h>
18#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080019#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070021#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070022#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080023#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070024#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080025#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070026#include <cutils/properties.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070027#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070028#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080029#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070030#include <openssl/digest.h>
31#include <openssl/hmac.h>
32#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070033#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080034#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070035#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070036
Mathias Agopian787ac1b2012-09-18 18:49:18 -070037#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070038#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080039#include "GravitySensor.h"
40#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070041#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080042#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070043#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070044#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080045
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070047#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080049#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080050#include "SensorRecord.h"
51#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080052
Brian Stack51498e62018-10-03 10:52:21 -070053#include <ctime>
Peng Xueb4d6282015-12-10 18:02:41 -080054#include <inttypes.h>
55#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070056#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080057#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080058#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070059#include <sys/stat.h>
60#include <sys/types.h>
61#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070062
Svet Ganove752a5c2018-01-15 17:14:20 -080063#include <private/android_filesystem_config.h>
64
Mathias Agopianfc328812010-07-14 23:41:37 -070065namespace android {
66// ---------------------------------------------------------------------------
67
Mathias Agopian33015422011-05-27 18:18:13 -070068/*
69 * Notes:
70 *
71 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070072 * - run mag sensor from time to time to force calibration
73 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
74 *
75 */
76
Aravind Akella8ef3c892015-07-10 11:24:28 -070077const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070078uint8_t SensorService::sHmacGlobalKey[128] = {};
79bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070080std::map<String16, int> SensorService::sPackageTargetVersion;
81Mutex SensorService::sPackageTargetVersionLock;
82AppOpsManager SensorService::sAppOpsManager;
Greg Kaiser53ca2e02016-06-21 16:11:14 -070083
84#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
85#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070086#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070087
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070088// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070089static const String16 sDumpPermission("android.permission.DUMP");
90static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080091static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070092
Mathias Agopianfc328812010-07-14 23:41:37 -070093SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070094 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070095 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +090096 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -080097 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -070098}
99
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700100bool SensorService::initializeHmacKey() {
101 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
102 if (fd != -1) {
103 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
104 close(fd);
105 if (result == sizeof(sHmacGlobalKey)) {
106 return true;
107 }
108 ALOGW("Unable to read HMAC key; generating new one.");
109 }
110
111 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
112 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
113 return false;
114 }
115
116 // We need to make sure this is only readable to us.
117 bool wroteKey = false;
118 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
119 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
120 S_IRUSR|S_IWUSR);
121 if (fd != -1) {
122 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
123 close(fd);
124 wroteKey = (result == sizeof(sHmacGlobalKey));
125 }
126 if (wroteKey) {
127 ALOGI("Generated new HMAC key.");
128 } else {
129 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
130 "after reboot.");
131 }
132 // Even if we failed to write the key we return true, because we did
133 // initialize the HMAC key.
134 return true;
135}
136
Peng Xu98d30f62016-08-01 18:12:11 -0700137// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
138void SensorService::enableSchedFifoMode() {
139 struct sched_param param = {0};
140 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
141 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
142 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
143 }
144}
145
Peng Xu47e96012016-03-28 17:55:56 -0700146void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000147 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800148 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700149
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700150 sHmacGlobalKeyIsValid = initializeHmacKey();
151
Mathias Agopianf001c922010-11-11 17:58:51 -0800152 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800153 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700154 ssize_t count = dev.getSensorList(&list);
155 if (count > 0) {
156 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700157 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700158 uint32_t virtualSensorsNeeds =
159 (1<<SENSOR_TYPE_GRAVITY) |
160 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700161 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
162 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
163 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700164
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700165 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700166 bool useThisSensor=true;
167
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700168 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700169 case SENSOR_TYPE_ACCELEROMETER:
170 hasAccel = true;
171 break;
172 case SENSOR_TYPE_MAGNETIC_FIELD:
173 hasMag = true;
174 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700175 case SENSOR_TYPE_ORIENTATION:
176 orientationIndex = i;
177 break;
178 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700179 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700180 hasGyro = true;
181 break;
182 case SENSOR_TYPE_GRAVITY:
183 case SENSOR_TYPE_LINEAR_ACCELERATION:
184 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700185 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
186 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
187 if (IGNORE_HARDWARE_FUSION) {
188 useThisSensor = false;
189 } else {
190 virtualSensorsNeeds &= ~(1<<list[i].type);
191 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700192 break;
193 }
Peng Xuf66684a2015-07-23 11:41:53 -0700194 if (useThisSensor) {
195 registerSensor( new HardwareSensor(list[i]) );
196 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700197 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700198
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700199 // it's safe to instantiate the SensorFusion object here
200 // (it wants to be instantiated after h/w sensors have been
201 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700202 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700203
Aravind Akellaf5047892015-07-20 17:29:33 -0700204 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700205 // Add Android virtual sensors if they're not already
206 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700207 bool needRotationVector =
208 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700209
Peng Xu0cc8f802016-04-05 23:46:03 -0700210 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
211 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700212
Peng Xu0cc8f802016-04-05 23:46:03 -0700213 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700214 registerSensor( new CorrectedGyroSensor(list, count), true, true);
215 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700216 }
217
Peng Xuf66684a2015-07-23 11:41:53 -0700218 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700219 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
220 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700221
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800222 bool needLinearAcceleration =
223 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
224 registerSensor(new LinearAccelerationSensor(list, count),
225 !needLinearAcceleration, true);
226
Peng Xu0cc8f802016-04-05 23:46:03 -0700227 bool needGameRotationVector =
228 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
229 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700230 }
231
232 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700233 bool needGeoMagRotationVector =
234 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
235 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700236 }
237
Aravind Akella5466c3d2014-08-22 16:11:10 -0700238 // Check if the device really supports batching by looking at the FIFO event
239 // counts for each sensor.
240 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700241 mSensors.forEachSensor(
242 [&batchingSupported] (const Sensor& s) -> bool {
243 if (s.getFifoMaxEventCount() > 0) {
244 batchingSupported = true;
245 }
246 return !batchingSupported;
247 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700248
249 if (batchingSupported) {
250 // Increase socket buffer size to a max of 100 KB for batching capabilities.
251 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
252 } else {
253 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
254 }
255
256 // Compare the socketBufferSize value against the system limits and limit
257 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700258 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
259 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700260 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700261 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700262 size_t maxSystemSocketBufferSize;
263 sscanf(line, "%zu", &maxSystemSocketBufferSize);
264 if (mSocketBufferSize > maxSystemSocketBufferSize) {
265 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700266 }
267 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700268 if (fp) {
269 fclose(fp);
270 }
271
Aravind Akella9a844cf2014-02-11 18:58:52 -0800272 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700273 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700274 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
275 mSensorEventBuffer = new sensors_event_t[minBufferSize];
276 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700277 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700278 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700279
Aravind Akella18d6d512015-06-18 14:18:28 -0700280 mNextSensorRegIndex = 0;
281 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
282 mLastNSensorRegistrations.push();
283 }
284
285 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700286 mAckReceiver = new SensorEventAckReceiver(this);
287 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700288 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700289
290 // priority can only be changed after run
291 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800292
293 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800294 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800295
296 // Start watching sensor privacy changes
297 mSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800298 }
299 }
300}
301
302void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
Brian Duddie967ce172019-06-10 11:08:27 -0700303 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700304 const auto& connections = connLock.getActiveConnections();
Arthur Ishiguro14c96b12020-03-26 15:09:03 -0700305 const auto& directConnections = connLock.getDirectConnections();
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700306
307 mLock.unlock();
308 for (const sp<SensorEventConnection>& conn : connections) {
Brian Duddie967ce172019-06-10 11:08:27 -0700309 if (conn->getUid() == uid) {
310 conn->setSensorAccess(hasAccess);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700311 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700312 }
Arthur Ishiguro14c96b12020-03-26 15:09:03 -0700313
314 for (const sp<SensorDirectConnection>& conn : directConnections) {
315 if (conn->getUid() == uid) {
316 conn->setSensorAccess(hasAccess);
317 }
318 }
Arthur Ishiguro410d5672020-04-06 08:50:20 -0700319
320 // Lock the mutex again for clean shutdown
321 mLock.lock();
Mathias Agopianfc328812010-07-14 23:41:37 -0700322}
323
Peng Xu0cc8f802016-04-05 23:46:03 -0700324const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
325 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800326 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700327 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700328 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700329 return s->getSensor();
330 } else {
331 return mSensors.getNonSensor();
332 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800333}
334
Peng Xu6a2d3a02015-12-21 12:00:23 -0800335const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700336 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800337}
338
Peng Xu6a2d3a02015-12-21 12:00:23 -0800339bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700340 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800341
342 const auto i = mRecentEvent.find(handle);
343 if (i != mRecentEvent.end()) {
344 delete i->second;
345 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800346 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700347 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800348}
349
Peng Xu0cc8f802016-04-05 23:46:03 -0700350const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
351 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700352}
353
Peng Xu47e96012016-03-28 17:55:56 -0700354SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800355 for (auto && entry : mRecentEvent) {
356 delete entry.second;
357 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800358 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800359 mSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700360}
361
362status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700363 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700364 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800365 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700366 IPCThreadState::self()->getCallingPid(),
367 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700368 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700369 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700370 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800371 return INVALID_OPERATION;
372 }
Brian Duddie967ce172019-06-10 11:08:27 -0700373 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800374 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700375 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700376 // If already in restricted mode. Ignore.
377 if (mCurrentOperatingMode == RESTRICTED) {
378 return status_t(NO_ERROR);
379 }
380 // If in any mode other than normal, ignore.
381 if (mCurrentOperatingMode != NORMAL) {
382 return INVALID_OPERATION;
383 }
Peng Xue36e3472016-11-03 11:57:10 -0700384
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700385 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800386 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700387 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700388 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700389 return status_t(NO_ERROR);
390 } else if (args.size() == 1 && args[0] == String16("enable")) {
391 // If currently in restricted mode, reset back to NORMAL mode else ignore.
392 if (mCurrentOperatingMode == RESTRICTED) {
393 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800394 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700395 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700396 }
Aravind Akella841a5922015-06-29 12:37:48 -0700397 if (mCurrentOperatingMode == DATA_INJECTION) {
398 resetToNormalModeLocked();
399 }
400 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700401 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700402 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
403 if (mCurrentOperatingMode == NORMAL) {
404 dev.disableAllSensors();
405 status_t err = dev.setMode(DATA_INJECTION);
406 if (err == NO_ERROR) {
407 mCurrentOperatingMode = DATA_INJECTION;
408 } else {
409 // Re-enable sensors.
410 dev.enableAllSensors();
411 }
412 mWhiteListedPackage.setTo(String8(args[1]));
413 return NO_ERROR;
414 } else if (mCurrentOperatingMode == DATA_INJECTION) {
415 // Already in DATA_INJECTION mode. Treat this as a no_op.
416 return NO_ERROR;
417 } else {
418 // Transition to data injection mode supported only from NORMAL mode.
419 return INVALID_OPERATION;
420 }
Mike Ma24743862020-01-29 00:36:55 -0800421 } else if (args.size() == 1 && args[0] == String16("--proto")) {
422 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700423 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700424 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700425 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700426 } else {
427 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700428 //
Brian Stack51498e62018-10-03 10:52:21 -0700429 timespec curTime;
430 clock_gettime(CLOCK_REALTIME, &curTime);
431 struct tm* timeinfo = localtime(&(curTime.tv_sec));
432 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
433 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800434 result.append("Sensor Device:\n");
435 result.append(SensorDevice::getInstance().dump().c_str());
436
437 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700438 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700439
Peng Xu6a2d3a02015-12-21 12:00:23 -0800440 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700441 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700442
Peng Xu0cc8f802016-04-05 23:46:03 -0700443 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800444 for (auto&& i : mRecentEvent) {
445 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700446 if (!i.second->isEmpty()) {
447 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
448 i.second->setFormat("normal");
449 } else {
450 i.second->setFormat("mask_data");
451 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800452 // if there is events and sensor does not need special permission.
453 result.appendFormat("%s: ", s->getSensor().getName().string());
454 result.append(i.second->dump().c_str());
455 }
456 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700457
Aravind Akella444f2672015-05-07 12:40:52 -0700458 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700459 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700460 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
461 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700462 if (dev.isSensorActive(handle)) {
463 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
464 getSensorName(handle).string(),
465 handle,
466 mActiveSensors.valueAt(i)->getNumConnections());
467 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700468 }
469
Andreas Gamped4036b62015-07-28 13:49:04 -0700470 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700471 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700472 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
473 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700474 result.appendFormat("Mode :");
475 switch(mCurrentOperatingMode) {
476 case NORMAL:
477 result.appendFormat(" NORMAL\n");
478 break;
479 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700480 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700481 break;
482 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700483 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700484 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800485 result.appendFormat("Sensor Privacy: %s\n",
486 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700487
Brian Duddie967ce172019-06-10 11:08:27 -0700488 const auto& activeConnections = connLock.getActiveConnections();
489 result.appendFormat("%zd active connections\n", activeConnections.size());
490 for (size_t i=0 ; i < activeConnections.size() ; i++) {
491 result.appendFormat("Connection Number: %zu \n", i);
492 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700493 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700494
Brian Duddie967ce172019-06-10 11:08:27 -0700495 const auto& directConnections = connLock.getDirectConnections();
496 result.appendFormat("%zd direct connections\n", directConnections.size());
497 for (size_t i = 0 ; i < directConnections.size() ; i++) {
498 result.appendFormat("Direct connection %zu:\n", i);
499 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700500 }
501
Aravind Akella18d6d512015-06-18 14:18:28 -0700502 result.appendFormat("Previous Registrations:\n");
503 // Log in the reverse chronological order.
504 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
505 SENSOR_REGISTRATIONS_BUF_SIZE;
506 const int startIndex = currentIndex;
507 do {
508 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
509 if (SensorRegistrationInfo::isSentinel(reg_info)) {
510 // Ignore sentinel, proceed to next item.
511 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
512 SENSOR_REGISTRATIONS_BUF_SIZE;
513 continue;
514 }
Peng Xu51224682017-03-10 16:57:27 -0800515 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700516 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
517 SENSOR_REGISTRATIONS_BUF_SIZE;
518 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700519 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700520 }
521 write(fd, result.string(), result.size());
522 return NO_ERROR;
523}
524
Mike Ma24743862020-01-29 00:36:55 -0800525/**
526 * Dump debugging information as android.service.SensorServiceProto protobuf message using
527 * ProtoOutputStream.
528 *
529 * See proto definition and some notes about ProtoOutputStream in
530 * frameworks/base/core/proto/android/service/sensor_service.proto
531 */
532status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
533 using namespace service::SensorServiceProto;
534 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800535 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
536 if (!mSensors.hasAnySensor()) {
537 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
538 }
Mike Ma24743862020-01-29 00:36:55 -0800539 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
540
541 timespec curTime;
542 clock_gettime(CLOCK_REALTIME, &curTime);
543 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
544
545 // Write SensorDeviceProto
546 uint64_t token = proto.start(SENSOR_DEVICE);
547 SensorDevice::getInstance().dump(&proto);
548 proto.end(token);
549
550 // Write SensorListProto
551 token = proto.start(SENSORS);
552 mSensors.dump(&proto);
553 proto.end(token);
554
555 // Write SensorFusionProto
556 token = proto.start(FUSION_STATE);
557 SensorFusion::getInstance().dump(&proto);
558 proto.end(token);
559
560 // Write SensorEventsProto
561 token = proto.start(SENSOR_EVENTS);
562 for (auto&& i : mRecentEvent) {
563 sp<SensorInterface> s = mSensors.getInterface(i.first);
564 if (!i.second->isEmpty()) {
565 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
566 "normal" : "mask_data");
567 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
568 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
569 std::string(s->getSensor().getName().string()));
570 i.second->dump(&proto);
571 proto.end(mToken);
572 }
573 }
574 proto.end(token);
575
576 // Write ActiveSensorProto
577 SensorDevice& dev = SensorDevice::getInstance();
578 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
579 int handle = mActiveSensors.keyAt(i);
580 if (dev.isSensorActive(handle)) {
581 token = proto.start(ACTIVE_SENSORS);
582 proto.write(service::ActiveSensorProto::NAME,
583 std::string(getSensorName(handle).string()));
584 proto.write(service::ActiveSensorProto::HANDLE, handle);
585 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
586 int(mActiveSensors.valueAt(i)->getNumConnections()));
587 proto.end(token);
588 }
589 }
590
591 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
592 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
593 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
594
595 switch(mCurrentOperatingMode) {
596 case NORMAL:
597 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
598 break;
599 case RESTRICTED:
600 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
601 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
602 break;
603 case DATA_INJECTION:
604 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
605 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
606 break;
607 default:
608 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
609 }
610 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
611
612 // Write repeated SensorEventConnectionProto
613 const auto& activeConnections = connLock->getActiveConnections();
614 for (size_t i = 0; i < activeConnections.size(); i++) {
615 token = proto.start(ACTIVE_CONNECTIONS);
616 activeConnections[i]->dump(&proto);
617 proto.end(token);
618 }
619
620 // Write repeated SensorDirectConnectionProto
621 const auto& directConnections = connLock->getDirectConnections();
622 for (size_t i = 0 ; i < directConnections.size() ; i++) {
623 token = proto.start(DIRECT_CONNECTIONS);
624 directConnections[i]->dump(&proto);
625 proto.end(token);
626 }
627
628 // Write repeated SensorRegistrationInfoProto
629 const int startIndex = mNextSensorRegIndex;
630 int curr = startIndex;
631 do {
632 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
633 if (SensorRegistrationInfo::isSentinel(reg_info)) {
634 // Ignore sentinel, proceed to next item.
635 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
636 continue;
637 }
638 token = proto.start(PREVIOUS_REGISTRATIONS);
639 reg_info.dump(&proto);
640 proto.end(token);
641 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
642 } while (startIndex != curr);
643
644 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
645}
646
Michael Groover5e1f60b2018-12-04 22:34:29 -0800647void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700648 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
649 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800650}
651
Brian Duddie967ce172019-06-10 11:08:27 -0700652void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800653 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700654 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
655 connection->updateSensorSubscriptions();
656 }
Brian Duddie967ce172019-06-10 11:08:27 -0700657 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
Arthur Ishiguro14c96b12020-03-26 15:09:03 -0700658 connection->updateSensorSubscriptions();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800659 }
660 dev.disableAllSensors();
661 // Clear all pending flush connections for all active sensors. If one of the active
662 // connections has called flush() and the underlying sensor has been disabled before a
663 // flush complete event is returned, we need to remove the connection from this queue.
664 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
665 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
666 }
667}
668
669void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700670 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
671 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800672}
673
Brian Duddie967ce172019-06-10 11:08:27 -0700674void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800675 // sensors should only be enabled if the operating state is not restricted and sensor
676 // privacy is not enabled.
677 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
678 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
679 mCurrentOperatingMode,
680 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
681 return;
682 }
683 SensorDevice& dev(SensorDevice::getInstance());
684 dev.enableAllSensors();
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700685 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
686 connection->updateSensorSubscriptions();
687 }
Brian Duddie967ce172019-06-10 11:08:27 -0700688 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
Arthur Ishiguro14c96b12020-03-26 15:09:03 -0700689 connection->updateSensorSubscriptions();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800690 }
691}
692
Brian Duddie967ce172019-06-10 11:08:27 -0700693
Svet Ganove752a5c2018-01-15 17:14:20 -0800694// NOTE: This is a remote API - make sure all args are validated
695status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
696 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
697 return PERMISSION_DENIED;
698 }
699 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
700 return BAD_VALUE;
701 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700702 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800703 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700704 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800705 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700706 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800707 return handleGetUidState(args, out, err);
708 } else if (args.size() == 1 && args[0] == String16("help")) {
709 printHelp(out);
710 return NO_ERROR;
711 }
712 printHelp(err);
713 return BAD_VALUE;
714}
715
Tanmay Patild33a1822019-04-11 18:38:55 -0700716static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800717 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700718 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800719 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700720 ALOGE("Unknown package: '%s'", String8(packageName).string());
721 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800722 return BAD_VALUE;
723 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700724
725 if (userId < 0) {
726 ALOGE("Invalid user: %d", userId);
727 dprintf(err, "Invalid user: %d\n", userId);
728 return BAD_VALUE;
729 }
730
731 uid = multiuser_get_uid(userId, uid);
732 return NO_ERROR;
733}
734
735status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
736 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
737 if (!(args.size() == 3 || args.size() == 5)) {
738 printHelp(err);
739 return BAD_VALUE;
740 }
741
Svet Ganove752a5c2018-01-15 17:14:20 -0800742 bool active = false;
743 if (args[2] == String16("active")) {
744 active = true;
745 } else if ((args[2] != String16("idle"))) {
746 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
747 return BAD_VALUE;
748 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700749
750 int userId = 0;
751 if (args.size() == 5 && args[3] == String16("--user")) {
752 userId = atoi(String8(args[4]));
753 }
754
755 uid_t uid;
756 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
757 return BAD_VALUE;
758 }
759
Svet Ganove752a5c2018-01-15 17:14:20 -0800760 mUidPolicy->addOverrideUid(uid, active);
761 return NO_ERROR;
762}
763
764status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700765 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
766 if (!(args.size() == 2 || args.size() == 4)) {
767 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800768 return BAD_VALUE;
769 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700770
771 int userId = 0;
772 if (args.size() == 4 && args[2] == String16("--user")) {
773 userId = atoi(String8(args[3]));
774 }
775
776 uid_t uid;
777 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
778 return BAD_VALUE;
779 }
780
Svet Ganove752a5c2018-01-15 17:14:20 -0800781 mUidPolicy->removeOverrideUid(uid);
782 return NO_ERROR;
783}
784
785status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700786 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
787 if (!(args.size() == 2 || args.size() == 4)) {
788 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800789 return BAD_VALUE;
790 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700791
792 int userId = 0;
793 if (args.size() == 4 && args[2] == String16("--user")) {
794 userId = atoi(String8(args[3]));
795 }
796
797 uid_t uid;
798 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
799 return BAD_VALUE;
800 }
801
Svet Ganove752a5c2018-01-15 17:14:20 -0800802 if (mUidPolicy->isUidActive(uid)) {
803 return dprintf(out, "active\n");
804 } else {
805 return dprintf(out, "idle\n");
806 }
807}
808
809status_t SensorService::printHelp(int out) {
810 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700811 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
812 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
813 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800814 " help print this message\n");
815}
816
Peng Xu0cc8f802016-04-05 23:46:03 -0700817//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800818void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700819 sensors_event_t const* buffer, const int count) {
820 for (int i=0 ; i<count ; i++) {
821 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700822 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
823 handle = buffer[i].meta_data.sensor;
824 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700825 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700826 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700827 // If this buffer has an event from a one_shot sensor and this connection is registered
828 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700829 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700830 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
831 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800832 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700833 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700834
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700835 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700836 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700837}
838
Peng Xu47e96012016-03-28 17:55:56 -0700839bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000840 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700841
Peng Xueb4d6282015-12-10 18:02:41 -0800842 // each virtual sensor could generate an event per "real" event, that's why we need to size
843 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
844 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700845 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700846 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700847 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700848
Mathias Agopianf001c922010-11-11 17:58:51 -0800849 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700850
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700851 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700852 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700853 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
854 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700855 if(count == DEAD_OBJECT && device.isReconnecting()) {
856 device.reconnect();
857 continue;
858 } else {
859 ALOGE("sensor poll failed (%s)", strerror(-count));
860 break;
861 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700862 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700863
864 // Reset sensors_event_t.flags to zero for all events in the buffer.
865 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700866 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700867 }
Brian Duddie967ce172019-06-10 11:08:27 -0700868 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700869
Aravind Akella9a844cf2014-02-11 18:58:52 -0800870 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
871 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
872 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
873 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
874 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700875 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700876 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700877 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700878 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700879 }
880 }
881
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700882 if (wakeEvents > 0) {
883 if (!mWakeLockAcquired) {
884 setWakeLockAcquiredLocked(true);
885 }
886 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800887 }
Aravind Akella8493b792014-09-08 15:45:47 -0700888 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800889
Mathias Agopianf001c922010-11-11 17:58:51 -0800890 // handle virtual sensors
891 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700892 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700893 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800894 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700895 SensorFusion& fusion(SensorFusion::getInstance());
896 if (fusion.isEnabled()) {
897 for (size_t i=0 ; i<size_t(count) ; i++) {
898 fusion.process(event[i]);
899 }
900 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700901 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700902 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700903 if (count + k >= minBufferSize) {
904 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700905 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700906 count, k, minBufferSize);
907 break;
908 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800909 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700910 sp<SensorInterface> si = mSensors.getInterface(handle);
911 if (si == nullptr) {
912 ALOGE("handle %d is not an valid virtual sensor", handle);
913 continue;
914 }
915
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700916 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700917 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800918 k++;
919 }
920 }
921 }
922 if (k) {
923 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700924 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800925 count += k;
926 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700927 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700928 }
929 }
930 }
931
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700932 // handle backward compatibility for RotationVector sensor
933 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
934 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700935 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700936 // All the 4 components of the quaternion should be available
937 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700938 mSensorEventBuffer[i].data[4] = -1;
939 }
940 }
941 }
942
Brian Duddie967ce172019-06-10 11:08:27 -0700943 // Cache the list of active connections, since we use it in multiple places below but won't
944 // modify it here
945 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
946
Aravind Akella8493b792014-09-08 15:45:47 -0700947 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700948 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
949 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
950 // SensorEventConnection mapped to the corresponding flush_complete_event in
951 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700952 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700953 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
954 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
955 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700956 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700957 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
958 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700959 }
960 }
Peng Xu2576cb62016-01-20 00:22:09 -0800961
962 // handle dynamic sensor meta events, process registration and unregistration of dynamic
963 // sensor based on content of event.
964 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
965 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
966 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
967 const sensor_t& dynamicSensor =
968 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
969 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
970 handle, dynamicSensor.type, dynamicSensor.name);
971
Peng Xu0cc8f802016-04-05 23:46:03 -0700972 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800973 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700974 sensor_t s = dynamicSensor;
975 // make sure the dynamic sensor flag is set
976 s.flags |= DYNAMIC_SENSOR_MASK;
977 // force the handle to be consistent
978 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800979
980 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800981
Peng Xu0cc8f802016-04-05 23:46:03 -0700982 // This will release hold on dynamic sensor meta, so it should be called
983 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700984 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800985 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700986 } else {
987 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
988 }
Peng Xu2576cb62016-01-20 00:22:09 -0800989 } else {
990 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
991 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
992
993 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800994 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800995 ALOGE("Dynamic sensor release error.");
996 }
997
Brian Duddie967ce172019-06-10 11:08:27 -0700998 for (const sp<SensorEventConnection>& connection : activeConnections) {
999 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -08001000 }
1001 }
1002 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001003 }
1004
Aravind Akella9a844cf2014-02-11 18:58:52 -08001005 // Send our events to clients. Check the state of wake lock for each client and release the
1006 // lock if none of the clients need it.
1007 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001008 for (const sp<SensorEventConnection>& connection : activeConnections) {
1009 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1010 mMapFlushEventsToConnections);
1011 needsWakeLock |= connection->needsWakeLock();
1012 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1013 // Early check for one-shot sensors.
1014 if (connection->hasOneShotSensors()) {
1015 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001016 }
1017 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001018
Aravind Akella9a844cf2014-02-11 18:58:52 -08001019 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001020 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001021 }
Aravind Akella8493b792014-09-08 15:45:47 -07001022 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001023
Steve Block3c20fbe2012-01-05 23:22:43 +00001024 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001025 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001026 return false;
1027}
1028
Aravind Akella56ae4262014-07-10 16:01:10 -07001029sp<Looper> SensorService::getLooper() const {
1030 return mLooper;
1031}
1032
Aravind Akellab4373ac2014-10-29 17:55:20 -07001033void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001034 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1035 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1036 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001037 }
Brian Duddie967ce172019-06-10 11:08:27 -07001038 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001039}
1040
1041void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1042 if (acquire) {
1043 if (!mWakeLockAcquired) {
1044 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1045 mWakeLockAcquired = true;
1046 }
1047 mLooper->wake();
1048 } else {
1049 if (mWakeLockAcquired) {
1050 release_wake_lock(WAKE_LOCK_NAME);
1051 mWakeLockAcquired = false;
1052 }
1053 }
1054}
1055
Aravind Akellab4373ac2014-10-29 17:55:20 -07001056bool SensorService::isWakeLockAcquired() {
1057 Mutex::Autolock _l(mLock);
1058 return mWakeLockAcquired;
1059}
1060
Aravind Akella56ae4262014-07-10 16:01:10 -07001061bool SensorService::SensorEventAckReceiver::threadLoop() {
1062 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001063 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001064 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001065 bool wakeLockAcquired = mService->isWakeLockAcquired();
1066 int timeout = -1;
1067 if (wakeLockAcquired) timeout = 5000;
1068 int ret = looper->pollOnce(timeout);
1069 if (ret == ALOOPER_POLL_TIMEOUT) {
1070 mService->resetAllWakeLockRefCounts();
1071 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001072 } while(!Thread::exitPending());
1073 return false;
1074}
1075
Aravind Akella9a844cf2014-02-11 18:58:52 -08001076void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001077 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001078 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001079 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1080 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001081 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001082 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001083 }
Peng Xu2576cb62016-01-20 00:22:09 -08001084
Peng Xu6a2d3a02015-12-21 12:00:23 -08001085 auto logger = mRecentEvent.find(buffer[i].sensor);
1086 if (logger != mRecentEvent.end()) {
1087 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001088 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001089 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001090}
1091
Peng Xu47e96012016-03-28 17:55:56 -07001092void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001093 struct compar {
1094 static int cmp(void const* lhs, void const* rhs) {
1095 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1096 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001097 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001098 }
1099 };
1100 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1101}
1102
Mathias Agopian5d270722010-07-19 15:20:39 -07001103String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001104 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001105}
1106
Aravind Akellab4099e72013-10-15 15:43:10 -07001107bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001108 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1109 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001110}
1111
Aravind Akella9a844cf2014-02-11 18:58:52 -08001112bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001113 int handle = event.sensor;
1114 if (event.type == SENSOR_TYPE_META_DATA) {
1115 handle = event.meta_data.sensor;
1116 }
Peng Xu755c4512016-04-07 23:15:14 -07001117 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1118 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001119}
1120
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001121int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1122 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1123 // UUID is not supported for this device.
1124 return 0;
1125 }
1126 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1127 // This sensor can be uniquely identified in the system by
1128 // the combination of its type and name.
1129 return -1;
1130 }
1131
1132 // We have a dynamic sensor.
1133
1134 if (!sHmacGlobalKeyIsValid) {
1135 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1136 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1137 return 0;
1138 }
1139
1140 // We want each app author/publisher to get a different ID, so that the
1141 // same dynamic sensor cannot be tracked across apps by multiple
1142 // authors/publishers. So we use both our UUID and our User ID.
1143 // Note potential confusion:
1144 // UUID => Universally Unique Identifier.
1145 // UID => User Identifier.
1146 // We refrain from using "uid" except as needed by API to try to
1147 // keep this distinction clear.
1148
1149 auto appUserId = IPCThreadState::self()->getCallingUid();
1150 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1151 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1152 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1153
1154 // Now we use our key on our UUID/app combo to get the hash.
1155 uint8_t hash[EVP_MAX_MD_SIZE];
1156 unsigned int hashLen;
1157 if (HMAC(EVP_sha256(),
1158 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1159 uuidAndApp, sizeof(uuidAndApp),
1160 hash, &hashLen) == nullptr) {
1161 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1162 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1163 return 0;
1164 }
1165
1166 int32_t id = 0;
1167 if (hashLen < sizeof(id)) {
1168 // We never expect this case, but out of paranoia, we handle it.
1169 // Our 'id' length is already quite small, we don't want the
1170 // effective length of it to be even smaller.
1171 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1172 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1173 return 0;
1174 }
1175
1176 // This is almost certainly less than all of 'hash', but it's as secure
1177 // as we can be with our current 'id' length.
1178 memcpy(&id, hash, sizeof(id));
1179
1180 // Note at the beginning of the function that we return the values of
1181 // 0 and -1 to represent special cases. As a result, we can't return
1182 // those as dynamic sensor IDs. If we happened to hash to one of those
1183 // values, we change 'id' so we report as a dynamic sensor, and not as
1184 // one of those special cases.
1185 if (id == -1) {
1186 id = -2;
1187 } else if (id == 0) {
1188 id = 1;
1189 }
1190 return id;
1191}
1192
1193void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1194 for (auto &sensor : sensorList) {
1195 int32_t id = getIdFromUuid(sensor.getUuid());
1196 sensor.setId(id);
1197 }
1198}
1199
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001200Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001201 char value[PROPERTY_VALUE_MAX];
1202 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001203 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001204 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001205 Vector<Sensor> accessibleSensorList;
1206 for (size_t i = 0; i < initialSensorList.size(); i++) {
1207 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001208 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001209 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001210 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001211 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001212}
1213
Peng Xu47e96012016-03-28 17:55:56 -07001214Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001215 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001216 mSensors.forEachSensor(
1217 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001218 if (sensor.isDynamicSensor()) {
1219 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1220 accessibleSensorList.add(sensor);
1221 } else {
1222 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1223 sensor.getName().string(),
1224 sensor.getRequiredPermission().string(),
1225 sensor.getRequiredAppOp());
1226 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001227 }
1228 return true;
1229 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001230 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001231 return accessibleSensorList;
1232}
1233
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001234sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001235 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001236 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1237 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001238 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001239 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001240
1241 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001242 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1243 // operating in DI mode.
1244 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001245 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1246 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001247 }
1248
Mathias Agopian5307d172012-09-18 17:02:43 -07001249 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001250 pid_t pid = IPCThreadState::self()->getCallingPid();
1251
1252 String8 connPackageName =
1253 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1254 String16 connOpPackageName =
1255 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001256 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001257 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001258 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001259 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001260 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001261 // Add the associated file descriptor to the Looper for polling whenever there is data to
1262 // be injected.
1263 result->updateLooperRegistration(mLooper);
1264 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001265 return result;
1266}
1267
Aravind Akella841a5922015-06-29 12:37:48 -07001268int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001269 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001270 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001271}
1272
Peng Xue36e3472016-11-03 11:57:10 -07001273sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1274 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1275 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001276 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001277
Michael Groover5e1f60b2018-12-04 22:34:29 -08001278 // No new direct connections are allowed when sensor privacy is enabled
1279 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1280 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1281 return nullptr;
1282 }
1283
Peng Xue36e3472016-11-03 11:57:10 -07001284 struct sensors_direct_mem_t mem = {
1285 .type = type,
1286 .format = format,
1287 .size = size,
1288 .handle = resource,
1289 };
1290 uid_t uid = IPCThreadState::self()->getCallingUid();
1291
1292 if (mem.handle == nullptr) {
1293 ALOGE("Failed to clone resource handle");
1294 return nullptr;
1295 }
1296
1297 // check format
1298 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1299 ALOGE("Direct channel format %d is unsupported!", format);
1300 return nullptr;
1301 }
1302
1303 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001304 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1305 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001306 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001307 return nullptr;
1308 }
1309 }
1310
1311 // check specific to memory type
1312 switch(type) {
1313 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001314 if (resource->numFds < 1) {
1315 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1316 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1317 return nullptr;
1318 }
Peng Xue36e3472016-11-03 11:57:10 -07001319 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001320 if (!ashmem_valid(fd)) {
1321 ALOGE("Supplied Ashmem memory region is invalid");
1322 return nullptr;
1323 }
1324
Peng Xue36e3472016-11-03 11:57:10 -07001325 int size2 = ashmem_get_size_region(fd);
1326 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001327 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001328 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1329 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001330 return nullptr;
1331 }
1332 break;
1333 }
1334 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001335 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001336 break;
1337 default:
1338 ALOGE("Unknown direct connection memory type %d", type);
1339 return nullptr;
1340 }
1341
1342 native_handle_t *clone = native_handle_clone(resource);
1343 if (!clone) {
1344 return nullptr;
1345 }
1346
Brian Duddie967ce172019-06-10 11:08:27 -07001347 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001348 SensorDevice& dev(SensorDevice::getInstance());
1349 int channelHandle = dev.registerDirectChannel(&mem);
1350
1351 if (channelHandle <= 0) {
1352 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1353 } else {
1354 mem.handle = clone;
1355 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1356 }
1357
1358 if (conn == nullptr) {
1359 native_handle_close(clone);
1360 native_handle_delete(clone);
1361 } else {
1362 // add to list of direct connections
1363 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001364 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001365 }
1366 return conn;
1367}
1368
Peng Xudd5c5cb2017-03-16 17:39:43 -07001369int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001370 int32_t handle, int32_t type,
1371 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001372 Mutex::Autolock _l(mLock);
1373
Alexey Polyudov88711e82017-05-23 19:54:04 -07001374 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001375 return PERMISSION_DENIED;
1376 }
1377
1378 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001379 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001380 size_t expectSize = INT32_MAX;
1381 switch (type) {
1382 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1383 isFloat = true;
1384 expectSize = 3;
1385 break;
1386 case AINFO_LOCAL_GRAVITY:
1387 isFloat = true;
1388 expectSize = 1;
1389 break;
1390 case AINFO_DOCK_STATE:
1391 case AINFO_HIGH_PERFORMANCE_MODE:
1392 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1393 isFloat = false;
1394 expectSize = 1;
1395 break;
1396 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001397 // CUSTOM events must only contain float data; it may have variable size
1398 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1399 ints.size() ||
1400 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1401 handle < 0) {
1402 return BAD_VALUE;
1403 }
1404 isFloat = true;
1405 isCustom = true;
1406 expectSize = floats.size();
1407 break;
1408 }
1409
1410 if (!isCustom && handle != -1) {
1411 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001412 }
1413
1414 // three events: first one is begin tag, last one is end tag, the one in the middle
1415 // is the payload.
1416 sensors_event_t event[3];
1417 int64_t timestamp = elapsedRealtimeNano();
1418 for (sensors_event_t* i = event; i < event + 3; i++) {
1419 *i = (sensors_event_t) {
1420 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001421 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001422 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1423 .timestamp = timestamp++,
1424 .additional_info = (additional_info_event_t) {
1425 .serial = 0
1426 }
1427 };
1428 }
1429
1430 event[0].additional_info.type = AINFO_BEGIN;
1431 event[1].additional_info.type = type;
1432 event[2].additional_info.type = AINFO_END;
1433
1434 if (isFloat) {
1435 if (floats.size() != expectSize) {
1436 return BAD_VALUE;
1437 }
1438 for (size_t i = 0; i < expectSize; ++i) {
1439 event[1].additional_info.data_float[i] = floats[i];
1440 }
1441 } else {
1442 if (ints.size() != expectSize) {
1443 return BAD_VALUE;
1444 }
1445 for (size_t i = 0; i < expectSize; ++i) {
1446 event[1].additional_info.data_int32[i] = ints[i];
1447 }
1448 }
1449
1450 SensorDevice& dev(SensorDevice::getInstance());
1451 for (sensors_event_t* i = event; i < event + 3; i++) {
1452 int ret = dev.injectSensorData(i);
1453 if (ret != NO_ERROR) {
1454 return ret;
1455 }
1456 }
1457 return NO_ERROR;
1458}
1459
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001460status_t SensorService::resetToNormalMode() {
1461 Mutex::Autolock _l(mLock);
1462 return resetToNormalModeLocked();
1463}
1464
1465status_t SensorService::resetToNormalModeLocked() {
1466 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001467 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301468 if (err == NO_ERROR) {
1469 mCurrentOperatingMode = NORMAL;
1470 dev.enableAllSensors();
1471 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001472 return err;
1473}
1474
Peng Xu47e96012016-03-28 17:55:56 -07001475void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001476 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001477 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001478 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001479 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001480 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001481 int handle = mActiveSensors.keyAt(i);
1482 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001483 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001484 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1485 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001486 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001487 } else {
1488 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001489 }
Aravind Akella8a969552014-09-28 17:52:41 -07001490 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001491 }
1492 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001493 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001494 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001495 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001496 c, i, handle);
1497
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001498 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001499 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001500 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001501 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001502 delete rec;
1503 size--;
1504 } else {
1505 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001506 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001507 }
Aravind Akella8a969552014-09-28 17:52:41 -07001508 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001509 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001510 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001511 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001512 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001513 }
Peng Xu4f707f82016-09-26 11:28:32 -07001514
Brian Stack793f4642019-04-18 17:21:34 -07001515 {
1516 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1517 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1518 if (iter != sPackageTargetVersion.end()) {
1519 sPackageTargetVersion.erase(iter);
1520 }
1521 }
1522
Peng Xu4f707f82016-09-26 11:28:32 -07001523 SensorDevice& dev(SensorDevice::getInstance());
1524 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001525}
1526
Peng Xue36e3472016-11-03 11:57:10 -07001527void SensorService::cleanupConnection(SensorDirectConnection* c) {
1528 Mutex::Autolock _l(mLock);
1529
1530 SensorDevice& dev(SensorDevice::getInstance());
1531 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001532 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001533}
1534
Peng Xu755c4512016-04-07 23:15:14 -07001535sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001536 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001537}
1538
Mathias Agopianfc328812010-07-14 23:41:37 -07001539status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001540 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001541 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001542 if (mInitCheck != NO_ERROR)
1543 return mInitCheck;
1544
Peng Xu755c4512016-04-07 23:15:14 -07001545 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1546 if (sensor == nullptr ||
1547 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001548 return BAD_VALUE;
1549 }
1550
Brian Duddie967ce172019-06-10 11:08:27 -07001551 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001552 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001553 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001554 return INVALID_OPERATION;
1555 }
1556
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001557 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001558 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001559 rec = new SensorRecord(connection);
1560 mActiveSensors.add(handle, rec);
1561 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001562 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001563 }
Brian Stack26029ee2019-04-22 17:25:49 -07001564
1565 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1566 // the recent event as stale to ensure that the previous event is not sent to a client. This
1567 // ensures on-change events that were generated during a previous sensor activation are not
1568 // erroneously sent to newly connected clients, especially if a second client registers for
1569 // an on-change sensor before the first client receives the updated event. Once an updated
1570 // event is received, the recent events will be marked as current, and any new clients will
1571 // immediately receive the most recent event.
1572 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1573 auto logger = mRecentEvent.find(handle);
1574 if (logger != mRecentEvent.end()) {
1575 logger->second->setLastEventStale();
1576 }
1577 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001578 } else {
1579 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001580 // this sensor is already activated, but we are adding a connection that uses it.
1581 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001582 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001583 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001584 // NOTE: The wake_up flag of this event may get set to
1585 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001586
1587 auto logger = mRecentEvent.find(handle);
1588 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001589 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001590 // Verify that the last sensor event was generated from the current activation
1591 // of the sensor. If not, it is possible for an on-change sensor to receive a
1592 // sensor event that is stale if two clients re-activate the sensor
1593 // simultaneously.
1594 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001595 event.sensor = handle;
1596 if (event.version == sizeof(sensors_event_t)) {
1597 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1598 setWakeLockAcquiredLocked(true);
1599 }
Yi Kong8f313e32018-07-17 14:13:29 -07001600 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001601 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001602 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001603 }
1604 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001605 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001606 }
1607 }
1608 }
1609 }
1610
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -07001611 if (connection->addSensor(handle, samplingPeriodNs, maxBatchReportLatencyNs, reservedFlags)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001612 BatteryService::enableSensor(connection->getUid(), handle);
1613 // the sensor was added (which means it wasn't already there)
1614 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001615 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001616 } else {
1617 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1618 handle, connection.get());
1619 }
1620
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301621 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001622 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301623 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1624 samplingPeriodNs = maxDelayNs;
1625 }
1626
Aravind Akella724d91d2013-06-27 12:04:23 -07001627 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1628 if (samplingPeriodNs < minDelayNs) {
1629 samplingPeriodNs = minDelayNs;
1630 }
1631
Aravind Akella6c2664a2014-08-13 12:24:50 -07001632 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1633 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001634 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1635
Aravind Akella4949c502015-02-11 15:54:35 -08001636 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001637 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001638
Peng Xu20483c42015-10-26 15:14:43 -07001639 // Call flush() before calling activate() on the sensor. Wait for a first
1640 // flush complete event before sending events on this connection. Ignore
1641 // one-shot sensors which don't support flush(). Ignore on-change sensors
1642 // to maintain the on-change logic (any on-change events except the initial
1643 // one should be trigger by a change in value). Also if this sensor isn't
1644 // already active, don't call flush().
1645 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001646 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001647 rec->getNumConnections() > 1) {
1648 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001649 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001650 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001651 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001652 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001653 } else {
1654 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001655 }
1656 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001657
1658 if (err == NO_ERROR) {
1659 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1660 err = sensor->activate(connection.get(), true);
1661 }
1662
Aravind Akella8a969552014-09-28 17:52:41 -07001663 if (err == NO_ERROR) {
1664 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001665
Brian Stack240d1d62019-05-17 09:49:39 -07001666 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1667 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001668 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1669 }
1670
Peng Xu51224682017-03-10 16:57:27 -08001671 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1672 SensorRegistrationInfo(handle, connection->getPackageName(),
1673 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001674 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001675 }
1676
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001677 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001678 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001679 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001680 }
1681 return err;
1682}
1683
Peng Xu47e96012016-03-28 17:55:56 -07001684status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001685 if (mInitCheck != NO_ERROR)
1686 return mInitCheck;
1687
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001688 Mutex::Autolock _l(mLock);
1689 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001690 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001691 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1692 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001693
1694 }
1695 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001696 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1697 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001698 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001699 }
1700 return err;
1701}
1702
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001703status_t SensorService::cleanupWithoutDisable(
1704 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001705 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001706 return cleanupWithoutDisableLocked(connection, handle);
1707}
1708
1709status_t SensorService::cleanupWithoutDisableLocked(
1710 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001711 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001712 if (rec) {
1713 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001714 if (connection->removeSensor(handle)) {
1715 BatteryService::disableSensor(connection->getUid(), handle);
1716 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001717 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001718 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001719 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001720 }
1721 // see if this sensor becomes inactive
1722 if (rec->removeConnection(connection)) {
1723 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001724 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001725 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001726 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001727 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001728 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001729 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001730}
1731
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001732status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001733 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001734 if (mInitCheck != NO_ERROR)
1735 return mInitCheck;
1736
Peng Xu755c4512016-04-07 23:15:14 -07001737 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1738 if (sensor == nullptr ||
1739 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001740 return BAD_VALUE;
1741 }
1742
Mathias Agopian1cd70002010-07-21 15:59:50 -07001743 if (ns < 0)
1744 return BAD_VALUE;
1745
Mathias Agopian62569ec2011-11-07 21:21:47 -08001746 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1747 if (ns < minDelayNs) {
1748 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001749 }
1750
Mathias Agopianf001c922010-11-11 17:58:51 -08001751 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001752}
1753
Svetoslavb412f6e2015-04-29 16:50:41 -07001754status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1755 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001756 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001757 SensorDevice& dev(SensorDevice::getInstance());
1758 const int halVersion = dev.getHalDeviceVersion();
1759 status_t err(NO_ERROR);
1760 Mutex::Autolock _l(mLock);
Arthur Ishiguro6eb75be2020-04-01 11:58:43 -07001761
1762 size_t numSensors = 0;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001763 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07001764 for (int handle : connection->getActiveSensorHandles()) {
Peng Xu755c4512016-04-07 23:15:14 -07001765 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1766 if (sensor == nullptr) {
1767 continue;
1768 }
Arthur Ishiguro6eb75be2020-04-01 11:58:43 -07001769 numSensors++;
1770
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001771 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1772 ALOGE("flush called on a one-shot sensor");
1773 err = INVALID_OPERATION;
1774 continue;
1775 }
Arthur Ishiguro6eb75be2020-04-01 11:58:43 -07001776
Aravind Akella8493b792014-09-08 15:45:47 -07001777 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001778 // For older devices just increment pending flush count which will send a trivial
1779 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001780 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001781 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001782 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1783 err = INVALID_OPERATION;
1784 continue;
1785 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001786 status_t err_flush = sensor->flush(connection.get(), handle);
1787 if (err_flush == NO_ERROR) {
1788 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001789 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001790 }
1791 err = (err_flush != NO_ERROR) ? err_flush : err;
1792 }
Aravind Akella70018042014-04-07 22:52:37 +00001793 }
Arthur Ishiguro6eb75be2020-04-01 11:58:43 -07001794
1795 return (numSensors == 0) ? INVALID_OPERATION : err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001796}
Aravind Akella70018042014-04-07 22:52:37 +00001797
Svetoslavb412f6e2015-04-29 16:50:41 -07001798bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1799 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001800 // Check if a permission is required for this sensor
1801 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001802 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001803 }
1804
Brian Stack793f4642019-04-18 17:21:34 -07001805 const int32_t opCode = sensor.getRequiredAppOp();
1806 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1807 IPCThreadState::self()->getCallingUid(), opPackageName);
Brian Stack6a700f92019-05-08 17:02:53 -07001808 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
Brian Stack793f4642019-04-18 17:21:34 -07001809
Brian Stack793f4642019-04-18 17:21:34 -07001810 bool canAccess = false;
Brian Stack6a700f92019-05-08 17:02:53 -07001811 if (hasPermissionForSensor(sensor)) {
1812 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1813 if (opCode < 0 || appOpAllowed) {
Brian Stack793f4642019-04-18 17:21:34 -07001814 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001815 }
1816 } else if (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1817 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR) {
1818 int targetSdkVersion = getTargetSdkVersion(opPackageName);
1819 // Allow access to the sensor 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, and the user hasn't revoked the app op.
1822 //
1823 // Verifying the app op is required to ensure that the user hasn't revoked the necessary
1824 // permissions to access the Step Detector and Step Counter when the application targets
1825 // pre-Q. Without this check, if the user revokes the pre-Q install-time GMS Core AR
1826 // permission, the app would still be able to receive Step Counter and Step Detector events.
1827 if (appOpAllowed &&
1828 targetSdkVersion > 0 &&
1829 targetSdkVersion <= __ANDROID_API_P__) {
1830 canAccess = true;
Brian Stack793f4642019-04-18 17:21:34 -07001831 }
1832 }
1833
1834 if (canAccess) {
1835 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1836 } else {
1837 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1838 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1839 }
1840
1841 return canAccess;
1842}
1843
1844bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001845 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001846 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001847
1848 // Runtime permissions can't use the cache as they may change.
1849 if (sensor.isRequiredPermissionRuntime()) {
1850 hasPermission = checkPermission(String16(requiredPermission),
1851 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001852 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001853 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1854 }
Brian Stack793f4642019-04-18 17:21:34 -07001855 return hasPermission;
1856}
Svetoslavb412f6e2015-04-29 16:50:41 -07001857
Brian Stack793f4642019-04-18 17:21:34 -07001858int SensorService::getTargetSdkVersion(const String16& opPackageName) {
1859 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1860 int targetSdkVersion = -1;
1861 auto entry = sPackageTargetVersion.find(opPackageName);
1862 if (entry != sPackageTargetVersion.end()) {
1863 targetSdkVersion = entry->second;
1864 } else {
1865 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1866 if (binder != nullptr) {
1867 sp<content::pm::IPackageManagerNative> packageManager =
1868 interface_cast<content::pm::IPackageManagerNative>(binder);
1869 if (packageManager != nullptr) {
1870 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1871 opPackageName, &targetSdkVersion);
1872 if (!status.isOk()) {
1873 targetSdkVersion = -1;
1874 }
1875 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001876 }
Brian Stack793f4642019-04-18 17:21:34 -07001877 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001878 }
Brian Stack793f4642019-04-18 17:21:34 -07001879 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001880}
1881
Aravind Akella9a844cf2014-02-11 18:58:52 -08001882void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001883 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1884 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001885}
1886
Brian Duddie967ce172019-06-10 11:08:27 -07001887void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001888 if (!mWakeLockAcquired) {
1889 return;
1890 }
1891 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001892 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1893 if (connection->needsWakeLock()) {
1894 releaseLock = false;
1895 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001896 }
1897 }
1898 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001899 setWakeLockAcquiredLocked(false);
1900 }
1901}
1902
1903void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1904 Mutex::Autolock _l(mLock);
1905 connection->writeToSocketFromCache();
1906 if (connection->needsWakeLock()) {
1907 setWakeLockAcquiredLocked(true);
1908 }
1909}
1910
Aravind Akella4949c502015-02-11 15:54:35 -08001911bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001912 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001913}
1914
Brian Stack5180e462019-03-08 17:15:19 -08001915bool SensorService::isOperationPermitted(const String16& opPackageName) {
Peng Xue36e3472016-11-03 11:57:10 -07001916 Mutex::Autolock _l(mLock);
Brian Stack5180e462019-03-08 17:15:19 -08001917 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001918 String8 package(opPackageName);
Brian Stack5180e462019-03-08 17:15:19 -08001919 return isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001920 }
Brian Stack5180e462019-03-08 17:15:19 -08001921 return true;
Peng Xue36e3472016-11-03 11:57:10 -07001922}
1923
Svet Ganove752a5c2018-01-15 17:14:20 -08001924void SensorService::UidPolicy::registerSelf() {
1925 ActivityManager am;
1926 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1927 | ActivityManager::UID_OBSERVER_IDLE
1928 | ActivityManager::UID_OBSERVER_ACTIVE,
1929 ActivityManager::PROCESS_STATE_UNKNOWN,
1930 String16("android"));
1931}
1932
1933void SensorService::UidPolicy::unregisterSelf() {
1934 ActivityManager am;
1935 am.unregisterUidObserver(this);
1936}
1937
1938void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1939 onUidIdle(uid, disabled);
1940}
1941
1942void SensorService::UidPolicy::onUidActive(uid_t uid) {
1943 {
1944 Mutex::Autolock _l(mUidLock);
1945 mActiveUids.insert(uid);
1946 }
1947 sp<SensorService> service = mService.promote();
1948 if (service != nullptr) {
1949 service->setSensorAccess(uid, true);
1950 }
1951}
1952
1953void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1954 bool deleted = false;
1955 {
1956 Mutex::Autolock _l(mUidLock);
1957 if (mActiveUids.erase(uid) > 0) {
1958 deleted = true;
1959 }
1960 }
1961 if (deleted) {
1962 sp<SensorService> service = mService.promote();
1963 if (service != nullptr) {
1964 service->setSensorAccess(uid, false);
1965 }
1966 }
1967}
1968
1969void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1970 updateOverrideUid(uid, active, true);
1971}
1972
1973void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1974 updateOverrideUid(uid, false, false);
1975}
1976
1977void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1978 bool wasActive = false;
1979 bool isActive = false;
1980 {
1981 Mutex::Autolock _l(mUidLock);
1982 wasActive = isUidActiveLocked(uid);
1983 mOverrideUids.erase(uid);
1984 if (insert) {
1985 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1986 }
1987 isActive = isUidActiveLocked(uid);
1988 }
1989 if (wasActive != isActive) {
1990 sp<SensorService> service = mService.promote();
1991 if (service != nullptr) {
1992 service->setSensorAccess(uid, isActive);
1993 }
1994 }
1995}
1996
1997bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1998 // Non-app UIDs are considered always active
1999 if (uid < FIRST_APPLICATION_UID) {
2000 return true;
2001 }
2002 Mutex::Autolock _l(mUidLock);
2003 return isUidActiveLocked(uid);
2004}
2005
2006bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2007 // Non-app UIDs are considered always active
2008 if (uid < FIRST_APPLICATION_UID) {
2009 return true;
2010 }
2011 auto it = mOverrideUids.find(uid);
2012 if (it != mOverrideUids.end()) {
2013 return it->second;
2014 }
2015 return mActiveUids.find(uid) != mActiveUids.end();
2016}
2017
Michael Groover5e1f60b2018-12-04 22:34:29 -08002018void SensorService::SensorPrivacyPolicy::registerSelf() {
2019 SensorPrivacyManager spm;
2020 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2021 spm.addSensorPrivacyListener(this);
2022}
2023
2024void SensorService::SensorPrivacyPolicy::unregisterSelf() {
2025 SensorPrivacyManager spm;
2026 spm.removeSensorPrivacyListener(this);
2027}
2028
2029bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2030 return mSensorPrivacyEnabled;
2031}
2032
2033binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2034 mSensorPrivacyEnabled = enabled;
2035 sp<SensorService> service = mService.promote();
2036 if (service != nullptr) {
2037 if (enabled) {
2038 service->disableAllSensors();
2039 } else {
2040 service->enableAllSensors();
2041 }
2042 }
2043 return binder::Status::ok();
2044}
Brian Duddie967ce172019-06-10 11:08:27 -07002045
2046SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2047 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2048 : mConnectionHolder(holder), mAutolock(mutex) {}
2049
2050template<typename ConnectionType>
2051const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2052 const SortedVector<wp<ConnectionType>>& connectionList,
2053 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2054 referenceHolder->emplace_back();
2055 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2056 for (const wp<ConnectionType>& weakConnection : connectionList){
2057 sp<ConnectionType> connection = weakConnection.promote();
2058 if (connection != nullptr) {
2059 connections.push_back(std::move(connection));
2060 }
2061 }
2062 return connections;
2063}
2064
2065const std::vector<sp<SensorService::SensorEventConnection>>&
2066 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2067 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2068 &mReferencedActiveConnections);
2069}
2070
2071const std::vector<sp<SensorService::SensorDirectConnection>>&
2072 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2073 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2074 &mReferencedDirectConnections);
2075}
2076
2077void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2078 const sp<SensorService::SensorEventConnection>& connection) {
2079 if (mActiveConnections.indexOf(connection) < 0) {
2080 mActiveConnections.add(connection);
2081 }
2082}
2083
2084void SensorService::SensorConnectionHolder::removeEventConnection(
2085 const wp<SensorService::SensorEventConnection>& connection) {
2086 mActiveConnections.remove(connection);
2087}
2088
2089void SensorService::SensorConnectionHolder::addDirectConnection(
2090 const sp<SensorService::SensorDirectConnection>& connection) {
2091 mDirectConnections.add(connection);
2092}
2093
2094void SensorService::SensorConnectionHolder::removeDirectConnection(
2095 const wp<SensorService::SensorDirectConnection>& connection) {
2096 mDirectConnections.remove(connection);
2097}
2098
2099SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2100 return ConnectionSafeAutolock(*this, mutex);
2101}
2102
2103} // namespace android