blob: 9a37ff1902689261dc149a0edf3ef8a03c26376d [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");
444 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
445 int handle = mActiveSensors.keyAt(i);
446 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
447 getSensorName(handle).string(),
448 handle,
449 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700450 }
451
Andreas Gamped4036b62015-07-28 13:49:04 -0700452 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700453 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700454 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
455 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700456 result.appendFormat("Mode :");
457 switch(mCurrentOperatingMode) {
458 case NORMAL:
459 result.appendFormat(" NORMAL\n");
460 break;
461 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700462 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700463 break;
464 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700465 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700466 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800467 result.appendFormat("Sensor Privacy: %s\n",
468 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700469
Peng Xue36e3472016-11-03 11:57:10 -0700470 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella444f2672015-05-07 12:40:52 -0700471 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
472 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -0700473 if (connection != nullptr) {
Aravind Akella444f2672015-05-07 12:40:52 -0700474 result.appendFormat("Connection Number: %zu \n", i);
475 connection->dump(result);
476 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700477 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700478
Peng Xue36e3472016-11-03 11:57:10 -0700479 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
480 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
481 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
482 if (connection != nullptr) {
483 result.appendFormat("Direct connection %zu:\n", i);
484 connection->dump(result);
485 }
486 }
487
Aravind Akella18d6d512015-06-18 14:18:28 -0700488 result.appendFormat("Previous Registrations:\n");
489 // Log in the reverse chronological order.
490 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
491 SENSOR_REGISTRATIONS_BUF_SIZE;
492 const int startIndex = currentIndex;
493 do {
494 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
495 if (SensorRegistrationInfo::isSentinel(reg_info)) {
496 // Ignore sentinel, proceed to next item.
497 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
498 SENSOR_REGISTRATIONS_BUF_SIZE;
499 continue;
500 }
Peng Xu51224682017-03-10 16:57:27 -0800501 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700502 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
503 SENSOR_REGISTRATIONS_BUF_SIZE;
504 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700505 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700506 }
507 write(fd, result.string(), result.size());
508 return NO_ERROR;
509}
510
Michael Groover5e1f60b2018-12-04 22:34:29 -0800511void SensorService::disableAllSensors() {
512 Mutex::Autolock _l(mLock);
513 disableAllSensorsLocked();
514}
515
516void SensorService::disableAllSensorsLocked() {
517 SensorDevice& dev(SensorDevice::getInstance());
518 for (auto &i : mDirectConnections) {
519 sp<SensorDirectConnection> connection(i.promote());
520 if (connection != nullptr) {
521 connection->stopAll(true /* backupRecord */);
522 }
523 }
524 dev.disableAllSensors();
525 // Clear all pending flush connections for all active sensors. If one of the active
526 // connections has called flush() and the underlying sensor has been disabled before a
527 // flush complete event is returned, we need to remove the connection from this queue.
528 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
529 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
530 }
531}
532
533void SensorService::enableAllSensors() {
534 Mutex::Autolock _l(mLock);
535 enableAllSensorsLocked();
536}
537
538void SensorService::enableAllSensorsLocked() {
539 // sensors should only be enabled if the operating state is not restricted and sensor
540 // privacy is not enabled.
541 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
542 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
543 mCurrentOperatingMode,
544 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
545 return;
546 }
547 SensorDevice& dev(SensorDevice::getInstance());
548 dev.enableAllSensors();
549 for (auto &i : mDirectConnections) {
550 sp<SensorDirectConnection> connection(i.promote());
551 if (connection != nullptr) {
552 connection->recoverAll();
553 }
554 }
555}
556
Svet Ganove752a5c2018-01-15 17:14:20 -0800557// NOTE: This is a remote API - make sure all args are validated
558status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
559 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
560 return PERMISSION_DENIED;
561 }
562 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
563 return BAD_VALUE;
564 }
565 if (args.size() == 3 && args[0] == String16("set-uid-state")) {
566 return handleSetUidState(args, err);
567 } else if (args.size() == 2 && args[0] == String16("reset-uid-state")) {
568 return handleResetUidState(args, err);
569 } else if (args.size() == 2 && args[0] == String16("get-uid-state")) {
570 return handleGetUidState(args, out, err);
571 } else if (args.size() == 1 && args[0] == String16("help")) {
572 printHelp(out);
573 return NO_ERROR;
574 }
575 printHelp(err);
576 return BAD_VALUE;
577}
578
579status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
580 PermissionController pc;
581 int uid = pc.getPackageUid(args[1], 0);
582 if (uid <= 0) {
583 ALOGE("Unknown package: '%s'", String8(args[1]).string());
584 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
585 return BAD_VALUE;
586 }
587 bool active = false;
588 if (args[2] == String16("active")) {
589 active = true;
590 } else if ((args[2] != String16("idle"))) {
591 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
592 return BAD_VALUE;
593 }
594 mUidPolicy->addOverrideUid(uid, active);
595 return NO_ERROR;
596}
597
598status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
599 PermissionController pc;
600 int uid = pc.getPackageUid(args[1], 0);
601 if (uid < 0) {
602 ALOGE("Unknown package: '%s'", String8(args[1]).string());
603 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
604 return BAD_VALUE;
605 }
606 mUidPolicy->removeOverrideUid(uid);
607 return NO_ERROR;
608}
609
610status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
611 PermissionController pc;
612 int uid = pc.getPackageUid(args[1], 0);
613 if (uid < 0) {
614 ALOGE("Unknown package: '%s'", String8(args[1]).string());
615 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
616 return BAD_VALUE;
617 }
618 if (mUidPolicy->isUidActive(uid)) {
619 return dprintf(out, "active\n");
620 } else {
621 return dprintf(out, "idle\n");
622 }
623}
624
625status_t SensorService::printHelp(int out) {
626 return dprintf(out, "Sensor service commands:\n"
627 " get-uid-state <PACKAGE> gets the uid state\n"
628 " set-uid-state <PACKAGE> <active|idle> overrides the uid state\n"
629 " reset-uid-state <PACKAGE> clears the uid state override\n"
630 " help print this message\n");
631}
632
Peng Xu0cc8f802016-04-05 23:46:03 -0700633//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800634void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700635 sensors_event_t const* buffer, const int count) {
636 for (int i=0 ; i<count ; i++) {
637 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700638 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
639 handle = buffer[i].meta_data.sensor;
640 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700641 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700642 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700643 // If this buffer has an event from a one_shot sensor and this connection is registered
644 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700645 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700646 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
647 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800648 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700649 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700650
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700651 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700652 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700653}
654
Peng Xu47e96012016-03-28 17:55:56 -0700655bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000656 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700657
Peng Xueb4d6282015-12-10 18:02:41 -0800658 // each virtual sensor could generate an event per "real" event, that's why we need to size
659 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
660 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700661 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700662 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700663 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700664
Mathias Agopianf001c922010-11-11 17:58:51 -0800665 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700666
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700667 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700668 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700669 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
670 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700671 if(count == DEAD_OBJECT && device.isReconnecting()) {
672 device.reconnect();
673 continue;
674 } else {
675 ALOGE("sensor poll failed (%s)", strerror(-count));
676 break;
677 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700678 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700679
680 // Reset sensors_event_t.flags to zero for all events in the buffer.
681 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700682 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700683 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700684
Peng Xueb4d6282015-12-10 18:02:41 -0800685 // Make a copy of the connection vector as some connections may be removed during the course
686 // of this loop (especially when one-shot sensor events are present in the sensor_event
687 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
688 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
689 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
690 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700691 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700692 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800693
Aravind Akella9a844cf2014-02-11 18:58:52 -0800694 Mutex::Autolock _l(mLock);
695 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
696 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
697 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
698 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
699 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700700 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700701 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700702 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700703 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700704 }
705 }
706
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700707 if (wakeEvents > 0) {
708 if (!mWakeLockAcquired) {
709 setWakeLockAcquiredLocked(true);
710 }
711 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800712 }
Aravind Akella8493b792014-09-08 15:45:47 -0700713 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800714
Mathias Agopianf001c922010-11-11 17:58:51 -0800715 // handle virtual sensors
716 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700717 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700718 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800719 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700720 SensorFusion& fusion(SensorFusion::getInstance());
721 if (fusion.isEnabled()) {
722 for (size_t i=0 ; i<size_t(count) ; i++) {
723 fusion.process(event[i]);
724 }
725 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700726 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700727 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700728 if (count + k >= minBufferSize) {
729 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700730 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700731 count, k, minBufferSize);
732 break;
733 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800734 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700735 sp<SensorInterface> si = mSensors.getInterface(handle);
736 if (si == nullptr) {
737 ALOGE("handle %d is not an valid virtual sensor", handle);
738 continue;
739 }
740
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700741 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700742 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800743 k++;
744 }
745 }
746 }
747 if (k) {
748 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700749 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800750 count += k;
751 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700752 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700753 }
754 }
755 }
756
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700757 // handle backward compatibility for RotationVector sensor
758 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
759 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700760 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700761 // All the 4 components of the quaternion should be available
762 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700763 mSensorEventBuffer[i].data[4] = -1;
764 }
765 }
766 }
767
Aravind Akella8493b792014-09-08 15:45:47 -0700768 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700769 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
770 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
771 // SensorEventConnection mapped to the corresponding flush_complete_event in
772 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700773 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700774 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
775 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
776 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700777 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700778 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
779 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700780 }
781 }
Peng Xu2576cb62016-01-20 00:22:09 -0800782
783 // handle dynamic sensor meta events, process registration and unregistration of dynamic
784 // sensor based on content of event.
785 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
786 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
787 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
788 const sensor_t& dynamicSensor =
789 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
790 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
791 handle, dynamicSensor.type, dynamicSensor.name);
792
Peng Xu0cc8f802016-04-05 23:46:03 -0700793 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800794 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700795 sensor_t s = dynamicSensor;
796 // make sure the dynamic sensor flag is set
797 s.flags |= DYNAMIC_SENSOR_MASK;
798 // force the handle to be consistent
799 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800800
801 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800802
Peng Xu0cc8f802016-04-05 23:46:03 -0700803 // This will release hold on dynamic sensor meta, so it should be called
804 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700805 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800806 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700807 } else {
808 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
809 }
Peng Xu2576cb62016-01-20 00:22:09 -0800810 } else {
811 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
812 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
813
814 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800815 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800816 ALOGE("Dynamic sensor release error.");
817 }
818
819 size_t numConnections = activeConnections.size();
820 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700821 if (activeConnections[i] != nullptr) {
Peng Xu2576cb62016-01-20 00:22:09 -0800822 activeConnections[i]->removeSensor(handle);
823 }
824 }
825 }
826 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700827 }
828
Aravind Akella9a844cf2014-02-11 18:58:52 -0800829 // Send our events to clients. Check the state of wake lock for each client and release the
830 // lock if none of the clients need it.
831 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700832 size_t numConnections = activeConnections.size();
833 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700834 if (activeConnections[i] != nullptr) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700835 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700836 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700837 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700838 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
839 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700840 if (activeConnections[i]->hasOneShotSensors()) {
841 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
842 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700843 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800844 }
845 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700846
Aravind Akella9a844cf2014-02-11 18:58:52 -0800847 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700848 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800849 }
Aravind Akella8493b792014-09-08 15:45:47 -0700850 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700851
Steve Block3c20fbe2012-01-05 23:22:43 +0000852 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800853 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700854 return false;
855}
856
Aravind Akella56ae4262014-07-10 16:01:10 -0700857sp<Looper> SensorService::getLooper() const {
858 return mLooper;
859}
860
Aravind Akellab4373ac2014-10-29 17:55:20 -0700861void SensorService::resetAllWakeLockRefCounts() {
862 SortedVector< sp<SensorEventConnection> > activeConnections;
863 populateActiveConnections(&activeConnections);
864 {
865 Mutex::Autolock _l(mLock);
866 for (size_t i=0 ; i < activeConnections.size(); ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700867 if (activeConnections[i] != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700868 activeConnections[i]->resetWakeLockRefCount();
869 }
870 }
871 setWakeLockAcquiredLocked(false);
872 }
873}
874
875void SensorService::setWakeLockAcquiredLocked(bool acquire) {
876 if (acquire) {
877 if (!mWakeLockAcquired) {
878 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
879 mWakeLockAcquired = true;
880 }
881 mLooper->wake();
882 } else {
883 if (mWakeLockAcquired) {
884 release_wake_lock(WAKE_LOCK_NAME);
885 mWakeLockAcquired = false;
886 }
887 }
888}
889
Aravind Akellab4373ac2014-10-29 17:55:20 -0700890bool SensorService::isWakeLockAcquired() {
891 Mutex::Autolock _l(mLock);
892 return mWakeLockAcquired;
893}
894
Aravind Akella56ae4262014-07-10 16:01:10 -0700895bool SensorService::SensorEventAckReceiver::threadLoop() {
896 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700897 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700898 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700899 bool wakeLockAcquired = mService->isWakeLockAcquired();
900 int timeout = -1;
901 if (wakeLockAcquired) timeout = 5000;
902 int ret = looper->pollOnce(timeout);
903 if (ret == ALOOPER_POLL_TIMEOUT) {
904 mService->resetAllWakeLockRefCounts();
905 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700906 } while(!Thread::exitPending());
907 return false;
908}
909
Aravind Akella9a844cf2014-02-11 18:58:52 -0800910void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800911 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800912 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800913 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
914 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800915 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800916 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800917 }
Peng Xu2576cb62016-01-20 00:22:09 -0800918
Peng Xu6a2d3a02015-12-21 12:00:23 -0800919 auto logger = mRecentEvent.find(buffer[i].sensor);
920 if (logger != mRecentEvent.end()) {
921 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800922 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800923 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800924}
925
Peng Xu47e96012016-03-28 17:55:56 -0700926void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800927 struct compar {
928 static int cmp(void const* lhs, void const* rhs) {
929 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
930 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700931 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800932 }
933 };
934 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
935}
936
Mathias Agopian5d270722010-07-19 15:20:39 -0700937String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700938 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700939}
940
Aravind Akellab4099e72013-10-15 15:43:10 -0700941bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700942 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
943 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700944}
945
Aravind Akella9a844cf2014-02-11 18:58:52 -0800946bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700947 int handle = event.sensor;
948 if (event.type == SENSOR_TYPE_META_DATA) {
949 handle = event.meta_data.sensor;
950 }
Peng Xu755c4512016-04-07 23:15:14 -0700951 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
952 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800953}
954
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700955int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
956 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
957 // UUID is not supported for this device.
958 return 0;
959 }
960 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
961 // This sensor can be uniquely identified in the system by
962 // the combination of its type and name.
963 return -1;
964 }
965
966 // We have a dynamic sensor.
967
968 if (!sHmacGlobalKeyIsValid) {
969 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
970 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
971 return 0;
972 }
973
974 // We want each app author/publisher to get a different ID, so that the
975 // same dynamic sensor cannot be tracked across apps by multiple
976 // authors/publishers. So we use both our UUID and our User ID.
977 // Note potential confusion:
978 // UUID => Universally Unique Identifier.
979 // UID => User Identifier.
980 // We refrain from using "uid" except as needed by API to try to
981 // keep this distinction clear.
982
983 auto appUserId = IPCThreadState::self()->getCallingUid();
984 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
985 memcpy(uuidAndApp, &uuid, sizeof(uuid));
986 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
987
988 // Now we use our key on our UUID/app combo to get the hash.
989 uint8_t hash[EVP_MAX_MD_SIZE];
990 unsigned int hashLen;
991 if (HMAC(EVP_sha256(),
992 sHmacGlobalKey, sizeof(sHmacGlobalKey),
993 uuidAndApp, sizeof(uuidAndApp),
994 hash, &hashLen) == nullptr) {
995 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
996 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
997 return 0;
998 }
999
1000 int32_t id = 0;
1001 if (hashLen < sizeof(id)) {
1002 // We never expect this case, but out of paranoia, we handle it.
1003 // Our 'id' length is already quite small, we don't want the
1004 // effective length of it to be even smaller.
1005 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1006 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1007 return 0;
1008 }
1009
1010 // This is almost certainly less than all of 'hash', but it's as secure
1011 // as we can be with our current 'id' length.
1012 memcpy(&id, hash, sizeof(id));
1013
1014 // Note at the beginning of the function that we return the values of
1015 // 0 and -1 to represent special cases. As a result, we can't return
1016 // those as dynamic sensor IDs. If we happened to hash to one of those
1017 // values, we change 'id' so we report as a dynamic sensor, and not as
1018 // one of those special cases.
1019 if (id == -1) {
1020 id = -2;
1021 } else if (id == 0) {
1022 id = 1;
1023 }
1024 return id;
1025}
1026
1027void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1028 for (auto &sensor : sensorList) {
1029 int32_t id = getIdFromUuid(sensor.getUuid());
1030 sensor.setId(id);
1031 }
1032}
1033
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001034Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001035 char value[PROPERTY_VALUE_MAX];
1036 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001037 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001038 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001039 Vector<Sensor> accessibleSensorList;
1040 for (size_t i = 0; i < initialSensorList.size(); i++) {
1041 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001042 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001043 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001044 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001045 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001046}
1047
Peng Xu47e96012016-03-28 17:55:56 -07001048Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001049 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001050 mSensors.forEachSensor(
1051 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001052 if (sensor.isDynamicSensor()) {
1053 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1054 accessibleSensorList.add(sensor);
1055 } else {
1056 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1057 sensor.getName().string(),
1058 sensor.getRequiredPermission().string(),
1059 sensor.getRequiredAppOp());
1060 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001061 }
1062 return true;
1063 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001064 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001065 return accessibleSensorList;
1066}
1067
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001068sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001069 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001070 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1071 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001072 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001073 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001074
1075 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001076 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1077 // operating in DI mode.
1078 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001079 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1080 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001081 }
1082
Mathias Agopian5307d172012-09-18 17:02:43 -07001083 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001084 pid_t pid = IPCThreadState::self()->getCallingPid();
1085
1086 String8 connPackageName =
1087 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1088 String16 connOpPackageName =
1089 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001090 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001091 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001092 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001093 if (requestedMode == DATA_INJECTION) {
1094 if (mActiveConnections.indexOf(result) < 0) {
1095 mActiveConnections.add(result);
1096 }
1097 // Add the associated file descriptor to the Looper for polling whenever there is data to
1098 // be injected.
1099 result->updateLooperRegistration(mLooper);
1100 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001101 return result;
1102}
1103
Aravind Akella841a5922015-06-29 12:37:48 -07001104int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001105 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001106 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001107}
1108
Peng Xue36e3472016-11-03 11:57:10 -07001109sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1110 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1111 const native_handle *resource) {
1112 Mutex::Autolock _l(mLock);
1113
Michael Groover5e1f60b2018-12-04 22:34:29 -08001114 // No new direct connections are allowed when sensor privacy is enabled
1115 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1116 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1117 return nullptr;
1118 }
1119
Peng Xue36e3472016-11-03 11:57:10 -07001120 struct sensors_direct_mem_t mem = {
1121 .type = type,
1122 .format = format,
1123 .size = size,
1124 .handle = resource,
1125 };
1126 uid_t uid = IPCThreadState::self()->getCallingUid();
1127
1128 if (mem.handle == nullptr) {
1129 ALOGE("Failed to clone resource handle");
1130 return nullptr;
1131 }
1132
1133 // check format
1134 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1135 ALOGE("Direct channel format %d is unsupported!", format);
1136 return nullptr;
1137 }
1138
1139 // check for duplication
1140 for (auto &i : mDirectConnections) {
1141 sp<SensorDirectConnection> connection(i.promote());
1142 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001143 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001144 return nullptr;
1145 }
1146 }
1147
1148 // check specific to memory type
1149 switch(type) {
1150 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001151 if (resource->numFds < 1) {
1152 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1153 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1154 return nullptr;
1155 }
Peng Xue36e3472016-11-03 11:57:10 -07001156 int fd = resource->data[0];
1157 int size2 = ashmem_get_size_region(fd);
1158 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001159 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001160 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1161 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001162 return nullptr;
1163 }
1164 break;
1165 }
1166 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001167 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001168 break;
1169 default:
1170 ALOGE("Unknown direct connection memory type %d", type);
1171 return nullptr;
1172 }
1173
1174 native_handle_t *clone = native_handle_clone(resource);
1175 if (!clone) {
1176 return nullptr;
1177 }
1178
1179 SensorDirectConnection* conn = nullptr;
1180 SensorDevice& dev(SensorDevice::getInstance());
1181 int channelHandle = dev.registerDirectChannel(&mem);
1182
1183 if (channelHandle <= 0) {
1184 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1185 } else {
1186 mem.handle = clone;
1187 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1188 }
1189
1190 if (conn == nullptr) {
1191 native_handle_close(clone);
1192 native_handle_delete(clone);
1193 } else {
1194 // add to list of direct connections
1195 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1196 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1197 }
1198 return conn;
1199}
1200
Peng Xudd5c5cb2017-03-16 17:39:43 -07001201int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001202 int32_t handle, int32_t type,
1203 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001204 Mutex::Autolock _l(mLock);
1205
Alexey Polyudov88711e82017-05-23 19:54:04 -07001206 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001207 return PERMISSION_DENIED;
1208 }
1209
1210 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001211 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001212 size_t expectSize = INT32_MAX;
1213 switch (type) {
1214 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1215 isFloat = true;
1216 expectSize = 3;
1217 break;
1218 case AINFO_LOCAL_GRAVITY:
1219 isFloat = true;
1220 expectSize = 1;
1221 break;
1222 case AINFO_DOCK_STATE:
1223 case AINFO_HIGH_PERFORMANCE_MODE:
1224 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1225 isFloat = false;
1226 expectSize = 1;
1227 break;
1228 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001229 // CUSTOM events must only contain float data; it may have variable size
1230 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1231 ints.size() ||
1232 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1233 handle < 0) {
1234 return BAD_VALUE;
1235 }
1236 isFloat = true;
1237 isCustom = true;
1238 expectSize = floats.size();
1239 break;
1240 }
1241
1242 if (!isCustom && handle != -1) {
1243 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001244 }
1245
1246 // three events: first one is begin tag, last one is end tag, the one in the middle
1247 // is the payload.
1248 sensors_event_t event[3];
1249 int64_t timestamp = elapsedRealtimeNano();
1250 for (sensors_event_t* i = event; i < event + 3; i++) {
1251 *i = (sensors_event_t) {
1252 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001253 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001254 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1255 .timestamp = timestamp++,
1256 .additional_info = (additional_info_event_t) {
1257 .serial = 0
1258 }
1259 };
1260 }
1261
1262 event[0].additional_info.type = AINFO_BEGIN;
1263 event[1].additional_info.type = type;
1264 event[2].additional_info.type = AINFO_END;
1265
1266 if (isFloat) {
1267 if (floats.size() != expectSize) {
1268 return BAD_VALUE;
1269 }
1270 for (size_t i = 0; i < expectSize; ++i) {
1271 event[1].additional_info.data_float[i] = floats[i];
1272 }
1273 } else {
1274 if (ints.size() != expectSize) {
1275 return BAD_VALUE;
1276 }
1277 for (size_t i = 0; i < expectSize; ++i) {
1278 event[1].additional_info.data_int32[i] = ints[i];
1279 }
1280 }
1281
1282 SensorDevice& dev(SensorDevice::getInstance());
1283 for (sensors_event_t* i = event; i < event + 3; i++) {
1284 int ret = dev.injectSensorData(i);
1285 if (ret != NO_ERROR) {
1286 return ret;
1287 }
1288 }
1289 return NO_ERROR;
1290}
1291
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001292status_t SensorService::resetToNormalMode() {
1293 Mutex::Autolock _l(mLock);
1294 return resetToNormalModeLocked();
1295}
1296
1297status_t SensorService::resetToNormalModeLocked() {
1298 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001299 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301300 if (err == NO_ERROR) {
1301 mCurrentOperatingMode = NORMAL;
1302 dev.enableAllSensors();
1303 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001304 return err;
1305}
1306
Peng Xu47e96012016-03-28 17:55:56 -07001307void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001308 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001309 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001310 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001311 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001312 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001313 int handle = mActiveSensors.keyAt(i);
1314 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001315 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001316 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1317 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001318 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001319 } else {
1320 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001321 }
Aravind Akella8a969552014-09-28 17:52:41 -07001322 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001323 }
1324 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001325 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001326 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001327 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001328 c, i, handle);
1329
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001330 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001331 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001332 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001333 mActiveVirtualSensors.erase(handle);
Brian Stack0b858c12018-10-19 10:53:25 -07001334
1335 // If this is the last connection, then mark the RecentEventLogger as stale. This is
1336 // critical for on-change events since the previous event is sent to a client if the
1337 // sensor is already active. If two clients request the sensor at the same time, one
1338 // of the clients would receive a stale event.
1339 auto logger = mRecentEvent.find(handle);
1340 if (logger != mRecentEvent.end()) {
1341 logger->second->setLastEventStale();
1342 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001343 delete rec;
1344 size--;
1345 } else {
1346 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001347 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001348 }
Aravind Akella8a969552014-09-28 17:52:41 -07001349 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001350 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001351 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001352 if (c->needsWakeLock()) {
1353 checkWakeLockStateLocked();
1354 }
Peng Xu4f707f82016-09-26 11:28:32 -07001355
1356 SensorDevice& dev(SensorDevice::getInstance());
1357 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001358}
1359
Peng Xue36e3472016-11-03 11:57:10 -07001360void SensorService::cleanupConnection(SensorDirectConnection* c) {
1361 Mutex::Autolock _l(mLock);
1362
1363 SensorDevice& dev(SensorDevice::getInstance());
1364 dev.unregisterDirectChannel(c->getHalChannelHandle());
1365 mDirectConnections.remove(c);
1366}
1367
Peng Xu755c4512016-04-07 23:15:14 -07001368sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001369 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001370}
1371
Mathias Agopianfc328812010-07-14 23:41:37 -07001372status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001373 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001374 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001375 if (mInitCheck != NO_ERROR)
1376 return mInitCheck;
1377
Peng Xu755c4512016-04-07 23:15:14 -07001378 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1379 if (sensor == nullptr ||
1380 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001381 return BAD_VALUE;
1382 }
1383
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001384 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001385 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001386 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001387 return INVALID_OPERATION;
1388 }
1389
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001390 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001391 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001392 rec = new SensorRecord(connection);
1393 mActiveSensors.add(handle, rec);
1394 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001395 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001396 }
1397 } else {
1398 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001399 // this sensor is already activated, but we are adding a connection that uses it.
1400 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001401 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001402 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001403 // NOTE: The wake_up flag of this event may get set to
1404 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001405
1406 auto logger = mRecentEvent.find(handle);
1407 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001408 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001409 // Verify that the last sensor event was generated from the current activation
1410 // of the sensor. If not, it is possible for an on-change sensor to receive a
1411 // sensor event that is stale if two clients re-activate the sensor
1412 // simultaneously.
1413 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001414 event.sensor = handle;
1415 if (event.version == sizeof(sensors_event_t)) {
1416 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1417 setWakeLockAcquiredLocked(true);
1418 }
Yi Kong8f313e32018-07-17 14:13:29 -07001419 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001420 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1421 checkWakeLockStateLocked();
1422 }
1423 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001424 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001425 }
1426 }
1427 }
1428 }
1429
1430 if (connection->addSensor(handle)) {
1431 BatteryService::enableSensor(connection->getUid(), handle);
1432 // the sensor was added (which means it wasn't already there)
1433 // so, see if this connection becomes active
1434 if (mActiveConnections.indexOf(connection) < 0) {
1435 mActiveConnections.add(connection);
1436 }
1437 } else {
1438 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1439 handle, connection.get());
1440 }
1441
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301442 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001443 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301444 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1445 samplingPeriodNs = maxDelayNs;
1446 }
1447
Aravind Akella724d91d2013-06-27 12:04:23 -07001448 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1449 if (samplingPeriodNs < minDelayNs) {
1450 samplingPeriodNs = minDelayNs;
1451 }
1452
Aravind Akella6c2664a2014-08-13 12:24:50 -07001453 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1454 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001455 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1456
Aravind Akella4949c502015-02-11 15:54:35 -08001457 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001458 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001459
Peng Xu20483c42015-10-26 15:14:43 -07001460 // Call flush() before calling activate() on the sensor. Wait for a first
1461 // flush complete event before sending events on this connection. Ignore
1462 // one-shot sensors which don't support flush(). Ignore on-change sensors
1463 // to maintain the on-change logic (any on-change events except the initial
1464 // one should be trigger by a change in value). Also if this sensor isn't
1465 // already active, don't call flush().
1466 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001467 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001468 rec->getNumConnections() > 1) {
1469 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001470 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001471 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001472 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001473 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001474 } else {
1475 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001476 }
1477 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001478
1479 if (err == NO_ERROR) {
1480 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1481 err = sensor->activate(connection.get(), true);
1482 }
1483
Aravind Akella8a969552014-09-28 17:52:41 -07001484 if (err == NO_ERROR) {
1485 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001486
1487 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1488 SensorRegistrationInfo(handle, connection->getPackageName(),
1489 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001490 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001491 }
1492
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001493 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001494 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001495 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001496 }
1497 return err;
1498}
1499
Peng Xu47e96012016-03-28 17:55:56 -07001500status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001501 if (mInitCheck != NO_ERROR)
1502 return mInitCheck;
1503
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001504 Mutex::Autolock _l(mLock);
1505 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001506 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001507 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1508 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001509
1510 }
1511 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001512 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1513 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001514 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001515 }
1516 return err;
1517}
1518
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001519status_t SensorService::cleanupWithoutDisable(
1520 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001521 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001522 return cleanupWithoutDisableLocked(connection, handle);
1523}
1524
1525status_t SensorService::cleanupWithoutDisableLocked(
1526 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001527 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001528 if (rec) {
1529 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001530 if (connection->removeSensor(handle)) {
1531 BatteryService::disableSensor(connection->getUid(), handle);
1532 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001533 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001534 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001535 mActiveConnections.remove(connection);
1536 }
1537 // see if this sensor becomes inactive
1538 if (rec->removeConnection(connection)) {
1539 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001540 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001541 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001542 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001543 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001544 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001545 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001546}
1547
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001548status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001549 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001550 if (mInitCheck != NO_ERROR)
1551 return mInitCheck;
1552
Peng Xu755c4512016-04-07 23:15:14 -07001553 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1554 if (sensor == nullptr ||
1555 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001556 return BAD_VALUE;
1557 }
1558
Mathias Agopian1cd70002010-07-21 15:59:50 -07001559 if (ns < 0)
1560 return BAD_VALUE;
1561
Mathias Agopian62569ec2011-11-07 21:21:47 -08001562 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1563 if (ns < minDelayNs) {
1564 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001565 }
1566
Mathias Agopianf001c922010-11-11 17:58:51 -08001567 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001568}
1569
Svetoslavb412f6e2015-04-29 16:50:41 -07001570status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1571 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001572 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001573 SensorDevice& dev(SensorDevice::getInstance());
1574 const int halVersion = dev.getHalDeviceVersion();
1575 status_t err(NO_ERROR);
1576 Mutex::Autolock _l(mLock);
1577 // Loop through all sensors for this connection and call flush on each of them.
1578 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1579 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001580 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1581 if (sensor == nullptr) {
1582 continue;
1583 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001584 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1585 ALOGE("flush called on a one-shot sensor");
1586 err = INVALID_OPERATION;
1587 continue;
1588 }
Aravind Akella8493b792014-09-08 15:45:47 -07001589 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001590 // For older devices just increment pending flush count which will send a trivial
1591 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001592 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001593 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001594 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1595 err = INVALID_OPERATION;
1596 continue;
1597 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001598 status_t err_flush = sensor->flush(connection.get(), handle);
1599 if (err_flush == NO_ERROR) {
1600 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001601 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001602 }
1603 err = (err_flush != NO_ERROR) ? err_flush : err;
1604 }
Aravind Akella70018042014-04-07 22:52:37 +00001605 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001606 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001607}
Aravind Akella70018042014-04-07 22:52:37 +00001608
Svetoslavb412f6e2015-04-29 16:50:41 -07001609bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1610 const String16& opPackageName) {
1611 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001612
Svetoslavb412f6e2015-04-29 16:50:41 -07001613 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001614 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001615 }
1616
1617 bool hasPermission = false;
1618
1619 // Runtime permissions can't use the cache as they may change.
1620 if (sensor.isRequiredPermissionRuntime()) {
1621 hasPermission = checkPermission(String16(requiredPermission),
1622 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001623 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001624 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1625 }
1626
1627 if (!hasPermission) {
1628 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1629 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001630 return false;
1631 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001632
1633 const int32_t opCode = sensor.getRequiredAppOp();
1634 if (opCode >= 0) {
1635 AppOpsManager appOps;
1636 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1637 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001638 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001639 operation, sensor.getName().string(), opCode);
1640 return false;
1641 }
1642 }
1643
1644 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001645}
1646
Aravind Akella9a844cf2014-02-11 18:58:52 -08001647void SensorService::checkWakeLockState() {
1648 Mutex::Autolock _l(mLock);
1649 checkWakeLockStateLocked();
1650}
1651
1652void SensorService::checkWakeLockStateLocked() {
1653 if (!mWakeLockAcquired) {
1654 return;
1655 }
1656 bool releaseLock = true;
1657 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1658 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001659 if (connection != nullptr) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001660 if (connection->needsWakeLock()) {
1661 releaseLock = false;
1662 break;
1663 }
1664 }
1665 }
1666 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001667 setWakeLockAcquiredLocked(false);
1668 }
1669}
1670
1671void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1672 Mutex::Autolock _l(mLock);
1673 connection->writeToSocketFromCache();
1674 if (connection->needsWakeLock()) {
1675 setWakeLockAcquiredLocked(true);
1676 }
1677}
1678
1679void SensorService::populateActiveConnections(
1680 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1681 Mutex::Autolock _l(mLock);
1682 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1683 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001684 if (connection != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001685 activeConnections->add(connection);
1686 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001687 }
1688}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001689
Aravind Akella4949c502015-02-11 15:54:35 -08001690bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001691 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001692}
1693
Peng Xue36e3472016-11-03 11:57:10 -07001694bool SensorService::isOperationRestricted(const String16& opPackageName) {
1695 Mutex::Autolock _l(mLock);
1696 if (mCurrentOperatingMode != RESTRICTED) {
1697 String8 package(opPackageName);
1698 return !isWhiteListedPackage(package);
1699 }
1700 return false;
1701}
1702
Svet Ganove752a5c2018-01-15 17:14:20 -08001703void SensorService::UidPolicy::registerSelf() {
1704 ActivityManager am;
1705 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1706 | ActivityManager::UID_OBSERVER_IDLE
1707 | ActivityManager::UID_OBSERVER_ACTIVE,
1708 ActivityManager::PROCESS_STATE_UNKNOWN,
1709 String16("android"));
1710}
1711
1712void SensorService::UidPolicy::unregisterSelf() {
1713 ActivityManager am;
1714 am.unregisterUidObserver(this);
1715}
1716
1717void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1718 onUidIdle(uid, disabled);
1719}
1720
1721void SensorService::UidPolicy::onUidActive(uid_t uid) {
1722 {
1723 Mutex::Autolock _l(mUidLock);
1724 mActiveUids.insert(uid);
1725 }
1726 sp<SensorService> service = mService.promote();
1727 if (service != nullptr) {
1728 service->setSensorAccess(uid, true);
1729 }
1730}
1731
1732void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1733 bool deleted = false;
1734 {
1735 Mutex::Autolock _l(mUidLock);
1736 if (mActiveUids.erase(uid) > 0) {
1737 deleted = true;
1738 }
1739 }
1740 if (deleted) {
1741 sp<SensorService> service = mService.promote();
1742 if (service != nullptr) {
1743 service->setSensorAccess(uid, false);
1744 }
1745 }
1746}
1747
1748void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1749 updateOverrideUid(uid, active, true);
1750}
1751
1752void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1753 updateOverrideUid(uid, false, false);
1754}
1755
1756void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1757 bool wasActive = false;
1758 bool isActive = false;
1759 {
1760 Mutex::Autolock _l(mUidLock);
1761 wasActive = isUidActiveLocked(uid);
1762 mOverrideUids.erase(uid);
1763 if (insert) {
1764 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1765 }
1766 isActive = isUidActiveLocked(uid);
1767 }
1768 if (wasActive != isActive) {
1769 sp<SensorService> service = mService.promote();
1770 if (service != nullptr) {
1771 service->setSensorAccess(uid, isActive);
1772 }
1773 }
1774}
1775
1776bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1777 // Non-app UIDs are considered always active
1778 if (uid < FIRST_APPLICATION_UID) {
1779 return true;
1780 }
1781 Mutex::Autolock _l(mUidLock);
1782 return isUidActiveLocked(uid);
1783}
1784
1785bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1786 // Non-app UIDs are considered always active
1787 if (uid < FIRST_APPLICATION_UID) {
1788 return true;
1789 }
1790 auto it = mOverrideUids.find(uid);
1791 if (it != mOverrideUids.end()) {
1792 return it->second;
1793 }
1794 return mActiveUids.find(uid) != mActiveUids.end();
1795}
1796
Michael Groover5e1f60b2018-12-04 22:34:29 -08001797void SensorService::SensorPrivacyPolicy::registerSelf() {
1798 SensorPrivacyManager spm;
1799 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1800 spm.addSensorPrivacyListener(this);
1801}
1802
1803void SensorService::SensorPrivacyPolicy::unregisterSelf() {
1804 SensorPrivacyManager spm;
1805 spm.removeSensorPrivacyListener(this);
1806}
1807
1808bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1809 return mSensorPrivacyEnabled;
1810}
1811
1812binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1813 mSensorPrivacyEnabled = enabled;
1814 sp<SensorService> service = mService.promote();
1815 if (service != nullptr) {
1816 if (enabled) {
1817 service->disableAllSensors();
1818 } else {
1819 service->enableAllSensors();
1820 }
1821 }
1822 return binder::Status::ok();
1823}
Mathias Agopianfc328812010-07-14 23:41:37 -07001824}; // namespace android