blob: 02699906ed7e18be60385d398ca41ea03dba75a6 [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 */
Svet Ganove752a5c2018-01-15 17:14:20 -080016#include <binder/ActivityManager.h>
Svetoslavb412f6e2015-04-29 16:50:41 -070017#include <binder/AppOpsManager.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;
78
79#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
80#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070081#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070082
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070083// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070084static const String16 sDumpPermission("android.permission.DUMP");
85static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080086static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070087
Mathias Agopianfc328812010-07-14 23:41:37 -070088SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070089 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070090 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +090091 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -080092 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -070093}
94
Greg Kaiser53ca2e02016-06-21 16:11:14 -070095bool SensorService::initializeHmacKey() {
96 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
97 if (fd != -1) {
98 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
99 close(fd);
100 if (result == sizeof(sHmacGlobalKey)) {
101 return true;
102 }
103 ALOGW("Unable to read HMAC key; generating new one.");
104 }
105
106 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
107 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
108 return false;
109 }
110
111 // We need to make sure this is only readable to us.
112 bool wroteKey = false;
113 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
114 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
115 S_IRUSR|S_IWUSR);
116 if (fd != -1) {
117 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
118 close(fd);
119 wroteKey = (result == sizeof(sHmacGlobalKey));
120 }
121 if (wroteKey) {
122 ALOGI("Generated new HMAC key.");
123 } else {
124 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
125 "after reboot.");
126 }
127 // Even if we failed to write the key we return true, because we did
128 // initialize the HMAC key.
129 return true;
130}
131
Peng Xu98d30f62016-08-01 18:12:11 -0700132// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
133void SensorService::enableSchedFifoMode() {
134 struct sched_param param = {0};
135 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
136 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
137 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
138 }
139}
140
Peng Xu47e96012016-03-28 17:55:56 -0700141void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000142 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800143 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700144
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700145 sHmacGlobalKeyIsValid = initializeHmacKey();
146
Mathias Agopianf001c922010-11-11 17:58:51 -0800147 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800148 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700149 ssize_t count = dev.getSensorList(&list);
150 if (count > 0) {
151 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700152 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700153 uint32_t virtualSensorsNeeds =
154 (1<<SENSOR_TYPE_GRAVITY) |
155 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700156 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
157 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
158 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700159
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700160 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700161 bool useThisSensor=true;
162
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700163 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700164 case SENSOR_TYPE_ACCELEROMETER:
165 hasAccel = true;
166 break;
167 case SENSOR_TYPE_MAGNETIC_FIELD:
168 hasMag = true;
169 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700170 case SENSOR_TYPE_ORIENTATION:
171 orientationIndex = i;
172 break;
173 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700174 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700175 hasGyro = true;
176 break;
177 case SENSOR_TYPE_GRAVITY:
178 case SENSOR_TYPE_LINEAR_ACCELERATION:
179 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700180 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
181 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
182 if (IGNORE_HARDWARE_FUSION) {
183 useThisSensor = false;
184 } else {
185 virtualSensorsNeeds &= ~(1<<list[i].type);
186 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700187 break;
188 }
Peng Xuf66684a2015-07-23 11:41:53 -0700189 if (useThisSensor) {
190 registerSensor( new HardwareSensor(list[i]) );
191 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700192 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700193
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700194 // it's safe to instantiate the SensorFusion object here
195 // (it wants to be instantiated after h/w sensors have been
196 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700197 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700198
Aravind Akellaf5047892015-07-20 17:29:33 -0700199 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700200 // Add Android virtual sensors if they're not already
201 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700202 bool needRotationVector =
203 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700204
Peng Xu0cc8f802016-04-05 23:46:03 -0700205 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
206 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700207
Peng Xu0cc8f802016-04-05 23:46:03 -0700208 bool needLinearAcceleration =
209 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700210
Peng Xu0cc8f802016-04-05 23:46:03 -0700211 registerSensor(new LinearAccelerationSensor(list, count),
212 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700213
Peng Xu0cc8f802016-04-05 23:46:03 -0700214 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700215 registerSensor( new CorrectedGyroSensor(list, count), true, true);
216 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700217 }
218
Peng Xuf66684a2015-07-23 11:41:53 -0700219 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700220 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
221 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700222
Peng Xu0cc8f802016-04-05 23:46:03 -0700223 bool needGameRotationVector =
224 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
225 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700226 }
227
228 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700229 bool needGeoMagRotationVector =
230 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
231 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700232 }
233
Aravind Akella5466c3d2014-08-22 16:11:10 -0700234 // Check if the device really supports batching by looking at the FIFO event
235 // counts for each sensor.
236 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700237 mSensors.forEachSensor(
238 [&batchingSupported] (const Sensor& s) -> bool {
239 if (s.getFifoMaxEventCount() > 0) {
240 batchingSupported = true;
241 }
242 return !batchingSupported;
243 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700244
245 if (batchingSupported) {
246 // Increase socket buffer size to a max of 100 KB for batching capabilities.
247 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
248 } else {
249 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
250 }
251
252 // Compare the socketBufferSize value against the system limits and limit
253 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700254 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
255 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700256 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700257 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700258 size_t maxSystemSocketBufferSize;
259 sscanf(line, "%zu", &maxSystemSocketBufferSize);
260 if (mSocketBufferSize > maxSystemSocketBufferSize) {
261 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700262 }
263 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700264 if (fp) {
265 fclose(fp);
266 }
267
Aravind Akella9a844cf2014-02-11 18:58:52 -0800268 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700269 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700270 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
271 mSensorEventBuffer = new sensors_event_t[minBufferSize];
272 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700273 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700274 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700275
Aravind Akella18d6d512015-06-18 14:18:28 -0700276 mNextSensorRegIndex = 0;
277 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
278 mLastNSensorRegistrations.push();
279 }
280
281 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700282 mAckReceiver = new SensorEventAckReceiver(this);
283 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700284 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700285
286 // priority can only be changed after run
287 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800288
289 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800290 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800291
292 // Start watching sensor privacy changes
293 mSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800294 }
295 }
296}
297
298void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
299 SortedVector< sp<SensorEventConnection> > activeConnections;
300 populateActiveConnections(&activeConnections);
301 {
302 Mutex::Autolock _l(mLock);
303 for (size_t i = 0 ; i < activeConnections.size(); i++) {
Yi Kong8f313e32018-07-17 14:13:29 -0700304 if (activeConnections[i] != nullptr && activeConnections[i]->getUid() == uid) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800305 activeConnections[i]->setSensorAccess(hasAccess);
306 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700307 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700308 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700309}
310
Peng Xu0cc8f802016-04-05 23:46:03 -0700311const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
312 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800313 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700314 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700315 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700316 return s->getSensor();
317 } else {
318 return mSensors.getNonSensor();
319 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800320}
321
Peng Xu6a2d3a02015-12-21 12:00:23 -0800322const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700323 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800324}
325
Peng Xu6a2d3a02015-12-21 12:00:23 -0800326bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700327 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800328
329 const auto i = mRecentEvent.find(handle);
330 if (i != mRecentEvent.end()) {
331 delete i->second;
332 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800333 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700334 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800335}
336
Peng Xu0cc8f802016-04-05 23:46:03 -0700337const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
338 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700339}
340
Peng Xu47e96012016-03-28 17:55:56 -0700341SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800342 for (auto && entry : mRecentEvent) {
343 delete entry.second;
344 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800345 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800346 mSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700347}
348
349status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700350 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700351 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800352 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700353 IPCThreadState::self()->getCallingPid(),
354 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700355 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700356 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700357 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800358 return INVALID_OPERATION;
359 }
360 Mutex::Autolock _l(mLock);
361 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700362 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700363 // If already in restricted mode. Ignore.
364 if (mCurrentOperatingMode == RESTRICTED) {
365 return status_t(NO_ERROR);
366 }
367 // If in any mode other than normal, ignore.
368 if (mCurrentOperatingMode != NORMAL) {
369 return INVALID_OPERATION;
370 }
Peng Xue36e3472016-11-03 11:57:10 -0700371
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700372 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800373 // temporarily stop all sensor direct report and disable sensors
374 disableAllSensorsLocked();
Aravind Akella841a5922015-06-29 12:37:48 -0700375 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700376 return status_t(NO_ERROR);
377 } else if (args.size() == 1 && args[0] == String16("enable")) {
378 // If currently in restricted mode, reset back to NORMAL mode else ignore.
379 if (mCurrentOperatingMode == RESTRICTED) {
380 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800381 // enable sensors and recover all sensor direct report
382 enableAllSensorsLocked();
Aravind Akella444f2672015-05-07 12:40:52 -0700383 }
Aravind Akella841a5922015-06-29 12:37:48 -0700384 if (mCurrentOperatingMode == DATA_INJECTION) {
385 resetToNormalModeLocked();
386 }
387 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700388 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700389 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
390 if (mCurrentOperatingMode == NORMAL) {
391 dev.disableAllSensors();
392 status_t err = dev.setMode(DATA_INJECTION);
393 if (err == NO_ERROR) {
394 mCurrentOperatingMode = DATA_INJECTION;
395 } else {
396 // Re-enable sensors.
397 dev.enableAllSensors();
398 }
399 mWhiteListedPackage.setTo(String8(args[1]));
400 return NO_ERROR;
401 } else if (mCurrentOperatingMode == DATA_INJECTION) {
402 // Already in DATA_INJECTION mode. Treat this as a no_op.
403 return NO_ERROR;
404 } else {
405 // Transition to data injection mode supported only from NORMAL mode.
406 return INVALID_OPERATION;
407 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700408 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700409 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700410 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700411 } else {
412 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700413 //
Brian Stack51498e62018-10-03 10:52:21 -0700414 timespec curTime;
415 clock_gettime(CLOCK_REALTIME, &curTime);
416 struct tm* timeinfo = localtime(&(curTime.tv_sec));
417 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
418 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800419 result.append("Sensor Device:\n");
420 result.append(SensorDevice::getInstance().dump().c_str());
421
422 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700423 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700424
Peng Xu6a2d3a02015-12-21 12:00:23 -0800425 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700426 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700427
Peng Xu0cc8f802016-04-05 23:46:03 -0700428 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800429 for (auto&& i : mRecentEvent) {
430 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700431 if (!i.second->isEmpty()) {
432 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
433 i.second->setFormat("normal");
434 } else {
435 i.second->setFormat("mask_data");
436 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800437 // if there is events and sensor does not need special permission.
438 result.appendFormat("%s: ", s->getSensor().getName().string());
439 result.append(i.second->dump().c_str());
440 }
441 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700442
Aravind Akella444f2672015-05-07 12:40:52 -0700443 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700444 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700445 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
446 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700447 if (dev.isSensorActive(handle)) {
448 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
449 getSensorName(handle).string(),
450 handle,
451 mActiveSensors.valueAt(i)->getNumConnections());
452 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700453 }
454
Andreas Gamped4036b62015-07-28 13:49:04 -0700455 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700456 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700457 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
458 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700459 result.appendFormat("Mode :");
460 switch(mCurrentOperatingMode) {
461 case NORMAL:
462 result.appendFormat(" NORMAL\n");
463 break;
464 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700465 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700466 break;
467 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700468 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700469 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800470 result.appendFormat("Sensor Privacy: %s\n",
471 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700472
Peng Xue36e3472016-11-03 11:57:10 -0700473 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella444f2672015-05-07 12:40:52 -0700474 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
475 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -0700476 if (connection != nullptr) {
Aravind Akella444f2672015-05-07 12:40:52 -0700477 result.appendFormat("Connection Number: %zu \n", i);
478 connection->dump(result);
479 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700480 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700481
Peng Xue36e3472016-11-03 11:57:10 -0700482 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
483 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
484 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
485 if (connection != nullptr) {
486 result.appendFormat("Direct connection %zu:\n", i);
487 connection->dump(result);
488 }
489 }
490
Aravind Akella18d6d512015-06-18 14:18:28 -0700491 result.appendFormat("Previous Registrations:\n");
492 // Log in the reverse chronological order.
493 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
494 SENSOR_REGISTRATIONS_BUF_SIZE;
495 const int startIndex = currentIndex;
496 do {
497 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
498 if (SensorRegistrationInfo::isSentinel(reg_info)) {
499 // Ignore sentinel, proceed to next item.
500 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
501 SENSOR_REGISTRATIONS_BUF_SIZE;
502 continue;
503 }
Peng Xu51224682017-03-10 16:57:27 -0800504 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700505 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
506 SENSOR_REGISTRATIONS_BUF_SIZE;
507 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700508 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700509 }
510 write(fd, result.string(), result.size());
511 return NO_ERROR;
512}
513
Michael Groover5e1f60b2018-12-04 22:34:29 -0800514void SensorService::disableAllSensors() {
515 Mutex::Autolock _l(mLock);
516 disableAllSensorsLocked();
517}
518
519void SensorService::disableAllSensorsLocked() {
520 SensorDevice& dev(SensorDevice::getInstance());
521 for (auto &i : mDirectConnections) {
522 sp<SensorDirectConnection> connection(i.promote());
523 if (connection != nullptr) {
524 connection->stopAll(true /* backupRecord */);
525 }
526 }
527 dev.disableAllSensors();
528 // Clear all pending flush connections for all active sensors. If one of the active
529 // connections has called flush() and the underlying sensor has been disabled before a
530 // flush complete event is returned, we need to remove the connection from this queue.
531 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
532 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
533 }
534}
535
536void SensorService::enableAllSensors() {
537 Mutex::Autolock _l(mLock);
538 enableAllSensorsLocked();
539}
540
541void SensorService::enableAllSensorsLocked() {
542 // sensors should only be enabled if the operating state is not restricted and sensor
543 // privacy is not enabled.
544 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
545 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
546 mCurrentOperatingMode,
547 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
548 return;
549 }
550 SensorDevice& dev(SensorDevice::getInstance());
551 dev.enableAllSensors();
552 for (auto &i : mDirectConnections) {
553 sp<SensorDirectConnection> connection(i.promote());
554 if (connection != nullptr) {
555 connection->recoverAll();
556 }
557 }
558}
559
Svet Ganove752a5c2018-01-15 17:14:20 -0800560// NOTE: This is a remote API - make sure all args are validated
561status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
562 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
563 return PERMISSION_DENIED;
564 }
565 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
566 return BAD_VALUE;
567 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700568 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800569 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700570 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800571 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700572 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800573 return handleGetUidState(args, out, err);
574 } else if (args.size() == 1 && args[0] == String16("help")) {
575 printHelp(out);
576 return NO_ERROR;
577 }
578 printHelp(err);
579 return BAD_VALUE;
580}
581
Tanmay Patild33a1822019-04-11 18:38:55 -0700582static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800583 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700584 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800585 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700586 ALOGE("Unknown package: '%s'", String8(packageName).string());
587 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800588 return BAD_VALUE;
589 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700590
591 if (userId < 0) {
592 ALOGE("Invalid user: %d", userId);
593 dprintf(err, "Invalid user: %d\n", userId);
594 return BAD_VALUE;
595 }
596
597 uid = multiuser_get_uid(userId, uid);
598 return NO_ERROR;
599}
600
601status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
602 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
603 if (!(args.size() == 3 || args.size() == 5)) {
604 printHelp(err);
605 return BAD_VALUE;
606 }
607
Svet Ganove752a5c2018-01-15 17:14:20 -0800608 bool active = false;
609 if (args[2] == String16("active")) {
610 active = true;
611 } else if ((args[2] != String16("idle"))) {
612 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
613 return BAD_VALUE;
614 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700615
616 int userId = 0;
617 if (args.size() == 5 && args[3] == String16("--user")) {
618 userId = atoi(String8(args[4]));
619 }
620
621 uid_t uid;
622 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
623 return BAD_VALUE;
624 }
625
Svet Ganove752a5c2018-01-15 17:14:20 -0800626 mUidPolicy->addOverrideUid(uid, active);
627 return NO_ERROR;
628}
629
630status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700631 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
632 if (!(args.size() == 2 || args.size() == 4)) {
633 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800634 return BAD_VALUE;
635 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700636
637 int userId = 0;
638 if (args.size() == 4 && args[2] == String16("--user")) {
639 userId = atoi(String8(args[3]));
640 }
641
642 uid_t uid;
643 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
644 return BAD_VALUE;
645 }
646
Svet Ganove752a5c2018-01-15 17:14:20 -0800647 mUidPolicy->removeOverrideUid(uid);
648 return NO_ERROR;
649}
650
651status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700652 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
653 if (!(args.size() == 2 || args.size() == 4)) {
654 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800655 return BAD_VALUE;
656 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700657
658 int userId = 0;
659 if (args.size() == 4 && args[2] == String16("--user")) {
660 userId = atoi(String8(args[3]));
661 }
662
663 uid_t uid;
664 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
665 return BAD_VALUE;
666 }
667
Svet Ganove752a5c2018-01-15 17:14:20 -0800668 if (mUidPolicy->isUidActive(uid)) {
669 return dprintf(out, "active\n");
670 } else {
671 return dprintf(out, "idle\n");
672 }
673}
674
675status_t SensorService::printHelp(int out) {
676 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700677 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
678 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
679 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800680 " help print this message\n");
681}
682
Peng Xu0cc8f802016-04-05 23:46:03 -0700683//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800684void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700685 sensors_event_t const* buffer, const int count) {
686 for (int i=0 ; i<count ; i++) {
687 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700688 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
689 handle = buffer[i].meta_data.sensor;
690 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700691 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700692 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700693 // If this buffer has an event from a one_shot sensor and this connection is registered
694 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700695 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700696 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
697 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800698 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700699 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700700
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700701 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700702 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700703}
704
Peng Xu47e96012016-03-28 17:55:56 -0700705bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000706 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700707
Peng Xueb4d6282015-12-10 18:02:41 -0800708 // each virtual sensor could generate an event per "real" event, that's why we need to size
709 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
710 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700711 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700712 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700713 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700714
Mathias Agopianf001c922010-11-11 17:58:51 -0800715 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700716
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700717 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700718 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700719 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
720 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700721 if(count == DEAD_OBJECT && device.isReconnecting()) {
722 device.reconnect();
723 continue;
724 } else {
725 ALOGE("sensor poll failed (%s)", strerror(-count));
726 break;
727 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700728 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700729
730 // Reset sensors_event_t.flags to zero for all events in the buffer.
731 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700732 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700733 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700734
Peng Xueb4d6282015-12-10 18:02:41 -0800735 // Make a copy of the connection vector as some connections may be removed during the course
736 // of this loop (especially when one-shot sensor events are present in the sensor_event
737 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
738 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
739 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
740 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700741 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700742 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800743
Aravind Akella9a844cf2014-02-11 18:58:52 -0800744 Mutex::Autolock _l(mLock);
745 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
746 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
747 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
748 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
749 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700750 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700751 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700752 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700753 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700754 }
755 }
756
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700757 if (wakeEvents > 0) {
758 if (!mWakeLockAcquired) {
759 setWakeLockAcquiredLocked(true);
760 }
761 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800762 }
Aravind Akella8493b792014-09-08 15:45:47 -0700763 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800764
Mathias Agopianf001c922010-11-11 17:58:51 -0800765 // handle virtual sensors
766 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700767 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700768 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800769 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700770 SensorFusion& fusion(SensorFusion::getInstance());
771 if (fusion.isEnabled()) {
772 for (size_t i=0 ; i<size_t(count) ; i++) {
773 fusion.process(event[i]);
774 }
775 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700776 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700777 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700778 if (count + k >= minBufferSize) {
779 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700780 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700781 count, k, minBufferSize);
782 break;
783 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800784 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700785 sp<SensorInterface> si = mSensors.getInterface(handle);
786 if (si == nullptr) {
787 ALOGE("handle %d is not an valid virtual sensor", handle);
788 continue;
789 }
790
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700791 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700792 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800793 k++;
794 }
795 }
796 }
797 if (k) {
798 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700799 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800800 count += k;
801 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700802 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700803 }
804 }
805 }
806
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700807 // handle backward compatibility for RotationVector sensor
808 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
809 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700810 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700811 // All the 4 components of the quaternion should be available
812 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700813 mSensorEventBuffer[i].data[4] = -1;
814 }
815 }
816 }
817
Aravind Akella8493b792014-09-08 15:45:47 -0700818 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700819 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
820 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
821 // SensorEventConnection mapped to the corresponding flush_complete_event in
822 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700823 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700824 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
825 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
826 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700827 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700828 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
829 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700830 }
831 }
Peng Xu2576cb62016-01-20 00:22:09 -0800832
833 // handle dynamic sensor meta events, process registration and unregistration of dynamic
834 // sensor based on content of event.
835 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
836 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
837 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
838 const sensor_t& dynamicSensor =
839 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
840 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
841 handle, dynamicSensor.type, dynamicSensor.name);
842
Peng Xu0cc8f802016-04-05 23:46:03 -0700843 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800844 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700845 sensor_t s = dynamicSensor;
846 // make sure the dynamic sensor flag is set
847 s.flags |= DYNAMIC_SENSOR_MASK;
848 // force the handle to be consistent
849 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800850
851 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800852
Peng Xu0cc8f802016-04-05 23:46:03 -0700853 // This will release hold on dynamic sensor meta, so it should be called
854 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700855 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800856 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700857 } else {
858 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
859 }
Peng Xu2576cb62016-01-20 00:22:09 -0800860 } else {
861 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
862 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
863
864 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800865 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800866 ALOGE("Dynamic sensor release error.");
867 }
868
869 size_t numConnections = activeConnections.size();
870 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700871 if (activeConnections[i] != nullptr) {
Peng Xu2576cb62016-01-20 00:22:09 -0800872 activeConnections[i]->removeSensor(handle);
873 }
874 }
875 }
876 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700877 }
878
Aravind Akella9a844cf2014-02-11 18:58:52 -0800879 // Send our events to clients. Check the state of wake lock for each client and release the
880 // lock if none of the clients need it.
881 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700882 size_t numConnections = activeConnections.size();
883 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700884 if (activeConnections[i] != nullptr) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700885 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700886 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700887 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700888 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
889 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700890 if (activeConnections[i]->hasOneShotSensors()) {
891 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
892 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700893 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800894 }
895 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700896
Aravind Akella9a844cf2014-02-11 18:58:52 -0800897 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700898 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800899 }
Aravind Akella8493b792014-09-08 15:45:47 -0700900 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700901
Steve Block3c20fbe2012-01-05 23:22:43 +0000902 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800903 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700904 return false;
905}
906
Aravind Akella56ae4262014-07-10 16:01:10 -0700907sp<Looper> SensorService::getLooper() const {
908 return mLooper;
909}
910
Aravind Akellab4373ac2014-10-29 17:55:20 -0700911void SensorService::resetAllWakeLockRefCounts() {
912 SortedVector< sp<SensorEventConnection> > activeConnections;
913 populateActiveConnections(&activeConnections);
914 {
915 Mutex::Autolock _l(mLock);
916 for (size_t i=0 ; i < activeConnections.size(); ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700917 if (activeConnections[i] != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700918 activeConnections[i]->resetWakeLockRefCount();
919 }
920 }
921 setWakeLockAcquiredLocked(false);
922 }
923}
924
925void SensorService::setWakeLockAcquiredLocked(bool acquire) {
926 if (acquire) {
927 if (!mWakeLockAcquired) {
928 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
929 mWakeLockAcquired = true;
930 }
931 mLooper->wake();
932 } else {
933 if (mWakeLockAcquired) {
934 release_wake_lock(WAKE_LOCK_NAME);
935 mWakeLockAcquired = false;
936 }
937 }
938}
939
Aravind Akellab4373ac2014-10-29 17:55:20 -0700940bool SensorService::isWakeLockAcquired() {
941 Mutex::Autolock _l(mLock);
942 return mWakeLockAcquired;
943}
944
Aravind Akella56ae4262014-07-10 16:01:10 -0700945bool SensorService::SensorEventAckReceiver::threadLoop() {
946 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700947 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700948 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700949 bool wakeLockAcquired = mService->isWakeLockAcquired();
950 int timeout = -1;
951 if (wakeLockAcquired) timeout = 5000;
952 int ret = looper->pollOnce(timeout);
953 if (ret == ALOOPER_POLL_TIMEOUT) {
954 mService->resetAllWakeLockRefCounts();
955 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700956 } while(!Thread::exitPending());
957 return false;
958}
959
Aravind Akella9a844cf2014-02-11 18:58:52 -0800960void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800961 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800962 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800963 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
964 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800965 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800966 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800967 }
Peng Xu2576cb62016-01-20 00:22:09 -0800968
Peng Xu6a2d3a02015-12-21 12:00:23 -0800969 auto logger = mRecentEvent.find(buffer[i].sensor);
970 if (logger != mRecentEvent.end()) {
971 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800972 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800973 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800974}
975
Peng Xu47e96012016-03-28 17:55:56 -0700976void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800977 struct compar {
978 static int cmp(void const* lhs, void const* rhs) {
979 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
980 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700981 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800982 }
983 };
984 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
985}
986
Mathias Agopian5d270722010-07-19 15:20:39 -0700987String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700988 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700989}
990
Aravind Akellab4099e72013-10-15 15:43:10 -0700991bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700992 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
993 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700994}
995
Aravind Akella9a844cf2014-02-11 18:58:52 -0800996bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700997 int handle = event.sensor;
998 if (event.type == SENSOR_TYPE_META_DATA) {
999 handle = event.meta_data.sensor;
1000 }
Peng Xu755c4512016-04-07 23:15:14 -07001001 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1002 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001003}
1004
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001005int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1006 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1007 // UUID is not supported for this device.
1008 return 0;
1009 }
1010 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1011 // This sensor can be uniquely identified in the system by
1012 // the combination of its type and name.
1013 return -1;
1014 }
1015
1016 // We have a dynamic sensor.
1017
1018 if (!sHmacGlobalKeyIsValid) {
1019 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1020 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1021 return 0;
1022 }
1023
1024 // We want each app author/publisher to get a different ID, so that the
1025 // same dynamic sensor cannot be tracked across apps by multiple
1026 // authors/publishers. So we use both our UUID and our User ID.
1027 // Note potential confusion:
1028 // UUID => Universally Unique Identifier.
1029 // UID => User Identifier.
1030 // We refrain from using "uid" except as needed by API to try to
1031 // keep this distinction clear.
1032
1033 auto appUserId = IPCThreadState::self()->getCallingUid();
1034 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1035 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1036 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1037
1038 // Now we use our key on our UUID/app combo to get the hash.
1039 uint8_t hash[EVP_MAX_MD_SIZE];
1040 unsigned int hashLen;
1041 if (HMAC(EVP_sha256(),
1042 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1043 uuidAndApp, sizeof(uuidAndApp),
1044 hash, &hashLen) == nullptr) {
1045 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1046 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1047 return 0;
1048 }
1049
1050 int32_t id = 0;
1051 if (hashLen < sizeof(id)) {
1052 // We never expect this case, but out of paranoia, we handle it.
1053 // Our 'id' length is already quite small, we don't want the
1054 // effective length of it to be even smaller.
1055 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1056 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1057 return 0;
1058 }
1059
1060 // This is almost certainly less than all of 'hash', but it's as secure
1061 // as we can be with our current 'id' length.
1062 memcpy(&id, hash, sizeof(id));
1063
1064 // Note at the beginning of the function that we return the values of
1065 // 0 and -1 to represent special cases. As a result, we can't return
1066 // those as dynamic sensor IDs. If we happened to hash to one of those
1067 // values, we change 'id' so we report as a dynamic sensor, and not as
1068 // one of those special cases.
1069 if (id == -1) {
1070 id = -2;
1071 } else if (id == 0) {
1072 id = 1;
1073 }
1074 return id;
1075}
1076
1077void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1078 for (auto &sensor : sensorList) {
1079 int32_t id = getIdFromUuid(sensor.getUuid());
1080 sensor.setId(id);
1081 }
1082}
1083
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001084Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001085 char value[PROPERTY_VALUE_MAX];
1086 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001087 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001088 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001089 Vector<Sensor> accessibleSensorList;
1090 for (size_t i = 0; i < initialSensorList.size(); i++) {
1091 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001092 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001093 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001094 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001095 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001096}
1097
Peng Xu47e96012016-03-28 17:55:56 -07001098Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001099 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001100 mSensors.forEachSensor(
1101 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001102 if (sensor.isDynamicSensor()) {
1103 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1104 accessibleSensorList.add(sensor);
1105 } else {
1106 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1107 sensor.getName().string(),
1108 sensor.getRequiredPermission().string(),
1109 sensor.getRequiredAppOp());
1110 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001111 }
1112 return true;
1113 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001114 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001115 return accessibleSensorList;
1116}
1117
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001118sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001119 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001120 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1121 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001122 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001123 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001124
1125 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001126 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1127 // operating in DI mode.
1128 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001129 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1130 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001131 }
1132
Mathias Agopian5307d172012-09-18 17:02:43 -07001133 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001134 pid_t pid = IPCThreadState::self()->getCallingPid();
1135
1136 String8 connPackageName =
1137 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1138 String16 connOpPackageName =
1139 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001140 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001141 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001142 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001143 if (requestedMode == DATA_INJECTION) {
1144 if (mActiveConnections.indexOf(result) < 0) {
1145 mActiveConnections.add(result);
1146 }
1147 // Add the associated file descriptor to the Looper for polling whenever there is data to
1148 // be injected.
1149 result->updateLooperRegistration(mLooper);
1150 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001151 return result;
1152}
1153
Aravind Akella841a5922015-06-29 12:37:48 -07001154int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001155 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001156 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001157}
1158
Peng Xue36e3472016-11-03 11:57:10 -07001159sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1160 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1161 const native_handle *resource) {
1162 Mutex::Autolock _l(mLock);
1163
Michael Groover5e1f60b2018-12-04 22:34:29 -08001164 // No new direct connections are allowed when sensor privacy is enabled
1165 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1166 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1167 return nullptr;
1168 }
1169
Peng Xue36e3472016-11-03 11:57:10 -07001170 struct sensors_direct_mem_t mem = {
1171 .type = type,
1172 .format = format,
1173 .size = size,
1174 .handle = resource,
1175 };
1176 uid_t uid = IPCThreadState::self()->getCallingUid();
1177
1178 if (mem.handle == nullptr) {
1179 ALOGE("Failed to clone resource handle");
1180 return nullptr;
1181 }
1182
1183 // check format
1184 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1185 ALOGE("Direct channel format %d is unsupported!", format);
1186 return nullptr;
1187 }
1188
1189 // check for duplication
1190 for (auto &i : mDirectConnections) {
1191 sp<SensorDirectConnection> connection(i.promote());
1192 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001193 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001194 return nullptr;
1195 }
1196 }
1197
1198 // check specific to memory type
1199 switch(type) {
1200 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001201 if (resource->numFds < 1) {
1202 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1203 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1204 return nullptr;
1205 }
Peng Xue36e3472016-11-03 11:57:10 -07001206 int fd = resource->data[0];
1207 int size2 = ashmem_get_size_region(fd);
1208 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001209 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001210 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1211 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001212 return nullptr;
1213 }
1214 break;
1215 }
1216 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001217 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001218 break;
1219 default:
1220 ALOGE("Unknown direct connection memory type %d", type);
1221 return nullptr;
1222 }
1223
1224 native_handle_t *clone = native_handle_clone(resource);
1225 if (!clone) {
1226 return nullptr;
1227 }
1228
1229 SensorDirectConnection* conn = nullptr;
1230 SensorDevice& dev(SensorDevice::getInstance());
1231 int channelHandle = dev.registerDirectChannel(&mem);
1232
1233 if (channelHandle <= 0) {
1234 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1235 } else {
1236 mem.handle = clone;
1237 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1238 }
1239
1240 if (conn == nullptr) {
1241 native_handle_close(clone);
1242 native_handle_delete(clone);
1243 } else {
1244 // add to list of direct connections
1245 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1246 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1247 }
1248 return conn;
1249}
1250
Peng Xudd5c5cb2017-03-16 17:39:43 -07001251int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001252 int32_t handle, int32_t type,
1253 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001254 Mutex::Autolock _l(mLock);
1255
Alexey Polyudov88711e82017-05-23 19:54:04 -07001256 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001257 return PERMISSION_DENIED;
1258 }
1259
1260 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001261 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001262 size_t expectSize = INT32_MAX;
1263 switch (type) {
1264 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1265 isFloat = true;
1266 expectSize = 3;
1267 break;
1268 case AINFO_LOCAL_GRAVITY:
1269 isFloat = true;
1270 expectSize = 1;
1271 break;
1272 case AINFO_DOCK_STATE:
1273 case AINFO_HIGH_PERFORMANCE_MODE:
1274 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1275 isFloat = false;
1276 expectSize = 1;
1277 break;
1278 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001279 // CUSTOM events must only contain float data; it may have variable size
1280 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1281 ints.size() ||
1282 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1283 handle < 0) {
1284 return BAD_VALUE;
1285 }
1286 isFloat = true;
1287 isCustom = true;
1288 expectSize = floats.size();
1289 break;
1290 }
1291
1292 if (!isCustom && handle != -1) {
1293 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001294 }
1295
1296 // three events: first one is begin tag, last one is end tag, the one in the middle
1297 // is the payload.
1298 sensors_event_t event[3];
1299 int64_t timestamp = elapsedRealtimeNano();
1300 for (sensors_event_t* i = event; i < event + 3; i++) {
1301 *i = (sensors_event_t) {
1302 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001303 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001304 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1305 .timestamp = timestamp++,
1306 .additional_info = (additional_info_event_t) {
1307 .serial = 0
1308 }
1309 };
1310 }
1311
1312 event[0].additional_info.type = AINFO_BEGIN;
1313 event[1].additional_info.type = type;
1314 event[2].additional_info.type = AINFO_END;
1315
1316 if (isFloat) {
1317 if (floats.size() != expectSize) {
1318 return BAD_VALUE;
1319 }
1320 for (size_t i = 0; i < expectSize; ++i) {
1321 event[1].additional_info.data_float[i] = floats[i];
1322 }
1323 } else {
1324 if (ints.size() != expectSize) {
1325 return BAD_VALUE;
1326 }
1327 for (size_t i = 0; i < expectSize; ++i) {
1328 event[1].additional_info.data_int32[i] = ints[i];
1329 }
1330 }
1331
1332 SensorDevice& dev(SensorDevice::getInstance());
1333 for (sensors_event_t* i = event; i < event + 3; i++) {
1334 int ret = dev.injectSensorData(i);
1335 if (ret != NO_ERROR) {
1336 return ret;
1337 }
1338 }
1339 return NO_ERROR;
1340}
1341
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001342status_t SensorService::resetToNormalMode() {
1343 Mutex::Autolock _l(mLock);
1344 return resetToNormalModeLocked();
1345}
1346
1347status_t SensorService::resetToNormalModeLocked() {
1348 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001349 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301350 if (err == NO_ERROR) {
1351 mCurrentOperatingMode = NORMAL;
1352 dev.enableAllSensors();
1353 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001354 return err;
1355}
1356
Peng Xu47e96012016-03-28 17:55:56 -07001357void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001358 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001359 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001360 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001361 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001362 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001363 int handle = mActiveSensors.keyAt(i);
1364 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001365 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001366 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1367 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001368 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001369 } else {
1370 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001371 }
Aravind Akella8a969552014-09-28 17:52:41 -07001372 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001373 }
1374 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001375 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001376 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001377 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001378 c, i, handle);
1379
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001380 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001381 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001382 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001383 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001384 delete rec;
1385 size--;
1386 } else {
1387 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001388 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001389 }
Aravind Akella8a969552014-09-28 17:52:41 -07001390 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001391 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001392 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001393 if (c->needsWakeLock()) {
1394 checkWakeLockStateLocked();
1395 }
Peng Xu4f707f82016-09-26 11:28:32 -07001396
1397 SensorDevice& dev(SensorDevice::getInstance());
1398 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001399}
1400
Peng Xue36e3472016-11-03 11:57:10 -07001401void SensorService::cleanupConnection(SensorDirectConnection* c) {
1402 Mutex::Autolock _l(mLock);
1403
1404 SensorDevice& dev(SensorDevice::getInstance());
1405 dev.unregisterDirectChannel(c->getHalChannelHandle());
1406 mDirectConnections.remove(c);
1407}
1408
Peng Xu755c4512016-04-07 23:15:14 -07001409sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001410 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001411}
1412
Mathias Agopianfc328812010-07-14 23:41:37 -07001413status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001414 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001415 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001416 if (mInitCheck != NO_ERROR)
1417 return mInitCheck;
1418
Peng Xu755c4512016-04-07 23:15:14 -07001419 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1420 if (sensor == nullptr ||
1421 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001422 return BAD_VALUE;
1423 }
1424
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001425 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001426 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001427 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001428 return INVALID_OPERATION;
1429 }
1430
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001431 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001432 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001433 rec = new SensorRecord(connection);
1434 mActiveSensors.add(handle, rec);
1435 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001436 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001437 }
Brian Stack26029ee2019-04-22 17:25:49 -07001438
1439 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1440 // the recent event as stale to ensure that the previous event is not sent to a client. This
1441 // ensures on-change events that were generated during a previous sensor activation are not
1442 // erroneously sent to newly connected clients, especially if a second client registers for
1443 // an on-change sensor before the first client receives the updated event. Once an updated
1444 // event is received, the recent events will be marked as current, and any new clients will
1445 // immediately receive the most recent event.
1446 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1447 auto logger = mRecentEvent.find(handle);
1448 if (logger != mRecentEvent.end()) {
1449 logger->second->setLastEventStale();
1450 }
1451 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001452 } else {
1453 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001454 // this sensor is already activated, but we are adding a connection that uses it.
1455 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001456 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001457 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001458 // NOTE: The wake_up flag of this event may get set to
1459 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001460
1461 auto logger = mRecentEvent.find(handle);
1462 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001463 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001464 // Verify that the last sensor event was generated from the current activation
1465 // of the sensor. If not, it is possible for an on-change sensor to receive a
1466 // sensor event that is stale if two clients re-activate the sensor
1467 // simultaneously.
1468 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001469 event.sensor = handle;
1470 if (event.version == sizeof(sensors_event_t)) {
1471 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1472 setWakeLockAcquiredLocked(true);
1473 }
Yi Kong8f313e32018-07-17 14:13:29 -07001474 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001475 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1476 checkWakeLockStateLocked();
1477 }
1478 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001479 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001480 }
1481 }
1482 }
1483 }
1484
1485 if (connection->addSensor(handle)) {
1486 BatteryService::enableSensor(connection->getUid(), handle);
1487 // the sensor was added (which means it wasn't already there)
1488 // so, see if this connection becomes active
1489 if (mActiveConnections.indexOf(connection) < 0) {
1490 mActiveConnections.add(connection);
1491 }
1492 } else {
1493 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1494 handle, connection.get());
1495 }
1496
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301497 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001498 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301499 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1500 samplingPeriodNs = maxDelayNs;
1501 }
1502
Aravind Akella724d91d2013-06-27 12:04:23 -07001503 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1504 if (samplingPeriodNs < minDelayNs) {
1505 samplingPeriodNs = minDelayNs;
1506 }
1507
Aravind Akella6c2664a2014-08-13 12:24:50 -07001508 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1509 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001510 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1511
Aravind Akella4949c502015-02-11 15:54:35 -08001512 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001513 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001514
Peng Xu20483c42015-10-26 15:14:43 -07001515 // Call flush() before calling activate() on the sensor. Wait for a first
1516 // flush complete event before sending events on this connection. Ignore
1517 // one-shot sensors which don't support flush(). Ignore on-change sensors
1518 // to maintain the on-change logic (any on-change events except the initial
1519 // one should be trigger by a change in value). Also if this sensor isn't
1520 // already active, don't call flush().
1521 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001522 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001523 rec->getNumConnections() > 1) {
1524 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001525 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001526 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001527 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001528 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001529 } else {
1530 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001531 }
1532 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001533
1534 if (err == NO_ERROR) {
1535 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1536 err = sensor->activate(connection.get(), true);
1537 }
1538
Aravind Akella8a969552014-09-28 17:52:41 -07001539 if (err == NO_ERROR) {
1540 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001541
1542 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1543 SensorRegistrationInfo(handle, connection->getPackageName(),
1544 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001545 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001546 }
1547
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001548 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001549 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001550 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001551 }
1552 return err;
1553}
1554
Peng Xu47e96012016-03-28 17:55:56 -07001555status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001556 if (mInitCheck != NO_ERROR)
1557 return mInitCheck;
1558
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001559 Mutex::Autolock _l(mLock);
1560 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001561 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001562 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1563 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001564
1565 }
1566 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001567 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1568 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001569 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001570 }
1571 return err;
1572}
1573
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001574status_t SensorService::cleanupWithoutDisable(
1575 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001576 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001577 return cleanupWithoutDisableLocked(connection, handle);
1578}
1579
1580status_t SensorService::cleanupWithoutDisableLocked(
1581 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001582 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001583 if (rec) {
1584 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001585 if (connection->removeSensor(handle)) {
1586 BatteryService::disableSensor(connection->getUid(), handle);
1587 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001588 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001589 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001590 mActiveConnections.remove(connection);
1591 }
1592 // see if this sensor becomes inactive
1593 if (rec->removeConnection(connection)) {
1594 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001595 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001596 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001597 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001598 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001599 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001600 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001601}
1602
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001603status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001604 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001605 if (mInitCheck != NO_ERROR)
1606 return mInitCheck;
1607
Peng Xu755c4512016-04-07 23:15:14 -07001608 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1609 if (sensor == nullptr ||
1610 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001611 return BAD_VALUE;
1612 }
1613
Mathias Agopian1cd70002010-07-21 15:59:50 -07001614 if (ns < 0)
1615 return BAD_VALUE;
1616
Mathias Agopian62569ec2011-11-07 21:21:47 -08001617 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1618 if (ns < minDelayNs) {
1619 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001620 }
1621
Mathias Agopianf001c922010-11-11 17:58:51 -08001622 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001623}
1624
Svetoslavb412f6e2015-04-29 16:50:41 -07001625status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1626 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001627 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001628 SensorDevice& dev(SensorDevice::getInstance());
1629 const int halVersion = dev.getHalDeviceVersion();
1630 status_t err(NO_ERROR);
1631 Mutex::Autolock _l(mLock);
1632 // Loop through all sensors for this connection and call flush on each of them.
1633 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1634 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001635 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1636 if (sensor == nullptr) {
1637 continue;
1638 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001639 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1640 ALOGE("flush called on a one-shot sensor");
1641 err = INVALID_OPERATION;
1642 continue;
1643 }
Aravind Akella8493b792014-09-08 15:45:47 -07001644 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001645 // For older devices just increment pending flush count which will send a trivial
1646 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001647 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001648 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001649 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1650 err = INVALID_OPERATION;
1651 continue;
1652 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001653 status_t err_flush = sensor->flush(connection.get(), handle);
1654 if (err_flush == NO_ERROR) {
1655 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001656 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001657 }
1658 err = (err_flush != NO_ERROR) ? err_flush : err;
1659 }
Aravind Akella70018042014-04-07 22:52:37 +00001660 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001661 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001662}
Aravind Akella70018042014-04-07 22:52:37 +00001663
Svetoslavb412f6e2015-04-29 16:50:41 -07001664bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1665 const String16& opPackageName) {
1666 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001667
Svetoslavb412f6e2015-04-29 16:50:41 -07001668 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001669 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001670 }
1671
1672 bool hasPermission = false;
1673
1674 // Runtime permissions can't use the cache as they may change.
1675 if (sensor.isRequiredPermissionRuntime()) {
1676 hasPermission = checkPermission(String16(requiredPermission),
1677 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001678 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001679 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1680 }
1681
1682 if (!hasPermission) {
1683 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1684 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001685 return false;
1686 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001687
1688 const int32_t opCode = sensor.getRequiredAppOp();
1689 if (opCode >= 0) {
1690 AppOpsManager appOps;
1691 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1692 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001693 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001694 operation, sensor.getName().string(), opCode);
1695 return false;
1696 }
1697 }
1698
1699 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001700}
1701
Aravind Akella9a844cf2014-02-11 18:58:52 -08001702void SensorService::checkWakeLockState() {
1703 Mutex::Autolock _l(mLock);
1704 checkWakeLockStateLocked();
1705}
1706
1707void SensorService::checkWakeLockStateLocked() {
1708 if (!mWakeLockAcquired) {
1709 return;
1710 }
1711 bool releaseLock = true;
1712 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1713 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001714 if (connection != nullptr) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001715 if (connection->needsWakeLock()) {
1716 releaseLock = false;
1717 break;
1718 }
1719 }
1720 }
1721 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001722 setWakeLockAcquiredLocked(false);
1723 }
1724}
1725
1726void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1727 Mutex::Autolock _l(mLock);
1728 connection->writeToSocketFromCache();
1729 if (connection->needsWakeLock()) {
1730 setWakeLockAcquiredLocked(true);
1731 }
1732}
1733
1734void SensorService::populateActiveConnections(
1735 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1736 Mutex::Autolock _l(mLock);
1737 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1738 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001739 if (connection != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001740 activeConnections->add(connection);
1741 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001742 }
1743}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001744
Aravind Akella4949c502015-02-11 15:54:35 -08001745bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001746 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001747}
1748
Brian Stack5180e462019-03-08 17:15:19 -08001749bool SensorService::isOperationPermitted(const String16& opPackageName) {
Peng Xue36e3472016-11-03 11:57:10 -07001750 Mutex::Autolock _l(mLock);
Brian Stack5180e462019-03-08 17:15:19 -08001751 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001752 String8 package(opPackageName);
Brian Stack5180e462019-03-08 17:15:19 -08001753 return isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001754 }
Brian Stack5180e462019-03-08 17:15:19 -08001755 return true;
Peng Xue36e3472016-11-03 11:57:10 -07001756}
1757
Svet Ganove752a5c2018-01-15 17:14:20 -08001758void SensorService::UidPolicy::registerSelf() {
1759 ActivityManager am;
1760 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1761 | ActivityManager::UID_OBSERVER_IDLE
1762 | ActivityManager::UID_OBSERVER_ACTIVE,
1763 ActivityManager::PROCESS_STATE_UNKNOWN,
1764 String16("android"));
1765}
1766
1767void SensorService::UidPolicy::unregisterSelf() {
1768 ActivityManager am;
1769 am.unregisterUidObserver(this);
1770}
1771
1772void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1773 onUidIdle(uid, disabled);
1774}
1775
1776void SensorService::UidPolicy::onUidActive(uid_t uid) {
1777 {
1778 Mutex::Autolock _l(mUidLock);
1779 mActiveUids.insert(uid);
1780 }
1781 sp<SensorService> service = mService.promote();
1782 if (service != nullptr) {
1783 service->setSensorAccess(uid, true);
1784 }
1785}
1786
1787void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1788 bool deleted = false;
1789 {
1790 Mutex::Autolock _l(mUidLock);
1791 if (mActiveUids.erase(uid) > 0) {
1792 deleted = true;
1793 }
1794 }
1795 if (deleted) {
1796 sp<SensorService> service = mService.promote();
1797 if (service != nullptr) {
1798 service->setSensorAccess(uid, false);
1799 }
1800 }
1801}
1802
1803void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1804 updateOverrideUid(uid, active, true);
1805}
1806
1807void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1808 updateOverrideUid(uid, false, false);
1809}
1810
1811void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1812 bool wasActive = false;
1813 bool isActive = false;
1814 {
1815 Mutex::Autolock _l(mUidLock);
1816 wasActive = isUidActiveLocked(uid);
1817 mOverrideUids.erase(uid);
1818 if (insert) {
1819 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1820 }
1821 isActive = isUidActiveLocked(uid);
1822 }
1823 if (wasActive != isActive) {
1824 sp<SensorService> service = mService.promote();
1825 if (service != nullptr) {
1826 service->setSensorAccess(uid, isActive);
1827 }
1828 }
1829}
1830
1831bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1832 // Non-app UIDs are considered always active
1833 if (uid < FIRST_APPLICATION_UID) {
1834 return true;
1835 }
1836 Mutex::Autolock _l(mUidLock);
1837 return isUidActiveLocked(uid);
1838}
1839
1840bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1841 // Non-app UIDs are considered always active
1842 if (uid < FIRST_APPLICATION_UID) {
1843 return true;
1844 }
1845 auto it = mOverrideUids.find(uid);
1846 if (it != mOverrideUids.end()) {
1847 return it->second;
1848 }
1849 return mActiveUids.find(uid) != mActiveUids.end();
1850}
1851
Michael Groover5e1f60b2018-12-04 22:34:29 -08001852void SensorService::SensorPrivacyPolicy::registerSelf() {
1853 SensorPrivacyManager spm;
1854 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1855 spm.addSensorPrivacyListener(this);
1856}
1857
1858void SensorService::SensorPrivacyPolicy::unregisterSelf() {
1859 SensorPrivacyManager spm;
1860 spm.removeSensorPrivacyListener(this);
1861}
1862
1863bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1864 return mSensorPrivacyEnabled;
1865}
1866
1867binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1868 mSensorPrivacyEnabled = enabled;
1869 sp<SensorService> service = mService.promote();
1870 if (service != nullptr) {
1871 if (enabled) {
1872 service->disableAllSensors();
1873 } else {
1874 service->enableAllSensors();
1875 }
1876 }
1877 return binder::Status::ok();
1878}
Mathias Agopianfc328812010-07-14 23:41:37 -07001879}; // namespace android