blob: a8cb372792777e156a553fb0b4906e41297e27ef [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 }
568 if (args.size() == 3 && args[0] == String16("set-uid-state")) {
569 return handleSetUidState(args, err);
570 } else if (args.size() == 2 && args[0] == String16("reset-uid-state")) {
571 return handleResetUidState(args, err);
572 } else if (args.size() == 2 && args[0] == String16("get-uid-state")) {
573 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
582status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
583 PermissionController pc;
584 int uid = pc.getPackageUid(args[1], 0);
585 if (uid <= 0) {
586 ALOGE("Unknown package: '%s'", String8(args[1]).string());
587 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
588 return BAD_VALUE;
589 }
590 bool active = false;
591 if (args[2] == String16("active")) {
592 active = true;
593 } else if ((args[2] != String16("idle"))) {
594 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
595 return BAD_VALUE;
596 }
597 mUidPolicy->addOverrideUid(uid, active);
598 return NO_ERROR;
599}
600
601status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
602 PermissionController pc;
603 int uid = pc.getPackageUid(args[1], 0);
604 if (uid < 0) {
605 ALOGE("Unknown package: '%s'", String8(args[1]).string());
606 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
607 return BAD_VALUE;
608 }
609 mUidPolicy->removeOverrideUid(uid);
610 return NO_ERROR;
611}
612
613status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
614 PermissionController pc;
615 int uid = pc.getPackageUid(args[1], 0);
616 if (uid < 0) {
617 ALOGE("Unknown package: '%s'", String8(args[1]).string());
618 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
619 return BAD_VALUE;
620 }
621 if (mUidPolicy->isUidActive(uid)) {
622 return dprintf(out, "active\n");
623 } else {
624 return dprintf(out, "idle\n");
625 }
626}
627
628status_t SensorService::printHelp(int out) {
629 return dprintf(out, "Sensor service commands:\n"
630 " get-uid-state <PACKAGE> gets the uid state\n"
631 " set-uid-state <PACKAGE> <active|idle> overrides the uid state\n"
632 " reset-uid-state <PACKAGE> clears the uid state override\n"
633 " help print this message\n");
634}
635
Peng Xu0cc8f802016-04-05 23:46:03 -0700636//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800637void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700638 sensors_event_t const* buffer, const int count) {
639 for (int i=0 ; i<count ; i++) {
640 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700641 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
642 handle = buffer[i].meta_data.sensor;
643 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700644 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700645 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700646 // If this buffer has an event from a one_shot sensor and this connection is registered
647 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700648 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700649 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
650 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800651 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700652 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700653
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700654 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700655 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700656}
657
Peng Xu47e96012016-03-28 17:55:56 -0700658bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000659 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700660
Peng Xueb4d6282015-12-10 18:02:41 -0800661 // each virtual sensor could generate an event per "real" event, that's why we need to size
662 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
663 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700664 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700665 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700666 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700667
Mathias Agopianf001c922010-11-11 17:58:51 -0800668 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700669
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700670 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700671 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700672 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
673 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700674 if(count == DEAD_OBJECT && device.isReconnecting()) {
675 device.reconnect();
676 continue;
677 } else {
678 ALOGE("sensor poll failed (%s)", strerror(-count));
679 break;
680 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700681 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700682
683 // Reset sensors_event_t.flags to zero for all events in the buffer.
684 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700685 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700686 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700687
Peng Xueb4d6282015-12-10 18:02:41 -0800688 // Make a copy of the connection vector as some connections may be removed during the course
689 // of this loop (especially when one-shot sensor events are present in the sensor_event
690 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
691 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
692 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
693 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700694 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700695 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800696
Aravind Akella9a844cf2014-02-11 18:58:52 -0800697 Mutex::Autolock _l(mLock);
698 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
699 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
700 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
701 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
702 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700703 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700704 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700705 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700706 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700707 }
708 }
709
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700710 if (wakeEvents > 0) {
711 if (!mWakeLockAcquired) {
712 setWakeLockAcquiredLocked(true);
713 }
714 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800715 }
Aravind Akella8493b792014-09-08 15:45:47 -0700716 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800717
Mathias Agopianf001c922010-11-11 17:58:51 -0800718 // handle virtual sensors
719 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700720 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700721 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800722 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700723 SensorFusion& fusion(SensorFusion::getInstance());
724 if (fusion.isEnabled()) {
725 for (size_t i=0 ; i<size_t(count) ; i++) {
726 fusion.process(event[i]);
727 }
728 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700729 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700730 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700731 if (count + k >= minBufferSize) {
732 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700733 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700734 count, k, minBufferSize);
735 break;
736 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800737 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700738 sp<SensorInterface> si = mSensors.getInterface(handle);
739 if (si == nullptr) {
740 ALOGE("handle %d is not an valid virtual sensor", handle);
741 continue;
742 }
743
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700744 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700745 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800746 k++;
747 }
748 }
749 }
750 if (k) {
751 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700752 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800753 count += k;
754 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700755 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700756 }
757 }
758 }
759
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700760 // handle backward compatibility for RotationVector sensor
761 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
762 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700763 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700764 // All the 4 components of the quaternion should be available
765 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700766 mSensorEventBuffer[i].data[4] = -1;
767 }
768 }
769 }
770
Aravind Akella8493b792014-09-08 15:45:47 -0700771 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700772 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
773 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
774 // SensorEventConnection mapped to the corresponding flush_complete_event in
775 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700776 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700777 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
778 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
779 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700780 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700781 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
782 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700783 }
784 }
Peng Xu2576cb62016-01-20 00:22:09 -0800785
786 // handle dynamic sensor meta events, process registration and unregistration of dynamic
787 // sensor based on content of event.
788 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
789 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
790 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
791 const sensor_t& dynamicSensor =
792 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
793 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
794 handle, dynamicSensor.type, dynamicSensor.name);
795
Peng Xu0cc8f802016-04-05 23:46:03 -0700796 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800797 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700798 sensor_t s = dynamicSensor;
799 // make sure the dynamic sensor flag is set
800 s.flags |= DYNAMIC_SENSOR_MASK;
801 // force the handle to be consistent
802 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800803
804 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800805
Peng Xu0cc8f802016-04-05 23:46:03 -0700806 // This will release hold on dynamic sensor meta, so it should be called
807 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700808 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800809 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700810 } else {
811 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
812 }
Peng Xu2576cb62016-01-20 00:22:09 -0800813 } else {
814 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
815 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
816
817 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800818 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800819 ALOGE("Dynamic sensor release error.");
820 }
821
822 size_t numConnections = activeConnections.size();
823 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700824 if (activeConnections[i] != nullptr) {
Peng Xu2576cb62016-01-20 00:22:09 -0800825 activeConnections[i]->removeSensor(handle);
826 }
827 }
828 }
829 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700830 }
831
Aravind Akella9a844cf2014-02-11 18:58:52 -0800832 // Send our events to clients. Check the state of wake lock for each client and release the
833 // lock if none of the clients need it.
834 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700835 size_t numConnections = activeConnections.size();
836 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700837 if (activeConnections[i] != nullptr) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700838 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700839 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700840 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700841 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
842 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700843 if (activeConnections[i]->hasOneShotSensors()) {
844 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
845 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700846 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800847 }
848 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700849
Aravind Akella9a844cf2014-02-11 18:58:52 -0800850 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700851 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800852 }
Aravind Akella8493b792014-09-08 15:45:47 -0700853 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700854
Steve Block3c20fbe2012-01-05 23:22:43 +0000855 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800856 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700857 return false;
858}
859
Aravind Akella56ae4262014-07-10 16:01:10 -0700860sp<Looper> SensorService::getLooper() const {
861 return mLooper;
862}
863
Aravind Akellab4373ac2014-10-29 17:55:20 -0700864void SensorService::resetAllWakeLockRefCounts() {
865 SortedVector< sp<SensorEventConnection> > activeConnections;
866 populateActiveConnections(&activeConnections);
867 {
868 Mutex::Autolock _l(mLock);
869 for (size_t i=0 ; i < activeConnections.size(); ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700870 if (activeConnections[i] != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700871 activeConnections[i]->resetWakeLockRefCount();
872 }
873 }
874 setWakeLockAcquiredLocked(false);
875 }
876}
877
878void SensorService::setWakeLockAcquiredLocked(bool acquire) {
879 if (acquire) {
880 if (!mWakeLockAcquired) {
881 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
882 mWakeLockAcquired = true;
883 }
884 mLooper->wake();
885 } else {
886 if (mWakeLockAcquired) {
887 release_wake_lock(WAKE_LOCK_NAME);
888 mWakeLockAcquired = false;
889 }
890 }
891}
892
Aravind Akellab4373ac2014-10-29 17:55:20 -0700893bool SensorService::isWakeLockAcquired() {
894 Mutex::Autolock _l(mLock);
895 return mWakeLockAcquired;
896}
897
Aravind Akella56ae4262014-07-10 16:01:10 -0700898bool SensorService::SensorEventAckReceiver::threadLoop() {
899 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700900 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700901 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700902 bool wakeLockAcquired = mService->isWakeLockAcquired();
903 int timeout = -1;
904 if (wakeLockAcquired) timeout = 5000;
905 int ret = looper->pollOnce(timeout);
906 if (ret == ALOOPER_POLL_TIMEOUT) {
907 mService->resetAllWakeLockRefCounts();
908 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700909 } while(!Thread::exitPending());
910 return false;
911}
912
Aravind Akella9a844cf2014-02-11 18:58:52 -0800913void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800914 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800915 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800916 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
917 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800918 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800919 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800920 }
Peng Xu2576cb62016-01-20 00:22:09 -0800921
Peng Xu6a2d3a02015-12-21 12:00:23 -0800922 auto logger = mRecentEvent.find(buffer[i].sensor);
923 if (logger != mRecentEvent.end()) {
924 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800925 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800926 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800927}
928
Peng Xu47e96012016-03-28 17:55:56 -0700929void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800930 struct compar {
931 static int cmp(void const* lhs, void const* rhs) {
932 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
933 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700934 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800935 }
936 };
937 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
938}
939
Mathias Agopian5d270722010-07-19 15:20:39 -0700940String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700941 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700942}
943
Aravind Akellab4099e72013-10-15 15:43:10 -0700944bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700945 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
946 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700947}
948
Aravind Akella9a844cf2014-02-11 18:58:52 -0800949bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700950 int handle = event.sensor;
951 if (event.type == SENSOR_TYPE_META_DATA) {
952 handle = event.meta_data.sensor;
953 }
Peng Xu755c4512016-04-07 23:15:14 -0700954 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
955 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800956}
957
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700958int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
959 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
960 // UUID is not supported for this device.
961 return 0;
962 }
963 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
964 // This sensor can be uniquely identified in the system by
965 // the combination of its type and name.
966 return -1;
967 }
968
969 // We have a dynamic sensor.
970
971 if (!sHmacGlobalKeyIsValid) {
972 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
973 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
974 return 0;
975 }
976
977 // We want each app author/publisher to get a different ID, so that the
978 // same dynamic sensor cannot be tracked across apps by multiple
979 // authors/publishers. So we use both our UUID and our User ID.
980 // Note potential confusion:
981 // UUID => Universally Unique Identifier.
982 // UID => User Identifier.
983 // We refrain from using "uid" except as needed by API to try to
984 // keep this distinction clear.
985
986 auto appUserId = IPCThreadState::self()->getCallingUid();
987 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
988 memcpy(uuidAndApp, &uuid, sizeof(uuid));
989 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
990
991 // Now we use our key on our UUID/app combo to get the hash.
992 uint8_t hash[EVP_MAX_MD_SIZE];
993 unsigned int hashLen;
994 if (HMAC(EVP_sha256(),
995 sHmacGlobalKey, sizeof(sHmacGlobalKey),
996 uuidAndApp, sizeof(uuidAndApp),
997 hash, &hashLen) == nullptr) {
998 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
999 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1000 return 0;
1001 }
1002
1003 int32_t id = 0;
1004 if (hashLen < sizeof(id)) {
1005 // We never expect this case, but out of paranoia, we handle it.
1006 // Our 'id' length is already quite small, we don't want the
1007 // effective length of it to be even smaller.
1008 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1009 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1010 return 0;
1011 }
1012
1013 // This is almost certainly less than all of 'hash', but it's as secure
1014 // as we can be with our current 'id' length.
1015 memcpy(&id, hash, sizeof(id));
1016
1017 // Note at the beginning of the function that we return the values of
1018 // 0 and -1 to represent special cases. As a result, we can't return
1019 // those as dynamic sensor IDs. If we happened to hash to one of those
1020 // values, we change 'id' so we report as a dynamic sensor, and not as
1021 // one of those special cases.
1022 if (id == -1) {
1023 id = -2;
1024 } else if (id == 0) {
1025 id = 1;
1026 }
1027 return id;
1028}
1029
1030void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1031 for (auto &sensor : sensorList) {
1032 int32_t id = getIdFromUuid(sensor.getUuid());
1033 sensor.setId(id);
1034 }
1035}
1036
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001037Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001038 char value[PROPERTY_VALUE_MAX];
1039 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001040 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001041 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001042 Vector<Sensor> accessibleSensorList;
1043 for (size_t i = 0; i < initialSensorList.size(); i++) {
1044 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001045 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001046 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001047 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001048 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001049}
1050
Peng Xu47e96012016-03-28 17:55:56 -07001051Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001052 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001053 mSensors.forEachSensor(
1054 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001055 if (sensor.isDynamicSensor()) {
1056 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1057 accessibleSensorList.add(sensor);
1058 } else {
1059 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1060 sensor.getName().string(),
1061 sensor.getRequiredPermission().string(),
1062 sensor.getRequiredAppOp());
1063 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001064 }
1065 return true;
1066 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001067 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001068 return accessibleSensorList;
1069}
1070
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001071sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001072 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001073 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1074 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001075 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001076 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001077
1078 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001079 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1080 // operating in DI mode.
1081 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001082 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1083 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001084 }
1085
Mathias Agopian5307d172012-09-18 17:02:43 -07001086 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001087 pid_t pid = IPCThreadState::self()->getCallingPid();
1088
1089 String8 connPackageName =
1090 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1091 String16 connOpPackageName =
1092 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001093 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001094 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001095 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001096 if (requestedMode == DATA_INJECTION) {
1097 if (mActiveConnections.indexOf(result) < 0) {
1098 mActiveConnections.add(result);
1099 }
1100 // Add the associated file descriptor to the Looper for polling whenever there is data to
1101 // be injected.
1102 result->updateLooperRegistration(mLooper);
1103 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001104 return result;
1105}
1106
Aravind Akella841a5922015-06-29 12:37:48 -07001107int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001108 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001109 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001110}
1111
Peng Xue36e3472016-11-03 11:57:10 -07001112sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1113 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1114 const native_handle *resource) {
1115 Mutex::Autolock _l(mLock);
1116
Michael Groover5e1f60b2018-12-04 22:34:29 -08001117 // No new direct connections are allowed when sensor privacy is enabled
1118 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1119 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1120 return nullptr;
1121 }
1122
Peng Xue36e3472016-11-03 11:57:10 -07001123 struct sensors_direct_mem_t mem = {
1124 .type = type,
1125 .format = format,
1126 .size = size,
1127 .handle = resource,
1128 };
1129 uid_t uid = IPCThreadState::self()->getCallingUid();
1130
1131 if (mem.handle == nullptr) {
1132 ALOGE("Failed to clone resource handle");
1133 return nullptr;
1134 }
1135
1136 // check format
1137 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1138 ALOGE("Direct channel format %d is unsupported!", format);
1139 return nullptr;
1140 }
1141
1142 // check for duplication
1143 for (auto &i : mDirectConnections) {
1144 sp<SensorDirectConnection> connection(i.promote());
1145 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001146 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001147 return nullptr;
1148 }
1149 }
1150
1151 // check specific to memory type
1152 switch(type) {
1153 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001154 if (resource->numFds < 1) {
1155 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1156 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1157 return nullptr;
1158 }
Peng Xue36e3472016-11-03 11:57:10 -07001159 int fd = resource->data[0];
1160 int size2 = ashmem_get_size_region(fd);
1161 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001162 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001163 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1164 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001165 return nullptr;
1166 }
1167 break;
1168 }
1169 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001170 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001171 break;
1172 default:
1173 ALOGE("Unknown direct connection memory type %d", type);
1174 return nullptr;
1175 }
1176
1177 native_handle_t *clone = native_handle_clone(resource);
1178 if (!clone) {
1179 return nullptr;
1180 }
1181
1182 SensorDirectConnection* conn = nullptr;
1183 SensorDevice& dev(SensorDevice::getInstance());
1184 int channelHandle = dev.registerDirectChannel(&mem);
1185
1186 if (channelHandle <= 0) {
1187 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1188 } else {
1189 mem.handle = clone;
1190 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1191 }
1192
1193 if (conn == nullptr) {
1194 native_handle_close(clone);
1195 native_handle_delete(clone);
1196 } else {
1197 // add to list of direct connections
1198 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1199 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1200 }
1201 return conn;
1202}
1203
Peng Xudd5c5cb2017-03-16 17:39:43 -07001204int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001205 int32_t handle, int32_t type,
1206 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001207 Mutex::Autolock _l(mLock);
1208
Alexey Polyudov88711e82017-05-23 19:54:04 -07001209 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001210 return PERMISSION_DENIED;
1211 }
1212
1213 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001214 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001215 size_t expectSize = INT32_MAX;
1216 switch (type) {
1217 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1218 isFloat = true;
1219 expectSize = 3;
1220 break;
1221 case AINFO_LOCAL_GRAVITY:
1222 isFloat = true;
1223 expectSize = 1;
1224 break;
1225 case AINFO_DOCK_STATE:
1226 case AINFO_HIGH_PERFORMANCE_MODE:
1227 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1228 isFloat = false;
1229 expectSize = 1;
1230 break;
1231 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001232 // CUSTOM events must only contain float data; it may have variable size
1233 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1234 ints.size() ||
1235 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1236 handle < 0) {
1237 return BAD_VALUE;
1238 }
1239 isFloat = true;
1240 isCustom = true;
1241 expectSize = floats.size();
1242 break;
1243 }
1244
1245 if (!isCustom && handle != -1) {
1246 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001247 }
1248
1249 // three events: first one is begin tag, last one is end tag, the one in the middle
1250 // is the payload.
1251 sensors_event_t event[3];
1252 int64_t timestamp = elapsedRealtimeNano();
1253 for (sensors_event_t* i = event; i < event + 3; i++) {
1254 *i = (sensors_event_t) {
1255 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001256 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001257 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1258 .timestamp = timestamp++,
1259 .additional_info = (additional_info_event_t) {
1260 .serial = 0
1261 }
1262 };
1263 }
1264
1265 event[0].additional_info.type = AINFO_BEGIN;
1266 event[1].additional_info.type = type;
1267 event[2].additional_info.type = AINFO_END;
1268
1269 if (isFloat) {
1270 if (floats.size() != expectSize) {
1271 return BAD_VALUE;
1272 }
1273 for (size_t i = 0; i < expectSize; ++i) {
1274 event[1].additional_info.data_float[i] = floats[i];
1275 }
1276 } else {
1277 if (ints.size() != expectSize) {
1278 return BAD_VALUE;
1279 }
1280 for (size_t i = 0; i < expectSize; ++i) {
1281 event[1].additional_info.data_int32[i] = ints[i];
1282 }
1283 }
1284
1285 SensorDevice& dev(SensorDevice::getInstance());
1286 for (sensors_event_t* i = event; i < event + 3; i++) {
1287 int ret = dev.injectSensorData(i);
1288 if (ret != NO_ERROR) {
1289 return ret;
1290 }
1291 }
1292 return NO_ERROR;
1293}
1294
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001295status_t SensorService::resetToNormalMode() {
1296 Mutex::Autolock _l(mLock);
1297 return resetToNormalModeLocked();
1298}
1299
1300status_t SensorService::resetToNormalModeLocked() {
1301 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001302 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301303 if (err == NO_ERROR) {
1304 mCurrentOperatingMode = NORMAL;
1305 dev.enableAllSensors();
1306 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001307 return err;
1308}
1309
Peng Xu47e96012016-03-28 17:55:56 -07001310void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001311 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001312 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001313 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001314 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001315 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001316 int handle = mActiveSensors.keyAt(i);
1317 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001318 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001319 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1320 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001321 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001322 } else {
1323 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001324 }
Aravind Akella8a969552014-09-28 17:52:41 -07001325 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001326 }
1327 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001328 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001329 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001330 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001331 c, i, handle);
1332
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001333 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001334 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001335 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001336 mActiveVirtualSensors.erase(handle);
Brian Stack0b858c12018-10-19 10:53:25 -07001337
1338 // If this is the last connection, then mark the RecentEventLogger as stale. This is
1339 // critical for on-change events since the previous event is sent to a client if the
1340 // sensor is already active. If two clients request the sensor at the same time, one
1341 // of the clients would receive a stale event.
1342 auto logger = mRecentEvent.find(handle);
1343 if (logger != mRecentEvent.end()) {
1344 logger->second->setLastEventStale();
1345 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001346 delete rec;
1347 size--;
1348 } else {
1349 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001350 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001351 }
Aravind Akella8a969552014-09-28 17:52:41 -07001352 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001353 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001354 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001355 if (c->needsWakeLock()) {
1356 checkWakeLockStateLocked();
1357 }
Peng Xu4f707f82016-09-26 11:28:32 -07001358
1359 SensorDevice& dev(SensorDevice::getInstance());
1360 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001361}
1362
Peng Xue36e3472016-11-03 11:57:10 -07001363void SensorService::cleanupConnection(SensorDirectConnection* c) {
1364 Mutex::Autolock _l(mLock);
1365
1366 SensorDevice& dev(SensorDevice::getInstance());
1367 dev.unregisterDirectChannel(c->getHalChannelHandle());
1368 mDirectConnections.remove(c);
1369}
1370
Peng Xu755c4512016-04-07 23:15:14 -07001371sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001372 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001373}
1374
Mathias Agopianfc328812010-07-14 23:41:37 -07001375status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001376 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001377 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001378 if (mInitCheck != NO_ERROR)
1379 return mInitCheck;
1380
Peng Xu755c4512016-04-07 23:15:14 -07001381 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1382 if (sensor == nullptr ||
1383 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001384 return BAD_VALUE;
1385 }
1386
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001387 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001388 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001389 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001390 return INVALID_OPERATION;
1391 }
1392
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001393 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001394 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001395 rec = new SensorRecord(connection);
1396 mActiveSensors.add(handle, rec);
1397 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001398 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001399 }
1400 } else {
1401 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001402 // this sensor is already activated, but we are adding a connection that uses it.
1403 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001404 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001405 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001406 // NOTE: The wake_up flag of this event may get set to
1407 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001408
1409 auto logger = mRecentEvent.find(handle);
1410 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001411 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001412 // Verify that the last sensor event was generated from the current activation
1413 // of the sensor. If not, it is possible for an on-change sensor to receive a
1414 // sensor event that is stale if two clients re-activate the sensor
1415 // simultaneously.
1416 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001417 event.sensor = handle;
1418 if (event.version == sizeof(sensors_event_t)) {
1419 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1420 setWakeLockAcquiredLocked(true);
1421 }
Yi Kong8f313e32018-07-17 14:13:29 -07001422 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001423 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1424 checkWakeLockStateLocked();
1425 }
1426 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001427 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001428 }
1429 }
1430 }
1431 }
1432
1433 if (connection->addSensor(handle)) {
1434 BatteryService::enableSensor(connection->getUid(), handle);
1435 // the sensor was added (which means it wasn't already there)
1436 // so, see if this connection becomes active
1437 if (mActiveConnections.indexOf(connection) < 0) {
1438 mActiveConnections.add(connection);
1439 }
1440 } else {
1441 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1442 handle, connection.get());
1443 }
1444
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301445 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001446 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301447 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1448 samplingPeriodNs = maxDelayNs;
1449 }
1450
Aravind Akella724d91d2013-06-27 12:04:23 -07001451 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1452 if (samplingPeriodNs < minDelayNs) {
1453 samplingPeriodNs = minDelayNs;
1454 }
1455
Aravind Akella6c2664a2014-08-13 12:24:50 -07001456 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1457 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001458 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1459
Aravind Akella4949c502015-02-11 15:54:35 -08001460 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001461 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001462
Peng Xu20483c42015-10-26 15:14:43 -07001463 // Call flush() before calling activate() on the sensor. Wait for a first
1464 // flush complete event before sending events on this connection. Ignore
1465 // one-shot sensors which don't support flush(). Ignore on-change sensors
1466 // to maintain the on-change logic (any on-change events except the initial
1467 // one should be trigger by a change in value). Also if this sensor isn't
1468 // already active, don't call flush().
1469 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001470 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001471 rec->getNumConnections() > 1) {
1472 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001473 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001474 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001475 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001476 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001477 } else {
1478 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001479 }
1480 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001481
1482 if (err == NO_ERROR) {
1483 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1484 err = sensor->activate(connection.get(), true);
1485 }
1486
Aravind Akella8a969552014-09-28 17:52:41 -07001487 if (err == NO_ERROR) {
1488 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001489
1490 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1491 SensorRegistrationInfo(handle, connection->getPackageName(),
1492 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001493 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001494 }
1495
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001496 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001497 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001498 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001499 }
1500 return err;
1501}
1502
Peng Xu47e96012016-03-28 17:55:56 -07001503status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001504 if (mInitCheck != NO_ERROR)
1505 return mInitCheck;
1506
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001507 Mutex::Autolock _l(mLock);
1508 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001509 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001510 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1511 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001512
1513 }
1514 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001515 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1516 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001517 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001518 }
1519 return err;
1520}
1521
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001522status_t SensorService::cleanupWithoutDisable(
1523 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001524 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001525 return cleanupWithoutDisableLocked(connection, handle);
1526}
1527
1528status_t SensorService::cleanupWithoutDisableLocked(
1529 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001530 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001531 if (rec) {
1532 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001533 if (connection->removeSensor(handle)) {
1534 BatteryService::disableSensor(connection->getUid(), handle);
1535 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001536 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001537 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001538 mActiveConnections.remove(connection);
1539 }
1540 // see if this sensor becomes inactive
1541 if (rec->removeConnection(connection)) {
1542 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001543 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001544 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001545 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001546 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001547 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001548 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001549}
1550
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001551status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001552 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001553 if (mInitCheck != NO_ERROR)
1554 return mInitCheck;
1555
Peng Xu755c4512016-04-07 23:15:14 -07001556 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1557 if (sensor == nullptr ||
1558 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001559 return BAD_VALUE;
1560 }
1561
Mathias Agopian1cd70002010-07-21 15:59:50 -07001562 if (ns < 0)
1563 return BAD_VALUE;
1564
Mathias Agopian62569ec2011-11-07 21:21:47 -08001565 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1566 if (ns < minDelayNs) {
1567 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001568 }
1569
Mathias Agopianf001c922010-11-11 17:58:51 -08001570 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001571}
1572
Svetoslavb412f6e2015-04-29 16:50:41 -07001573status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1574 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001575 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001576 SensorDevice& dev(SensorDevice::getInstance());
1577 const int halVersion = dev.getHalDeviceVersion();
1578 status_t err(NO_ERROR);
1579 Mutex::Autolock _l(mLock);
1580 // Loop through all sensors for this connection and call flush on each of them.
1581 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1582 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001583 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1584 if (sensor == nullptr) {
1585 continue;
1586 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001587 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1588 ALOGE("flush called on a one-shot sensor");
1589 err = INVALID_OPERATION;
1590 continue;
1591 }
Aravind Akella8493b792014-09-08 15:45:47 -07001592 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001593 // For older devices just increment pending flush count which will send a trivial
1594 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001595 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001596 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001597 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1598 err = INVALID_OPERATION;
1599 continue;
1600 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001601 status_t err_flush = sensor->flush(connection.get(), handle);
1602 if (err_flush == NO_ERROR) {
1603 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001604 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001605 }
1606 err = (err_flush != NO_ERROR) ? err_flush : err;
1607 }
Aravind Akella70018042014-04-07 22:52:37 +00001608 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001609 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001610}
Aravind Akella70018042014-04-07 22:52:37 +00001611
Svetoslavb412f6e2015-04-29 16:50:41 -07001612bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1613 const String16& opPackageName) {
1614 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001615
Svetoslavb412f6e2015-04-29 16:50:41 -07001616 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001617 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001618 }
1619
1620 bool hasPermission = false;
1621
1622 // Runtime permissions can't use the cache as they may change.
1623 if (sensor.isRequiredPermissionRuntime()) {
1624 hasPermission = checkPermission(String16(requiredPermission),
1625 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001626 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001627 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1628 }
1629
1630 if (!hasPermission) {
1631 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1632 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001633 return false;
1634 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001635
1636 const int32_t opCode = sensor.getRequiredAppOp();
1637 if (opCode >= 0) {
1638 AppOpsManager appOps;
1639 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1640 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001641 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001642 operation, sensor.getName().string(), opCode);
1643 return false;
1644 }
1645 }
1646
1647 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001648}
1649
Aravind Akella9a844cf2014-02-11 18:58:52 -08001650void SensorService::checkWakeLockState() {
1651 Mutex::Autolock _l(mLock);
1652 checkWakeLockStateLocked();
1653}
1654
1655void SensorService::checkWakeLockStateLocked() {
1656 if (!mWakeLockAcquired) {
1657 return;
1658 }
1659 bool releaseLock = true;
1660 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1661 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001662 if (connection != nullptr) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001663 if (connection->needsWakeLock()) {
1664 releaseLock = false;
1665 break;
1666 }
1667 }
1668 }
1669 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001670 setWakeLockAcquiredLocked(false);
1671 }
1672}
1673
1674void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1675 Mutex::Autolock _l(mLock);
1676 connection->writeToSocketFromCache();
1677 if (connection->needsWakeLock()) {
1678 setWakeLockAcquiredLocked(true);
1679 }
1680}
1681
1682void SensorService::populateActiveConnections(
1683 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1684 Mutex::Autolock _l(mLock);
1685 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1686 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001687 if (connection != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001688 activeConnections->add(connection);
1689 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001690 }
1691}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001692
Aravind Akella4949c502015-02-11 15:54:35 -08001693bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001694 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001695}
1696
Peng Xue36e3472016-11-03 11:57:10 -07001697bool SensorService::isOperationRestricted(const String16& opPackageName) {
1698 Mutex::Autolock _l(mLock);
1699 if (mCurrentOperatingMode != RESTRICTED) {
1700 String8 package(opPackageName);
1701 return !isWhiteListedPackage(package);
1702 }
1703 return false;
1704}
1705
Svet Ganove752a5c2018-01-15 17:14:20 -08001706void SensorService::UidPolicy::registerSelf() {
1707 ActivityManager am;
1708 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1709 | ActivityManager::UID_OBSERVER_IDLE
1710 | ActivityManager::UID_OBSERVER_ACTIVE,
1711 ActivityManager::PROCESS_STATE_UNKNOWN,
1712 String16("android"));
1713}
1714
1715void SensorService::UidPolicy::unregisterSelf() {
1716 ActivityManager am;
1717 am.unregisterUidObserver(this);
1718}
1719
1720void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1721 onUidIdle(uid, disabled);
1722}
1723
1724void SensorService::UidPolicy::onUidActive(uid_t uid) {
1725 {
1726 Mutex::Autolock _l(mUidLock);
1727 mActiveUids.insert(uid);
1728 }
1729 sp<SensorService> service = mService.promote();
1730 if (service != nullptr) {
1731 service->setSensorAccess(uid, true);
1732 }
1733}
1734
1735void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1736 bool deleted = false;
1737 {
1738 Mutex::Autolock _l(mUidLock);
1739 if (mActiveUids.erase(uid) > 0) {
1740 deleted = true;
1741 }
1742 }
1743 if (deleted) {
1744 sp<SensorService> service = mService.promote();
1745 if (service != nullptr) {
1746 service->setSensorAccess(uid, false);
1747 }
1748 }
1749}
1750
1751void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1752 updateOverrideUid(uid, active, true);
1753}
1754
1755void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1756 updateOverrideUid(uid, false, false);
1757}
1758
1759void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1760 bool wasActive = false;
1761 bool isActive = false;
1762 {
1763 Mutex::Autolock _l(mUidLock);
1764 wasActive = isUidActiveLocked(uid);
1765 mOverrideUids.erase(uid);
1766 if (insert) {
1767 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1768 }
1769 isActive = isUidActiveLocked(uid);
1770 }
1771 if (wasActive != isActive) {
1772 sp<SensorService> service = mService.promote();
1773 if (service != nullptr) {
1774 service->setSensorAccess(uid, isActive);
1775 }
1776 }
1777}
1778
1779bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1780 // Non-app UIDs are considered always active
1781 if (uid < FIRST_APPLICATION_UID) {
1782 return true;
1783 }
1784 Mutex::Autolock _l(mUidLock);
1785 return isUidActiveLocked(uid);
1786}
1787
1788bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1789 // Non-app UIDs are considered always active
1790 if (uid < FIRST_APPLICATION_UID) {
1791 return true;
1792 }
1793 auto it = mOverrideUids.find(uid);
1794 if (it != mOverrideUids.end()) {
1795 return it->second;
1796 }
1797 return mActiveUids.find(uid) != mActiveUids.end();
1798}
1799
Michael Groover5e1f60b2018-12-04 22:34:29 -08001800void SensorService::SensorPrivacyPolicy::registerSelf() {
1801 SensorPrivacyManager spm;
1802 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1803 spm.addSensorPrivacyListener(this);
1804}
1805
1806void SensorService::SensorPrivacyPolicy::unregisterSelf() {
1807 SensorPrivacyManager spm;
1808 spm.removeSensorPrivacyListener(this);
1809}
1810
1811bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1812 return mSensorPrivacyEnabled;
1813}
1814
1815binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1816 mSensorPrivacyEnabled = enabled;
1817 sp<SensorService> service = mService.promote();
1818 if (service != nullptr) {
1819 if (enabled) {
1820 service->disableAllSensors();
1821 } else {
1822 service->enableAllSensors();
1823 }
1824 }
1825 return binder::Status::ok();
1826}
Mathias Agopianfc328812010-07-14 23:41:37 -07001827}; // namespace android