blob: c11b88eac204aec8c5b9f3c97e8ac8e2dbfdf193 [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>
Svet Ganove752a5c2018-01-15 17:14:20 -080017#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070018#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070019#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070020#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080021#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070022#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080023#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070024#include <cutils/properties.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070025#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070026#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080027#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070028#include <openssl/digest.h>
29#include <openssl/hmac.h>
30#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070031#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080032#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070033#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070034
Mathias Agopian787ac1b2012-09-18 18:49:18 -070035#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070036#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080037#include "GravitySensor.h"
38#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070039#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080040#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070041#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070042#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080043
Mathias Agopian984826c2011-05-17 22:54:42 -070044#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070045#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080046#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080047#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048#include "SensorRecord.h"
49#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080050
Brian Stack51498e62018-10-03 10:52:21 -070051#include <ctime>
Peng Xueb4d6282015-12-10 18:02:41 -080052#include <inttypes.h>
53#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070054#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080055#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080056#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070057#include <sys/stat.h>
58#include <sys/types.h>
59#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070060
Svet Ganove752a5c2018-01-15 17:14:20 -080061#include <private/android_filesystem_config.h>
62
Mathias Agopianfc328812010-07-14 23:41:37 -070063namespace android {
64// ---------------------------------------------------------------------------
65
Mathias Agopian33015422011-05-27 18:18:13 -070066/*
67 * Notes:
68 *
69 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070070 * - run mag sensor from time to time to force calibration
71 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
72 *
73 */
74
Aravind Akella8ef3c892015-07-10 11:24:28 -070075const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070076uint8_t SensorService::sHmacGlobalKey[128] = {};
77bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070078std::map<String16, int> SensorService::sPackageTargetVersion;
79Mutex SensorService::sPackageTargetVersionLock;
80AppOpsManager SensorService::sAppOpsManager;
Greg Kaiser53ca2e02016-06-21 16:11:14 -070081
82#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
83#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070084#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070085
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070086// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070087static const String16 sDumpPermission("android.permission.DUMP");
88static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080089static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070090
Mathias Agopianfc328812010-07-14 23:41:37 -070091SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070092 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070093 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +090094 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -080095 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -070096}
97
Greg Kaiser53ca2e02016-06-21 16:11:14 -070098bool SensorService::initializeHmacKey() {
99 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
100 if (fd != -1) {
101 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
102 close(fd);
103 if (result == sizeof(sHmacGlobalKey)) {
104 return true;
105 }
106 ALOGW("Unable to read HMAC key; generating new one.");
107 }
108
109 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
110 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
111 return false;
112 }
113
114 // We need to make sure this is only readable to us.
115 bool wroteKey = false;
116 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
117 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
118 S_IRUSR|S_IWUSR);
119 if (fd != -1) {
120 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
121 close(fd);
122 wroteKey = (result == sizeof(sHmacGlobalKey));
123 }
124 if (wroteKey) {
125 ALOGI("Generated new HMAC key.");
126 } else {
127 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
128 "after reboot.");
129 }
130 // Even if we failed to write the key we return true, because we did
131 // initialize the HMAC key.
132 return true;
133}
134
Peng Xu98d30f62016-08-01 18:12:11 -0700135// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
136void SensorService::enableSchedFifoMode() {
137 struct sched_param param = {0};
138 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
139 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
140 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
141 }
142}
143
Peng Xu47e96012016-03-28 17:55:56 -0700144void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000145 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800146 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700147
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700148 sHmacGlobalKeyIsValid = initializeHmacKey();
149
Mathias Agopianf001c922010-11-11 17:58:51 -0800150 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800151 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700152 ssize_t count = dev.getSensorList(&list);
153 if (count > 0) {
154 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700155 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700156 uint32_t virtualSensorsNeeds =
157 (1<<SENSOR_TYPE_GRAVITY) |
158 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700159 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
160 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
161 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700162
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700163 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700164 bool useThisSensor=true;
165
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700166 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700167 case SENSOR_TYPE_ACCELEROMETER:
168 hasAccel = true;
169 break;
170 case SENSOR_TYPE_MAGNETIC_FIELD:
171 hasMag = true;
172 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700173 case SENSOR_TYPE_ORIENTATION:
174 orientationIndex = i;
175 break;
176 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700177 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700178 hasGyro = true;
179 break;
180 case SENSOR_TYPE_GRAVITY:
181 case SENSOR_TYPE_LINEAR_ACCELERATION:
182 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700183 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
184 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
185 if (IGNORE_HARDWARE_FUSION) {
186 useThisSensor = false;
187 } else {
188 virtualSensorsNeeds &= ~(1<<list[i].type);
189 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700190 break;
191 }
Peng Xuf66684a2015-07-23 11:41:53 -0700192 if (useThisSensor) {
193 registerSensor( new HardwareSensor(list[i]) );
194 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700195 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700196
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700197 // it's safe to instantiate the SensorFusion object here
198 // (it wants to be instantiated after h/w sensors have been
199 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700200 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700201
Aravind Akellaf5047892015-07-20 17:29:33 -0700202 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700203 // Add Android virtual sensors if they're not already
204 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700205 bool needRotationVector =
206 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700207
Peng Xu0cc8f802016-04-05 23:46:03 -0700208 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
209 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700210
Peng Xu0cc8f802016-04-05 23:46:03 -0700211 bool needLinearAcceleration =
212 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700213
Peng Xu0cc8f802016-04-05 23:46:03 -0700214 registerSensor(new LinearAccelerationSensor(list, count),
215 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700216
Peng Xu0cc8f802016-04-05 23:46:03 -0700217 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700218 registerSensor( new CorrectedGyroSensor(list, count), true, true);
219 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700220 }
221
Peng Xuf66684a2015-07-23 11:41:53 -0700222 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700223 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
224 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700225
Peng Xu0cc8f802016-04-05 23:46:03 -0700226 bool needGameRotationVector =
227 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
228 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700229 }
230
231 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700232 bool needGeoMagRotationVector =
233 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
234 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700235 }
236
Aravind Akella5466c3d2014-08-22 16:11:10 -0700237 // Check if the device really supports batching by looking at the FIFO event
238 // counts for each sensor.
239 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700240 mSensors.forEachSensor(
241 [&batchingSupported] (const Sensor& s) -> bool {
242 if (s.getFifoMaxEventCount() > 0) {
243 batchingSupported = true;
244 }
245 return !batchingSupported;
246 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700247
248 if (batchingSupported) {
249 // Increase socket buffer size to a max of 100 KB for batching capabilities.
250 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
251 } else {
252 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
253 }
254
255 // Compare the socketBufferSize value against the system limits and limit
256 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700257 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
258 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700259 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700260 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700261 size_t maxSystemSocketBufferSize;
262 sscanf(line, "%zu", &maxSystemSocketBufferSize);
263 if (mSocketBufferSize > maxSystemSocketBufferSize) {
264 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700265 }
266 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700267 if (fp) {
268 fclose(fp);
269 }
270
Aravind Akella9a844cf2014-02-11 18:58:52 -0800271 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700272 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700273 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
274 mSensorEventBuffer = new sensors_event_t[minBufferSize];
275 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700276 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700277 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700278
Aravind Akella18d6d512015-06-18 14:18:28 -0700279 mNextSensorRegIndex = 0;
280 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
281 mLastNSensorRegistrations.push();
282 }
283
284 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700285 mAckReceiver = new SensorEventAckReceiver(this);
286 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700287 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700288
289 // priority can only be changed after run
290 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800291
292 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800293 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800294
295 // Start watching sensor privacy changes
296 mSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800297 }
298 }
299}
300
301void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
302 SortedVector< sp<SensorEventConnection> > activeConnections;
303 populateActiveConnections(&activeConnections);
304 {
305 Mutex::Autolock _l(mLock);
306 for (size_t i = 0 ; i < activeConnections.size(); i++) {
Yi Kong8f313e32018-07-17 14:13:29 -0700307 if (activeConnections[i] != nullptr && activeConnections[i]->getUid() == uid) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800308 activeConnections[i]->setSensorAccess(hasAccess);
309 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700310 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700311 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700312}
313
Peng Xu0cc8f802016-04-05 23:46:03 -0700314const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
315 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800316 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700317 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700318 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700319 return s->getSensor();
320 } else {
321 return mSensors.getNonSensor();
322 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800323}
324
Peng Xu6a2d3a02015-12-21 12:00:23 -0800325const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700326 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800327}
328
Peng Xu6a2d3a02015-12-21 12:00:23 -0800329bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700330 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800331
332 const auto i = mRecentEvent.find(handle);
333 if (i != mRecentEvent.end()) {
334 delete i->second;
335 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800336 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700337 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800338}
339
Peng Xu0cc8f802016-04-05 23:46:03 -0700340const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
341 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700342}
343
Peng Xu47e96012016-03-28 17:55:56 -0700344SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800345 for (auto && entry : mRecentEvent) {
346 delete entry.second;
347 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800348 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800349 mSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700350}
351
352status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700353 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700354 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800355 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700356 IPCThreadState::self()->getCallingPid(),
357 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700358 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700359 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700360 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800361 return INVALID_OPERATION;
362 }
363 Mutex::Autolock _l(mLock);
364 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700365 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700366 // If already in restricted mode. Ignore.
367 if (mCurrentOperatingMode == RESTRICTED) {
368 return status_t(NO_ERROR);
369 }
370 // If in any mode other than normal, ignore.
371 if (mCurrentOperatingMode != NORMAL) {
372 return INVALID_OPERATION;
373 }
Peng Xue36e3472016-11-03 11:57:10 -0700374
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700375 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800376 // temporarily stop all sensor direct report and disable sensors
377 disableAllSensorsLocked();
Aravind Akella841a5922015-06-29 12:37:48 -0700378 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700379 return status_t(NO_ERROR);
380 } else if (args.size() == 1 && args[0] == String16("enable")) {
381 // If currently in restricted mode, reset back to NORMAL mode else ignore.
382 if (mCurrentOperatingMode == RESTRICTED) {
383 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800384 // enable sensors and recover all sensor direct report
385 enableAllSensorsLocked();
Aravind Akella444f2672015-05-07 12:40:52 -0700386 }
Aravind Akella841a5922015-06-29 12:37:48 -0700387 if (mCurrentOperatingMode == DATA_INJECTION) {
388 resetToNormalModeLocked();
389 }
390 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700391 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700392 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
393 if (mCurrentOperatingMode == NORMAL) {
394 dev.disableAllSensors();
395 status_t err = dev.setMode(DATA_INJECTION);
396 if (err == NO_ERROR) {
397 mCurrentOperatingMode = DATA_INJECTION;
398 } else {
399 // Re-enable sensors.
400 dev.enableAllSensors();
401 }
402 mWhiteListedPackage.setTo(String8(args[1]));
403 return NO_ERROR;
404 } else if (mCurrentOperatingMode == DATA_INJECTION) {
405 // Already in DATA_INJECTION mode. Treat this as a no_op.
406 return NO_ERROR;
407 } else {
408 // Transition to data injection mode supported only from NORMAL mode.
409 return INVALID_OPERATION;
410 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700411 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700412 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700413 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700414 } else {
415 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700416 //
Brian Stack51498e62018-10-03 10:52:21 -0700417 timespec curTime;
418 clock_gettime(CLOCK_REALTIME, &curTime);
419 struct tm* timeinfo = localtime(&(curTime.tv_sec));
420 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
421 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800422 result.append("Sensor Device:\n");
423 result.append(SensorDevice::getInstance().dump().c_str());
424
425 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700426 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700427
Peng Xu6a2d3a02015-12-21 12:00:23 -0800428 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700429 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700430
Peng Xu0cc8f802016-04-05 23:46:03 -0700431 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800432 for (auto&& i : mRecentEvent) {
433 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700434 if (!i.second->isEmpty()) {
435 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
436 i.second->setFormat("normal");
437 } else {
438 i.second->setFormat("mask_data");
439 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800440 // if there is events and sensor does not need special permission.
441 result.appendFormat("%s: ", s->getSensor().getName().string());
442 result.append(i.second->dump().c_str());
443 }
444 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700445
Aravind Akella444f2672015-05-07 12:40:52 -0700446 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700447 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700448 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
449 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700450 if (dev.isSensorActive(handle)) {
451 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
452 getSensorName(handle).string(),
453 handle,
454 mActiveSensors.valueAt(i)->getNumConnections());
455 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700456 }
457
Andreas Gamped4036b62015-07-28 13:49:04 -0700458 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700459 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700460 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
461 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700462 result.appendFormat("Mode :");
463 switch(mCurrentOperatingMode) {
464 case NORMAL:
465 result.appendFormat(" NORMAL\n");
466 break;
467 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700468 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700469 break;
470 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700471 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700472 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800473 result.appendFormat("Sensor Privacy: %s\n",
474 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700475
Peng Xue36e3472016-11-03 11:57:10 -0700476 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella444f2672015-05-07 12:40:52 -0700477 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
478 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -0700479 if (connection != nullptr) {
Aravind Akella444f2672015-05-07 12:40:52 -0700480 result.appendFormat("Connection Number: %zu \n", i);
481 connection->dump(result);
482 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700483 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700484
Peng Xue36e3472016-11-03 11:57:10 -0700485 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
486 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
487 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
488 if (connection != nullptr) {
489 result.appendFormat("Direct connection %zu:\n", i);
490 connection->dump(result);
491 }
492 }
493
Aravind Akella18d6d512015-06-18 14:18:28 -0700494 result.appendFormat("Previous Registrations:\n");
495 // Log in the reverse chronological order.
496 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
497 SENSOR_REGISTRATIONS_BUF_SIZE;
498 const int startIndex = currentIndex;
499 do {
500 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
501 if (SensorRegistrationInfo::isSentinel(reg_info)) {
502 // Ignore sentinel, proceed to next item.
503 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
504 SENSOR_REGISTRATIONS_BUF_SIZE;
505 continue;
506 }
Peng Xu51224682017-03-10 16:57:27 -0800507 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700508 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
509 SENSOR_REGISTRATIONS_BUF_SIZE;
510 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700511 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700512 }
513 write(fd, result.string(), result.size());
514 return NO_ERROR;
515}
516
Michael Groover5e1f60b2018-12-04 22:34:29 -0800517void SensorService::disableAllSensors() {
518 Mutex::Autolock _l(mLock);
519 disableAllSensorsLocked();
520}
521
522void SensorService::disableAllSensorsLocked() {
523 SensorDevice& dev(SensorDevice::getInstance());
524 for (auto &i : mDirectConnections) {
525 sp<SensorDirectConnection> connection(i.promote());
526 if (connection != nullptr) {
527 connection->stopAll(true /* backupRecord */);
528 }
529 }
530 dev.disableAllSensors();
531 // Clear all pending flush connections for all active sensors. If one of the active
532 // connections has called flush() and the underlying sensor has been disabled before a
533 // flush complete event is returned, we need to remove the connection from this queue.
534 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
535 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
536 }
537}
538
539void SensorService::enableAllSensors() {
540 Mutex::Autolock _l(mLock);
541 enableAllSensorsLocked();
542}
543
544void SensorService::enableAllSensorsLocked() {
545 // sensors should only be enabled if the operating state is not restricted and sensor
546 // privacy is not enabled.
547 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
548 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
549 mCurrentOperatingMode,
550 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
551 return;
552 }
553 SensorDevice& dev(SensorDevice::getInstance());
554 dev.enableAllSensors();
555 for (auto &i : mDirectConnections) {
556 sp<SensorDirectConnection> connection(i.promote());
557 if (connection != nullptr) {
558 connection->recoverAll();
559 }
560 }
561}
562
Svet Ganove752a5c2018-01-15 17:14:20 -0800563// NOTE: This is a remote API - make sure all args are validated
564status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
565 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
566 return PERMISSION_DENIED;
567 }
568 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
569 return BAD_VALUE;
570 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700571 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800572 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700573 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800574 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700575 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800576 return handleGetUidState(args, out, err);
577 } else if (args.size() == 1 && args[0] == String16("help")) {
578 printHelp(out);
579 return NO_ERROR;
580 }
581 printHelp(err);
582 return BAD_VALUE;
583}
584
Tanmay Patild33a1822019-04-11 18:38:55 -0700585static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800586 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700587 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800588 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700589 ALOGE("Unknown package: '%s'", String8(packageName).string());
590 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800591 return BAD_VALUE;
592 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700593
594 if (userId < 0) {
595 ALOGE("Invalid user: %d", userId);
596 dprintf(err, "Invalid user: %d\n", userId);
597 return BAD_VALUE;
598 }
599
600 uid = multiuser_get_uid(userId, uid);
601 return NO_ERROR;
602}
603
604status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
605 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
606 if (!(args.size() == 3 || args.size() == 5)) {
607 printHelp(err);
608 return BAD_VALUE;
609 }
610
Svet Ganove752a5c2018-01-15 17:14:20 -0800611 bool active = false;
612 if (args[2] == String16("active")) {
613 active = true;
614 } else if ((args[2] != String16("idle"))) {
615 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
616 return BAD_VALUE;
617 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700618
619 int userId = 0;
620 if (args.size() == 5 && args[3] == String16("--user")) {
621 userId = atoi(String8(args[4]));
622 }
623
624 uid_t uid;
625 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
626 return BAD_VALUE;
627 }
628
Svet Ganove752a5c2018-01-15 17:14:20 -0800629 mUidPolicy->addOverrideUid(uid, active);
630 return NO_ERROR;
631}
632
633status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700634 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
635 if (!(args.size() == 2 || args.size() == 4)) {
636 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800637 return BAD_VALUE;
638 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700639
640 int userId = 0;
641 if (args.size() == 4 && args[2] == String16("--user")) {
642 userId = atoi(String8(args[3]));
643 }
644
645 uid_t uid;
646 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
647 return BAD_VALUE;
648 }
649
Svet Ganove752a5c2018-01-15 17:14:20 -0800650 mUidPolicy->removeOverrideUid(uid);
651 return NO_ERROR;
652}
653
654status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700655 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
656 if (!(args.size() == 2 || args.size() == 4)) {
657 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800658 return BAD_VALUE;
659 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700660
661 int userId = 0;
662 if (args.size() == 4 && args[2] == String16("--user")) {
663 userId = atoi(String8(args[3]));
664 }
665
666 uid_t uid;
667 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
668 return BAD_VALUE;
669 }
670
Svet Ganove752a5c2018-01-15 17:14:20 -0800671 if (mUidPolicy->isUidActive(uid)) {
672 return dprintf(out, "active\n");
673 } else {
674 return dprintf(out, "idle\n");
675 }
676}
677
678status_t SensorService::printHelp(int out) {
679 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700680 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
681 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
682 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800683 " help print this message\n");
684}
685
Peng Xu0cc8f802016-04-05 23:46:03 -0700686//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800687void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700688 sensors_event_t const* buffer, const int count) {
689 for (int i=0 ; i<count ; i++) {
690 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700691 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
692 handle = buffer[i].meta_data.sensor;
693 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700694 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700695 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700696 // If this buffer has an event from a one_shot sensor and this connection is registered
697 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700698 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700699 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
700 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800701 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700702 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700703
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700704 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700705 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700706}
707
Peng Xu47e96012016-03-28 17:55:56 -0700708bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000709 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700710
Peng Xueb4d6282015-12-10 18:02:41 -0800711 // each virtual sensor could generate an event per "real" event, that's why we need to size
712 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
713 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700714 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700715 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700716 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700717
Mathias Agopianf001c922010-11-11 17:58:51 -0800718 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700719
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700720 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700721 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700722 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
723 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700724 if(count == DEAD_OBJECT && device.isReconnecting()) {
725 device.reconnect();
726 continue;
727 } else {
728 ALOGE("sensor poll failed (%s)", strerror(-count));
729 break;
730 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700731 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700732
733 // Reset sensors_event_t.flags to zero for all events in the buffer.
734 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700735 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700736 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700737
Peng Xueb4d6282015-12-10 18:02:41 -0800738 // Make a copy of the connection vector as some connections may be removed during the course
739 // of this loop (especially when one-shot sensor events are present in the sensor_event
740 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
741 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
742 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
743 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700744 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700745 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800746
Aravind Akella9a844cf2014-02-11 18:58:52 -0800747 Mutex::Autolock _l(mLock);
748 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
749 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
750 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
751 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
752 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700753 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700754 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700755 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700756 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700757 }
758 }
759
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700760 if (wakeEvents > 0) {
761 if (!mWakeLockAcquired) {
762 setWakeLockAcquiredLocked(true);
763 }
764 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800765 }
Aravind Akella8493b792014-09-08 15:45:47 -0700766 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800767
Mathias Agopianf001c922010-11-11 17:58:51 -0800768 // handle virtual sensors
769 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700770 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700771 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800772 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700773 SensorFusion& fusion(SensorFusion::getInstance());
774 if (fusion.isEnabled()) {
775 for (size_t i=0 ; i<size_t(count) ; i++) {
776 fusion.process(event[i]);
777 }
778 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700779 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700780 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700781 if (count + k >= minBufferSize) {
782 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700783 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700784 count, k, minBufferSize);
785 break;
786 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800787 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700788 sp<SensorInterface> si = mSensors.getInterface(handle);
789 if (si == nullptr) {
790 ALOGE("handle %d is not an valid virtual sensor", handle);
791 continue;
792 }
793
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700794 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700795 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800796 k++;
797 }
798 }
799 }
800 if (k) {
801 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700802 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800803 count += k;
804 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700805 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700806 }
807 }
808 }
809
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700810 // handle backward compatibility for RotationVector sensor
811 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
812 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700813 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700814 // All the 4 components of the quaternion should be available
815 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700816 mSensorEventBuffer[i].data[4] = -1;
817 }
818 }
819 }
820
Aravind Akella8493b792014-09-08 15:45:47 -0700821 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700822 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
823 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
824 // SensorEventConnection mapped to the corresponding flush_complete_event in
825 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700826 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700827 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
828 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
829 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700830 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700831 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
832 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700833 }
834 }
Peng Xu2576cb62016-01-20 00:22:09 -0800835
836 // handle dynamic sensor meta events, process registration and unregistration of dynamic
837 // sensor based on content of event.
838 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
839 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
840 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
841 const sensor_t& dynamicSensor =
842 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
843 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
844 handle, dynamicSensor.type, dynamicSensor.name);
845
Peng Xu0cc8f802016-04-05 23:46:03 -0700846 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800847 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700848 sensor_t s = dynamicSensor;
849 // make sure the dynamic sensor flag is set
850 s.flags |= DYNAMIC_SENSOR_MASK;
851 // force the handle to be consistent
852 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800853
854 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800855
Peng Xu0cc8f802016-04-05 23:46:03 -0700856 // This will release hold on dynamic sensor meta, so it should be called
857 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700858 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800859 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700860 } else {
861 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
862 }
Peng Xu2576cb62016-01-20 00:22:09 -0800863 } else {
864 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
865 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
866
867 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800868 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800869 ALOGE("Dynamic sensor release error.");
870 }
871
872 size_t numConnections = activeConnections.size();
873 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700874 if (activeConnections[i] != nullptr) {
Peng Xu2576cb62016-01-20 00:22:09 -0800875 activeConnections[i]->removeSensor(handle);
876 }
877 }
878 }
879 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700880 }
881
Aravind Akella9a844cf2014-02-11 18:58:52 -0800882 // Send our events to clients. Check the state of wake lock for each client and release the
883 // lock if none of the clients need it.
884 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700885 size_t numConnections = activeConnections.size();
886 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700887 if (activeConnections[i] != nullptr) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700888 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700889 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700890 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700891 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
892 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700893 if (activeConnections[i]->hasOneShotSensors()) {
894 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
895 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700896 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800897 }
898 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700899
Aravind Akella9a844cf2014-02-11 18:58:52 -0800900 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700901 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800902 }
Aravind Akella8493b792014-09-08 15:45:47 -0700903 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700904
Steve Block3c20fbe2012-01-05 23:22:43 +0000905 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800906 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700907 return false;
908}
909
Aravind Akella56ae4262014-07-10 16:01:10 -0700910sp<Looper> SensorService::getLooper() const {
911 return mLooper;
912}
913
Aravind Akellab4373ac2014-10-29 17:55:20 -0700914void SensorService::resetAllWakeLockRefCounts() {
915 SortedVector< sp<SensorEventConnection> > activeConnections;
916 populateActiveConnections(&activeConnections);
917 {
918 Mutex::Autolock _l(mLock);
919 for (size_t i=0 ; i < activeConnections.size(); ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700920 if (activeConnections[i] != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700921 activeConnections[i]->resetWakeLockRefCount();
922 }
923 }
924 setWakeLockAcquiredLocked(false);
925 }
926}
927
928void SensorService::setWakeLockAcquiredLocked(bool acquire) {
929 if (acquire) {
930 if (!mWakeLockAcquired) {
931 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
932 mWakeLockAcquired = true;
933 }
934 mLooper->wake();
935 } else {
936 if (mWakeLockAcquired) {
937 release_wake_lock(WAKE_LOCK_NAME);
938 mWakeLockAcquired = false;
939 }
940 }
941}
942
Aravind Akellab4373ac2014-10-29 17:55:20 -0700943bool SensorService::isWakeLockAcquired() {
944 Mutex::Autolock _l(mLock);
945 return mWakeLockAcquired;
946}
947
Aravind Akella56ae4262014-07-10 16:01:10 -0700948bool SensorService::SensorEventAckReceiver::threadLoop() {
949 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700950 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700951 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700952 bool wakeLockAcquired = mService->isWakeLockAcquired();
953 int timeout = -1;
954 if (wakeLockAcquired) timeout = 5000;
955 int ret = looper->pollOnce(timeout);
956 if (ret == ALOOPER_POLL_TIMEOUT) {
957 mService->resetAllWakeLockRefCounts();
958 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700959 } while(!Thread::exitPending());
960 return false;
961}
962
Aravind Akella9a844cf2014-02-11 18:58:52 -0800963void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800964 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800965 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800966 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
967 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800968 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800969 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800970 }
Peng Xu2576cb62016-01-20 00:22:09 -0800971
Peng Xu6a2d3a02015-12-21 12:00:23 -0800972 auto logger = mRecentEvent.find(buffer[i].sensor);
973 if (logger != mRecentEvent.end()) {
974 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800975 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800976 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800977}
978
Peng Xu47e96012016-03-28 17:55:56 -0700979void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800980 struct compar {
981 static int cmp(void const* lhs, void const* rhs) {
982 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
983 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700984 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800985 }
986 };
987 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
988}
989
Mathias Agopian5d270722010-07-19 15:20:39 -0700990String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700991 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700992}
993
Aravind Akellab4099e72013-10-15 15:43:10 -0700994bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700995 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
996 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700997}
998
Aravind Akella9a844cf2014-02-11 18:58:52 -0800999bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001000 int handle = event.sensor;
1001 if (event.type == SENSOR_TYPE_META_DATA) {
1002 handle = event.meta_data.sensor;
1003 }
Peng Xu755c4512016-04-07 23:15:14 -07001004 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1005 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001006}
1007
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001008int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1009 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1010 // UUID is not supported for this device.
1011 return 0;
1012 }
1013 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1014 // This sensor can be uniquely identified in the system by
1015 // the combination of its type and name.
1016 return -1;
1017 }
1018
1019 // We have a dynamic sensor.
1020
1021 if (!sHmacGlobalKeyIsValid) {
1022 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1023 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1024 return 0;
1025 }
1026
1027 // We want each app author/publisher to get a different ID, so that the
1028 // same dynamic sensor cannot be tracked across apps by multiple
1029 // authors/publishers. So we use both our UUID and our User ID.
1030 // Note potential confusion:
1031 // UUID => Universally Unique Identifier.
1032 // UID => User Identifier.
1033 // We refrain from using "uid" except as needed by API to try to
1034 // keep this distinction clear.
1035
1036 auto appUserId = IPCThreadState::self()->getCallingUid();
1037 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1038 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1039 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1040
1041 // Now we use our key on our UUID/app combo to get the hash.
1042 uint8_t hash[EVP_MAX_MD_SIZE];
1043 unsigned int hashLen;
1044 if (HMAC(EVP_sha256(),
1045 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1046 uuidAndApp, sizeof(uuidAndApp),
1047 hash, &hashLen) == nullptr) {
1048 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1049 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1050 return 0;
1051 }
1052
1053 int32_t id = 0;
1054 if (hashLen < sizeof(id)) {
1055 // We never expect this case, but out of paranoia, we handle it.
1056 // Our 'id' length is already quite small, we don't want the
1057 // effective length of it to be even smaller.
1058 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1059 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1060 return 0;
1061 }
1062
1063 // This is almost certainly less than all of 'hash', but it's as secure
1064 // as we can be with our current 'id' length.
1065 memcpy(&id, hash, sizeof(id));
1066
1067 // Note at the beginning of the function that we return the values of
1068 // 0 and -1 to represent special cases. As a result, we can't return
1069 // those as dynamic sensor IDs. If we happened to hash to one of those
1070 // values, we change 'id' so we report as a dynamic sensor, and not as
1071 // one of those special cases.
1072 if (id == -1) {
1073 id = -2;
1074 } else if (id == 0) {
1075 id = 1;
1076 }
1077 return id;
1078}
1079
1080void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1081 for (auto &sensor : sensorList) {
1082 int32_t id = getIdFromUuid(sensor.getUuid());
1083 sensor.setId(id);
1084 }
1085}
1086
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001087Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001088 char value[PROPERTY_VALUE_MAX];
1089 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001090 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001091 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001092 Vector<Sensor> accessibleSensorList;
1093 for (size_t i = 0; i < initialSensorList.size(); i++) {
1094 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001095 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001096 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001097 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001098 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001099}
1100
Peng Xu47e96012016-03-28 17:55:56 -07001101Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001102 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001103 mSensors.forEachSensor(
1104 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001105 if (sensor.isDynamicSensor()) {
1106 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1107 accessibleSensorList.add(sensor);
1108 } else {
1109 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1110 sensor.getName().string(),
1111 sensor.getRequiredPermission().string(),
1112 sensor.getRequiredAppOp());
1113 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001114 }
1115 return true;
1116 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001117 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001118 return accessibleSensorList;
1119}
1120
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001121sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001122 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001123 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1124 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001125 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001126 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001127
1128 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001129 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1130 // operating in DI mode.
1131 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001132 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1133 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001134 }
1135
Mathias Agopian5307d172012-09-18 17:02:43 -07001136 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001137 pid_t pid = IPCThreadState::self()->getCallingPid();
1138
1139 String8 connPackageName =
1140 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1141 String16 connOpPackageName =
1142 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001143 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001144 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001145 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001146 if (requestedMode == DATA_INJECTION) {
1147 if (mActiveConnections.indexOf(result) < 0) {
1148 mActiveConnections.add(result);
1149 }
1150 // Add the associated file descriptor to the Looper for polling whenever there is data to
1151 // be injected.
1152 result->updateLooperRegistration(mLooper);
1153 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001154 return result;
1155}
1156
Aravind Akella841a5922015-06-29 12:37:48 -07001157int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001158 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001159 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001160}
1161
Peng Xue36e3472016-11-03 11:57:10 -07001162sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1163 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1164 const native_handle *resource) {
1165 Mutex::Autolock _l(mLock);
1166
Michael Groover5e1f60b2018-12-04 22:34:29 -08001167 // No new direct connections are allowed when sensor privacy is enabled
1168 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1169 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1170 return nullptr;
1171 }
1172
Peng Xue36e3472016-11-03 11:57:10 -07001173 struct sensors_direct_mem_t mem = {
1174 .type = type,
1175 .format = format,
1176 .size = size,
1177 .handle = resource,
1178 };
1179 uid_t uid = IPCThreadState::self()->getCallingUid();
1180
1181 if (mem.handle == nullptr) {
1182 ALOGE("Failed to clone resource handle");
1183 return nullptr;
1184 }
1185
1186 // check format
1187 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1188 ALOGE("Direct channel format %d is unsupported!", format);
1189 return nullptr;
1190 }
1191
1192 // check for duplication
1193 for (auto &i : mDirectConnections) {
1194 sp<SensorDirectConnection> connection(i.promote());
1195 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001196 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001197 return nullptr;
1198 }
1199 }
1200
1201 // check specific to memory type
1202 switch(type) {
1203 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001204 if (resource->numFds < 1) {
1205 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1206 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1207 return nullptr;
1208 }
Peng Xue36e3472016-11-03 11:57:10 -07001209 int fd = resource->data[0];
1210 int size2 = ashmem_get_size_region(fd);
1211 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001212 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001213 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1214 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001215 return nullptr;
1216 }
1217 break;
1218 }
1219 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001220 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001221 break;
1222 default:
1223 ALOGE("Unknown direct connection memory type %d", type);
1224 return nullptr;
1225 }
1226
1227 native_handle_t *clone = native_handle_clone(resource);
1228 if (!clone) {
1229 return nullptr;
1230 }
1231
1232 SensorDirectConnection* conn = nullptr;
1233 SensorDevice& dev(SensorDevice::getInstance());
1234 int channelHandle = dev.registerDirectChannel(&mem);
1235
1236 if (channelHandle <= 0) {
1237 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1238 } else {
1239 mem.handle = clone;
1240 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1241 }
1242
1243 if (conn == nullptr) {
1244 native_handle_close(clone);
1245 native_handle_delete(clone);
1246 } else {
1247 // add to list of direct connections
1248 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1249 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1250 }
1251 return conn;
1252}
1253
Peng Xudd5c5cb2017-03-16 17:39:43 -07001254int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001255 int32_t handle, int32_t type,
1256 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001257 Mutex::Autolock _l(mLock);
1258
Alexey Polyudov88711e82017-05-23 19:54:04 -07001259 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001260 return PERMISSION_DENIED;
1261 }
1262
1263 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001264 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001265 size_t expectSize = INT32_MAX;
1266 switch (type) {
1267 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1268 isFloat = true;
1269 expectSize = 3;
1270 break;
1271 case AINFO_LOCAL_GRAVITY:
1272 isFloat = true;
1273 expectSize = 1;
1274 break;
1275 case AINFO_DOCK_STATE:
1276 case AINFO_HIGH_PERFORMANCE_MODE:
1277 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1278 isFloat = false;
1279 expectSize = 1;
1280 break;
1281 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001282 // CUSTOM events must only contain float data; it may have variable size
1283 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1284 ints.size() ||
1285 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1286 handle < 0) {
1287 return BAD_VALUE;
1288 }
1289 isFloat = true;
1290 isCustom = true;
1291 expectSize = floats.size();
1292 break;
1293 }
1294
1295 if (!isCustom && handle != -1) {
1296 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001297 }
1298
1299 // three events: first one is begin tag, last one is end tag, the one in the middle
1300 // is the payload.
1301 sensors_event_t event[3];
1302 int64_t timestamp = elapsedRealtimeNano();
1303 for (sensors_event_t* i = event; i < event + 3; i++) {
1304 *i = (sensors_event_t) {
1305 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001306 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001307 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1308 .timestamp = timestamp++,
1309 .additional_info = (additional_info_event_t) {
1310 .serial = 0
1311 }
1312 };
1313 }
1314
1315 event[0].additional_info.type = AINFO_BEGIN;
1316 event[1].additional_info.type = type;
1317 event[2].additional_info.type = AINFO_END;
1318
1319 if (isFloat) {
1320 if (floats.size() != expectSize) {
1321 return BAD_VALUE;
1322 }
1323 for (size_t i = 0; i < expectSize; ++i) {
1324 event[1].additional_info.data_float[i] = floats[i];
1325 }
1326 } else {
1327 if (ints.size() != expectSize) {
1328 return BAD_VALUE;
1329 }
1330 for (size_t i = 0; i < expectSize; ++i) {
1331 event[1].additional_info.data_int32[i] = ints[i];
1332 }
1333 }
1334
1335 SensorDevice& dev(SensorDevice::getInstance());
1336 for (sensors_event_t* i = event; i < event + 3; i++) {
1337 int ret = dev.injectSensorData(i);
1338 if (ret != NO_ERROR) {
1339 return ret;
1340 }
1341 }
1342 return NO_ERROR;
1343}
1344
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001345status_t SensorService::resetToNormalMode() {
1346 Mutex::Autolock _l(mLock);
1347 return resetToNormalModeLocked();
1348}
1349
1350status_t SensorService::resetToNormalModeLocked() {
1351 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001352 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301353 if (err == NO_ERROR) {
1354 mCurrentOperatingMode = NORMAL;
1355 dev.enableAllSensors();
1356 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001357 return err;
1358}
1359
Peng Xu47e96012016-03-28 17:55:56 -07001360void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001361 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001362 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001363 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001364 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001365 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001366 int handle = mActiveSensors.keyAt(i);
1367 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001368 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001369 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1370 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001371 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001372 } else {
1373 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001374 }
Aravind Akella8a969552014-09-28 17:52:41 -07001375 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001376 }
1377 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001378 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001379 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001380 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001381 c, i, handle);
1382
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001383 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001384 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001385 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001386 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001387 delete rec;
1388 size--;
1389 } else {
1390 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001391 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001392 }
Aravind Akella8a969552014-09-28 17:52:41 -07001393 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001394 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001395 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001396 if (c->needsWakeLock()) {
1397 checkWakeLockStateLocked();
1398 }
Peng Xu4f707f82016-09-26 11:28:32 -07001399
Brian Stack793f4642019-04-18 17:21:34 -07001400 {
1401 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1402 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1403 if (iter != sPackageTargetVersion.end()) {
1404 sPackageTargetVersion.erase(iter);
1405 }
1406 }
1407
Peng Xu4f707f82016-09-26 11:28:32 -07001408 SensorDevice& dev(SensorDevice::getInstance());
1409 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001410}
1411
Peng Xue36e3472016-11-03 11:57:10 -07001412void SensorService::cleanupConnection(SensorDirectConnection* c) {
1413 Mutex::Autolock _l(mLock);
1414
1415 SensorDevice& dev(SensorDevice::getInstance());
1416 dev.unregisterDirectChannel(c->getHalChannelHandle());
1417 mDirectConnections.remove(c);
1418}
1419
Peng Xu755c4512016-04-07 23:15:14 -07001420sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001421 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001422}
1423
Mathias Agopianfc328812010-07-14 23:41:37 -07001424status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001425 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001426 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001427 if (mInitCheck != NO_ERROR)
1428 return mInitCheck;
1429
Peng Xu755c4512016-04-07 23:15:14 -07001430 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1431 if (sensor == nullptr ||
1432 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001433 return BAD_VALUE;
1434 }
1435
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001436 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001437 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001438 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001439 return INVALID_OPERATION;
1440 }
1441
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001442 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001443 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001444 rec = new SensorRecord(connection);
1445 mActiveSensors.add(handle, rec);
1446 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001447 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001448 }
Brian Stack26029ee2019-04-22 17:25:49 -07001449
1450 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1451 // the recent event as stale to ensure that the previous event is not sent to a client. This
1452 // ensures on-change events that were generated during a previous sensor activation are not
1453 // erroneously sent to newly connected clients, especially if a second client registers for
1454 // an on-change sensor before the first client receives the updated event. Once an updated
1455 // event is received, the recent events will be marked as current, and any new clients will
1456 // immediately receive the most recent event.
1457 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1458 auto logger = mRecentEvent.find(handle);
1459 if (logger != mRecentEvent.end()) {
1460 logger->second->setLastEventStale();
1461 }
1462 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001463 } else {
1464 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001465 // this sensor is already activated, but we are adding a connection that uses it.
1466 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001467 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001468 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001469 // NOTE: The wake_up flag of this event may get set to
1470 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001471
1472 auto logger = mRecentEvent.find(handle);
1473 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001474 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001475 // Verify that the last sensor event was generated from the current activation
1476 // of the sensor. If not, it is possible for an on-change sensor to receive a
1477 // sensor event that is stale if two clients re-activate the sensor
1478 // simultaneously.
1479 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001480 event.sensor = handle;
1481 if (event.version == sizeof(sensors_event_t)) {
1482 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1483 setWakeLockAcquiredLocked(true);
1484 }
Yi Kong8f313e32018-07-17 14:13:29 -07001485 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001486 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1487 checkWakeLockStateLocked();
1488 }
1489 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001490 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001491 }
1492 }
1493 }
1494 }
1495
1496 if (connection->addSensor(handle)) {
1497 BatteryService::enableSensor(connection->getUid(), handle);
1498 // the sensor was added (which means it wasn't already there)
1499 // so, see if this connection becomes active
1500 if (mActiveConnections.indexOf(connection) < 0) {
1501 mActiveConnections.add(connection);
1502 }
1503 } else {
1504 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1505 handle, connection.get());
1506 }
1507
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301508 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001509 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301510 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1511 samplingPeriodNs = maxDelayNs;
1512 }
1513
Aravind Akella724d91d2013-06-27 12:04:23 -07001514 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1515 if (samplingPeriodNs < minDelayNs) {
1516 samplingPeriodNs = minDelayNs;
1517 }
1518
Aravind Akella6c2664a2014-08-13 12:24:50 -07001519 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1520 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001521 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1522
Aravind Akella4949c502015-02-11 15:54:35 -08001523 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001524 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001525
Peng Xu20483c42015-10-26 15:14:43 -07001526 // Call flush() before calling activate() on the sensor. Wait for a first
1527 // flush complete event before sending events on this connection. Ignore
1528 // one-shot sensors which don't support flush(). Ignore on-change sensors
1529 // to maintain the on-change logic (any on-change events except the initial
1530 // one should be trigger by a change in value). Also if this sensor isn't
1531 // already active, don't call flush().
1532 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001533 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001534 rec->getNumConnections() > 1) {
1535 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001536 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001537 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001538 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001539 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001540 } else {
1541 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001542 }
1543 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001544
1545 if (err == NO_ERROR) {
1546 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1547 err = sensor->activate(connection.get(), true);
1548 }
1549
Aravind Akella8a969552014-09-28 17:52:41 -07001550 if (err == NO_ERROR) {
1551 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001552
Brian Stack240d1d62019-05-17 09:49:39 -07001553 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1554 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001555 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1556 }
1557
Peng Xu51224682017-03-10 16:57:27 -08001558 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1559 SensorRegistrationInfo(handle, connection->getPackageName(),
1560 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001561 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001562 }
1563
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001564 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001565 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001566 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001567 }
1568 return err;
1569}
1570
Peng Xu47e96012016-03-28 17:55:56 -07001571status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001572 if (mInitCheck != NO_ERROR)
1573 return mInitCheck;
1574
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001575 Mutex::Autolock _l(mLock);
1576 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001577 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001578 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1579 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001580
1581 }
1582 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001583 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1584 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001585 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001586 }
1587 return err;
1588}
1589
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001590status_t SensorService::cleanupWithoutDisable(
1591 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001592 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001593 return cleanupWithoutDisableLocked(connection, handle);
1594}
1595
1596status_t SensorService::cleanupWithoutDisableLocked(
1597 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001598 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001599 if (rec) {
1600 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001601 if (connection->removeSensor(handle)) {
1602 BatteryService::disableSensor(connection->getUid(), handle);
1603 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001604 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001605 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001606 mActiveConnections.remove(connection);
1607 }
1608 // see if this sensor becomes inactive
1609 if (rec->removeConnection(connection)) {
1610 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001611 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001612 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001613 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001614 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001615 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001616 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001617}
1618
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001619status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001620 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001621 if (mInitCheck != NO_ERROR)
1622 return mInitCheck;
1623
Peng Xu755c4512016-04-07 23:15:14 -07001624 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1625 if (sensor == nullptr ||
1626 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001627 return BAD_VALUE;
1628 }
1629
Mathias Agopian1cd70002010-07-21 15:59:50 -07001630 if (ns < 0)
1631 return BAD_VALUE;
1632
Mathias Agopian62569ec2011-11-07 21:21:47 -08001633 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1634 if (ns < minDelayNs) {
1635 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001636 }
1637
Mathias Agopianf001c922010-11-11 17:58:51 -08001638 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001639}
1640
Svetoslavb412f6e2015-04-29 16:50:41 -07001641status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1642 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001643 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001644 SensorDevice& dev(SensorDevice::getInstance());
1645 const int halVersion = dev.getHalDeviceVersion();
1646 status_t err(NO_ERROR);
1647 Mutex::Autolock _l(mLock);
1648 // Loop through all sensors for this connection and call flush on each of them.
1649 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1650 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001651 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1652 if (sensor == nullptr) {
1653 continue;
1654 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001655 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1656 ALOGE("flush called on a one-shot sensor");
1657 err = INVALID_OPERATION;
1658 continue;
1659 }
Aravind Akella8493b792014-09-08 15:45:47 -07001660 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001661 // For older devices just increment pending flush count which will send a trivial
1662 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001663 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001664 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001665 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1666 err = INVALID_OPERATION;
1667 continue;
1668 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001669 status_t err_flush = sensor->flush(connection.get(), handle);
1670 if (err_flush == NO_ERROR) {
1671 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001672 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001673 }
1674 err = (err_flush != NO_ERROR) ? err_flush : err;
1675 }
Aravind Akella70018042014-04-07 22:52:37 +00001676 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001677 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001678}
Aravind Akella70018042014-04-07 22:52:37 +00001679
Svetoslavb412f6e2015-04-29 16:50:41 -07001680bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1681 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001682 // Check if a permission is required for this sensor
1683 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001684 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001685 }
1686
Brian Stack793f4642019-04-18 17:21:34 -07001687 const int32_t opCode = sensor.getRequiredAppOp();
1688 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1689 IPCThreadState::self()->getCallingUid(), opPackageName);
Brian Stack6a700f92019-05-08 17:02:53 -07001690 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
Brian Stack793f4642019-04-18 17:21:34 -07001691
Brian Stack793f4642019-04-18 17:21:34 -07001692 bool canAccess = false;
Brian Stack6a700f92019-05-08 17:02:53 -07001693 if (hasPermissionForSensor(sensor)) {
1694 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1695 if (opCode < 0 || appOpAllowed) {
Brian Stack793f4642019-04-18 17:21:34 -07001696 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001697 }
1698 } else if (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1699 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR) {
1700 int targetSdkVersion = getTargetSdkVersion(opPackageName);
1701 // Allow access to the sensor if the application targets pre-Q, which is before the
1702 // requirement to hold the AR permission to access Step Counter and Step Detector events
1703 // was introduced, and the user hasn't revoked the app op.
1704 //
1705 // Verifying the app op is required to ensure that the user hasn't revoked the necessary
1706 // permissions to access the Step Detector and Step Counter when the application targets
1707 // pre-Q. Without this check, if the user revokes the pre-Q install-time GMS Core AR
1708 // permission, the app would still be able to receive Step Counter and Step Detector events.
1709 if (appOpAllowed &&
1710 targetSdkVersion > 0 &&
1711 targetSdkVersion <= __ANDROID_API_P__) {
1712 canAccess = true;
Brian Stack793f4642019-04-18 17:21:34 -07001713 }
1714 }
1715
1716 if (canAccess) {
1717 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1718 } else {
1719 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1720 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1721 }
1722
1723 return canAccess;
1724}
1725
1726bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001727 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001728 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001729
1730 // Runtime permissions can't use the cache as they may change.
1731 if (sensor.isRequiredPermissionRuntime()) {
1732 hasPermission = checkPermission(String16(requiredPermission),
1733 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001734 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001735 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1736 }
Brian Stack793f4642019-04-18 17:21:34 -07001737 return hasPermission;
1738}
Svetoslavb412f6e2015-04-29 16:50:41 -07001739
Brian Stack793f4642019-04-18 17:21:34 -07001740int SensorService::getTargetSdkVersion(const String16& opPackageName) {
1741 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1742 int targetSdkVersion = -1;
1743 auto entry = sPackageTargetVersion.find(opPackageName);
1744 if (entry != sPackageTargetVersion.end()) {
1745 targetSdkVersion = entry->second;
1746 } else {
1747 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1748 if (binder != nullptr) {
1749 sp<content::pm::IPackageManagerNative> packageManager =
1750 interface_cast<content::pm::IPackageManagerNative>(binder);
1751 if (packageManager != nullptr) {
1752 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1753 opPackageName, &targetSdkVersion);
1754 if (!status.isOk()) {
1755 targetSdkVersion = -1;
1756 }
1757 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001758 }
Brian Stack793f4642019-04-18 17:21:34 -07001759 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001760 }
Brian Stack793f4642019-04-18 17:21:34 -07001761 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001762}
1763
Aravind Akella9a844cf2014-02-11 18:58:52 -08001764void SensorService::checkWakeLockState() {
1765 Mutex::Autolock _l(mLock);
1766 checkWakeLockStateLocked();
1767}
1768
1769void SensorService::checkWakeLockStateLocked() {
1770 if (!mWakeLockAcquired) {
1771 return;
1772 }
1773 bool releaseLock = true;
1774 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1775 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001776 if (connection != nullptr) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001777 if (connection->needsWakeLock()) {
1778 releaseLock = false;
1779 break;
1780 }
1781 }
1782 }
1783 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001784 setWakeLockAcquiredLocked(false);
1785 }
1786}
1787
1788void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1789 Mutex::Autolock _l(mLock);
1790 connection->writeToSocketFromCache();
1791 if (connection->needsWakeLock()) {
1792 setWakeLockAcquiredLocked(true);
1793 }
1794}
1795
1796void SensorService::populateActiveConnections(
1797 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1798 Mutex::Autolock _l(mLock);
1799 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1800 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001801 if (connection != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001802 activeConnections->add(connection);
1803 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001804 }
1805}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001806
Aravind Akella4949c502015-02-11 15:54:35 -08001807bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001808 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001809}
1810
Brian Stack5180e462019-03-08 17:15:19 -08001811bool SensorService::isOperationPermitted(const String16& opPackageName) {
Peng Xue36e3472016-11-03 11:57:10 -07001812 Mutex::Autolock _l(mLock);
Brian Stack5180e462019-03-08 17:15:19 -08001813 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001814 String8 package(opPackageName);
Brian Stack5180e462019-03-08 17:15:19 -08001815 return isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001816 }
Brian Stack5180e462019-03-08 17:15:19 -08001817 return true;
Peng Xue36e3472016-11-03 11:57:10 -07001818}
1819
Svet Ganove752a5c2018-01-15 17:14:20 -08001820void SensorService::UidPolicy::registerSelf() {
1821 ActivityManager am;
1822 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1823 | ActivityManager::UID_OBSERVER_IDLE
1824 | ActivityManager::UID_OBSERVER_ACTIVE,
1825 ActivityManager::PROCESS_STATE_UNKNOWN,
1826 String16("android"));
1827}
1828
1829void SensorService::UidPolicy::unregisterSelf() {
1830 ActivityManager am;
1831 am.unregisterUidObserver(this);
1832}
1833
1834void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1835 onUidIdle(uid, disabled);
1836}
1837
1838void SensorService::UidPolicy::onUidActive(uid_t uid) {
1839 {
1840 Mutex::Autolock _l(mUidLock);
1841 mActiveUids.insert(uid);
1842 }
1843 sp<SensorService> service = mService.promote();
1844 if (service != nullptr) {
1845 service->setSensorAccess(uid, true);
1846 }
1847}
1848
1849void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1850 bool deleted = false;
1851 {
1852 Mutex::Autolock _l(mUidLock);
1853 if (mActiveUids.erase(uid) > 0) {
1854 deleted = true;
1855 }
1856 }
1857 if (deleted) {
1858 sp<SensorService> service = mService.promote();
1859 if (service != nullptr) {
1860 service->setSensorAccess(uid, false);
1861 }
1862 }
1863}
1864
1865void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1866 updateOverrideUid(uid, active, true);
1867}
1868
1869void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1870 updateOverrideUid(uid, false, false);
1871}
1872
1873void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1874 bool wasActive = false;
1875 bool isActive = false;
1876 {
1877 Mutex::Autolock _l(mUidLock);
1878 wasActive = isUidActiveLocked(uid);
1879 mOverrideUids.erase(uid);
1880 if (insert) {
1881 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1882 }
1883 isActive = isUidActiveLocked(uid);
1884 }
1885 if (wasActive != isActive) {
1886 sp<SensorService> service = mService.promote();
1887 if (service != nullptr) {
1888 service->setSensorAccess(uid, isActive);
1889 }
1890 }
1891}
1892
1893bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1894 // Non-app UIDs are considered always active
1895 if (uid < FIRST_APPLICATION_UID) {
1896 return true;
1897 }
1898 Mutex::Autolock _l(mUidLock);
1899 return isUidActiveLocked(uid);
1900}
1901
1902bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1903 // Non-app UIDs are considered always active
1904 if (uid < FIRST_APPLICATION_UID) {
1905 return true;
1906 }
1907 auto it = mOverrideUids.find(uid);
1908 if (it != mOverrideUids.end()) {
1909 return it->second;
1910 }
1911 return mActiveUids.find(uid) != mActiveUids.end();
1912}
1913
Michael Groover5e1f60b2018-12-04 22:34:29 -08001914void SensorService::SensorPrivacyPolicy::registerSelf() {
1915 SensorPrivacyManager spm;
1916 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1917 spm.addSensorPrivacyListener(this);
1918}
1919
1920void SensorService::SensorPrivacyPolicy::unregisterSelf() {
1921 SensorPrivacyManager spm;
1922 spm.removeSensorPrivacyListener(this);
1923}
1924
1925bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1926 return mSensorPrivacyEnabled;
1927}
1928
1929binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1930 mSensorPrivacyEnabled = enabled;
1931 sp<SensorService> service = mService.promote();
1932 if (service != nullptr) {
1933 if (enabled) {
1934 service->disableAllSensors();
1935 } else {
1936 service->enableAllSensors();
1937 }
1938 }
1939 return binder::Status::ok();
1940}
Mathias Agopianfc328812010-07-14 23:41:37 -07001941}; // namespace android