blob: 7c56e5cc4c7312848e44d8dc2edf06b7d6cd7941 [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>
32#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070033
Mathias Agopian787ac1b2012-09-18 18:49:18 -070034#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070035#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080036#include "GravitySensor.h"
37#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070038#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080039#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070040#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070041#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080042
Mathias Agopian984826c2011-05-17 22:54:42 -070043#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070044#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080045#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080046#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080047#include "SensorRecord.h"
48#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080049
50#include <inttypes.h>
51#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070052#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080053#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080054#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070055#include <sys/stat.h>
56#include <sys/types.h>
57#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070058
Svet Ganove752a5c2018-01-15 17:14:20 -080059#include <private/android_filesystem_config.h>
60
Mathias Agopianfc328812010-07-14 23:41:37 -070061namespace android {
62// ---------------------------------------------------------------------------
63
Mathias Agopian33015422011-05-27 18:18:13 -070064/*
65 * Notes:
66 *
67 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070068 * - run mag sensor from time to time to force calibration
69 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
70 *
71 */
72
Aravind Akella8ef3c892015-07-10 11:24:28 -070073const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070074uint8_t SensorService::sHmacGlobalKey[128] = {};
75bool SensorService::sHmacGlobalKeyIsValid = false;
76
77#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
78#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070079#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070080
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070081// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070082static const String16 sDumpPermission("android.permission.DUMP");
83static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080084static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070085
Mathias Agopianfc328812010-07-14 23:41:37 -070086SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070087 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070088 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +090089 mUidPolicy = new UidPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -070090}
91
Greg Kaiser53ca2e02016-06-21 16:11:14 -070092bool SensorService::initializeHmacKey() {
93 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
94 if (fd != -1) {
95 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
96 close(fd);
97 if (result == sizeof(sHmacGlobalKey)) {
98 return true;
99 }
100 ALOGW("Unable to read HMAC key; generating new one.");
101 }
102
103 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
104 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
105 return false;
106 }
107
108 // We need to make sure this is only readable to us.
109 bool wroteKey = false;
110 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
111 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
112 S_IRUSR|S_IWUSR);
113 if (fd != -1) {
114 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
115 close(fd);
116 wroteKey = (result == sizeof(sHmacGlobalKey));
117 }
118 if (wroteKey) {
119 ALOGI("Generated new HMAC key.");
120 } else {
121 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
122 "after reboot.");
123 }
124 // Even if we failed to write the key we return true, because we did
125 // initialize the HMAC key.
126 return true;
127}
128
Peng Xu98d30f62016-08-01 18:12:11 -0700129// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
130void SensorService::enableSchedFifoMode() {
131 struct sched_param param = {0};
132 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
133 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
134 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
135 }
136}
137
Peng Xu47e96012016-03-28 17:55:56 -0700138void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000139 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800140 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700141
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700142 sHmacGlobalKeyIsValid = initializeHmacKey();
143
Mathias Agopianf001c922010-11-11 17:58:51 -0800144 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800145 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700146 ssize_t count = dev.getSensorList(&list);
147 if (count > 0) {
148 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700149 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700150 uint32_t virtualSensorsNeeds =
151 (1<<SENSOR_TYPE_GRAVITY) |
152 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700153 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
154 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
155 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700156
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700157 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700158 bool useThisSensor=true;
159
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700160 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700161 case SENSOR_TYPE_ACCELEROMETER:
162 hasAccel = true;
163 break;
164 case SENSOR_TYPE_MAGNETIC_FIELD:
165 hasMag = true;
166 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700167 case SENSOR_TYPE_ORIENTATION:
168 orientationIndex = i;
169 break;
170 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700171 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700172 hasGyro = true;
173 break;
174 case SENSOR_TYPE_GRAVITY:
175 case SENSOR_TYPE_LINEAR_ACCELERATION:
176 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700177 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
178 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
179 if (IGNORE_HARDWARE_FUSION) {
180 useThisSensor = false;
181 } else {
182 virtualSensorsNeeds &= ~(1<<list[i].type);
183 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700184 break;
185 }
Peng Xuf66684a2015-07-23 11:41:53 -0700186 if (useThisSensor) {
187 registerSensor( new HardwareSensor(list[i]) );
188 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700189 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700190
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700191 // it's safe to instantiate the SensorFusion object here
192 // (it wants to be instantiated after h/w sensors have been
193 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700194 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700195
Aravind Akellaf5047892015-07-20 17:29:33 -0700196 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700197 // Add Android virtual sensors if they're not already
198 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700199 bool needRotationVector =
200 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700201
Peng Xu0cc8f802016-04-05 23:46:03 -0700202 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
203 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700204
Peng Xu0cc8f802016-04-05 23:46:03 -0700205 bool needLinearAcceleration =
206 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700207
Peng Xu0cc8f802016-04-05 23:46:03 -0700208 registerSensor(new LinearAccelerationSensor(list, count),
209 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700210
Peng Xu0cc8f802016-04-05 23:46:03 -0700211 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700212 registerSensor( new CorrectedGyroSensor(list, count), true, true);
213 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700214 }
215
Peng Xuf66684a2015-07-23 11:41:53 -0700216 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700217 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
218 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700219
Peng Xu0cc8f802016-04-05 23:46:03 -0700220 bool needGameRotationVector =
221 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
222 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700223 }
224
225 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700226 bool needGeoMagRotationVector =
227 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
228 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700229 }
230
Aravind Akella5466c3d2014-08-22 16:11:10 -0700231 // Check if the device really supports batching by looking at the FIFO event
232 // counts for each sensor.
233 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700234 mSensors.forEachSensor(
235 [&batchingSupported] (const Sensor& s) -> bool {
236 if (s.getFifoMaxEventCount() > 0) {
237 batchingSupported = true;
238 }
239 return !batchingSupported;
240 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700241
242 if (batchingSupported) {
243 // Increase socket buffer size to a max of 100 KB for batching capabilities.
244 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
245 } else {
246 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
247 }
248
249 // Compare the socketBufferSize value against the system limits and limit
250 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700251 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
252 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700253 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700254 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700255 size_t maxSystemSocketBufferSize;
256 sscanf(line, "%zu", &maxSystemSocketBufferSize);
257 if (mSocketBufferSize > maxSystemSocketBufferSize) {
258 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700259 }
260 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700261 if (fp) {
262 fclose(fp);
263 }
264
Aravind Akella9a844cf2014-02-11 18:58:52 -0800265 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700266 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700267 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
268 mSensorEventBuffer = new sensors_event_t[minBufferSize];
269 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700270 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700271 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700272
Aravind Akella18d6d512015-06-18 14:18:28 -0700273 mNextSensorRegIndex = 0;
274 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
275 mLastNSensorRegistrations.push();
276 }
277
278 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700279 mAckReceiver = new SensorEventAckReceiver(this);
280 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700281 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700282
283 // priority can only be changed after run
284 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800285
286 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800287 mUidPolicy->registerSelf();
288 }
289 }
290}
291
292void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
293 SortedVector< sp<SensorEventConnection> > activeConnections;
294 populateActiveConnections(&activeConnections);
295 {
296 Mutex::Autolock _l(mLock);
297 for (size_t i = 0 ; i < activeConnections.size(); i++) {
Yi Kong8f313e32018-07-17 14:13:29 -0700298 if (activeConnections[i] != nullptr && activeConnections[i]->getUid() == uid) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800299 activeConnections[i]->setSensorAccess(hasAccess);
300 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700301 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700302 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700303}
304
Peng Xu0cc8f802016-04-05 23:46:03 -0700305const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
306 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800307 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700308 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700309 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700310 return s->getSensor();
311 } else {
312 return mSensors.getNonSensor();
313 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800314}
315
Peng Xu6a2d3a02015-12-21 12:00:23 -0800316const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700317 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800318}
319
Peng Xu6a2d3a02015-12-21 12:00:23 -0800320bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700321 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800322
323 const auto i = mRecentEvent.find(handle);
324 if (i != mRecentEvent.end()) {
325 delete i->second;
326 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800327 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700328 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800329}
330
Peng Xu0cc8f802016-04-05 23:46:03 -0700331const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
332 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700333}
334
Peng Xu47e96012016-03-28 17:55:56 -0700335SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800336 for (auto && entry : mRecentEvent) {
337 delete entry.second;
338 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800339 mUidPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700340}
341
342status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700343 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700344 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800345 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700346 IPCThreadState::self()->getCallingPid(),
347 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700348 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700349 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700350 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800351 return INVALID_OPERATION;
352 }
353 Mutex::Autolock _l(mLock);
354 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700355 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700356 // If already in restricted mode. Ignore.
357 if (mCurrentOperatingMode == RESTRICTED) {
358 return status_t(NO_ERROR);
359 }
360 // If in any mode other than normal, ignore.
361 if (mCurrentOperatingMode != NORMAL) {
362 return INVALID_OPERATION;
363 }
Peng Xue36e3472016-11-03 11:57:10 -0700364
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700365 mCurrentOperatingMode = RESTRICTED;
Peng Xue36e3472016-11-03 11:57:10 -0700366 // temporarily stop all sensor direct report
367 for (auto &i : mDirectConnections) {
368 sp<SensorDirectConnection> connection(i.promote());
369 if (connection != nullptr) {
370 connection->stopAll(true /* backupRecord */);
371 }
372 }
373
Aravind Akella4949c502015-02-11 15:54:35 -0800374 dev.disableAllSensors();
375 // Clear all pending flush connections for all active sensors. If one of the active
376 // connections has called flush() and the underlying sensor has been disabled before a
377 // flush complete event is returned, we need to remove the connection from this queue.
378 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
379 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
380 }
Aravind Akella841a5922015-06-29 12:37:48 -0700381 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700382 return status_t(NO_ERROR);
383 } else if (args.size() == 1 && args[0] == String16("enable")) {
384 // If currently in restricted mode, reset back to NORMAL mode else ignore.
385 if (mCurrentOperatingMode == RESTRICTED) {
386 mCurrentOperatingMode = NORMAL;
387 dev.enableAllSensors();
Peng Xue36e3472016-11-03 11:57:10 -0700388 // recover all sensor direct report
389 for (auto &i : mDirectConnections) {
390 sp<SensorDirectConnection> connection(i.promote());
391 if (connection != nullptr) {
392 connection->recoverAll();
393 }
394 }
Aravind Akella444f2672015-05-07 12:40:52 -0700395 }
Aravind Akella841a5922015-06-29 12:37:48 -0700396 if (mCurrentOperatingMode == DATA_INJECTION) {
397 resetToNormalModeLocked();
398 }
399 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700400 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700401 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
402 if (mCurrentOperatingMode == NORMAL) {
403 dev.disableAllSensors();
404 status_t err = dev.setMode(DATA_INJECTION);
405 if (err == NO_ERROR) {
406 mCurrentOperatingMode = DATA_INJECTION;
407 } else {
408 // Re-enable sensors.
409 dev.enableAllSensors();
410 }
411 mWhiteListedPackage.setTo(String8(args[1]));
412 return NO_ERROR;
413 } else if (mCurrentOperatingMode == DATA_INJECTION) {
414 // Already in DATA_INJECTION mode. Treat this as a no_op.
415 return NO_ERROR;
416 } else {
417 // Transition to data injection mode supported only from NORMAL mode.
418 return INVALID_OPERATION;
419 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700420 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700421 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700422 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700423 } else {
424 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700425 //
Peng Xu6a2d3a02015-12-21 12:00:23 -0800426 result.append("Sensor Device:\n");
427 result.append(SensorDevice::getInstance().dump().c_str());
428
429 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700430 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700431
Peng Xu6a2d3a02015-12-21 12:00:23 -0800432 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700433 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700434
Peng Xu0cc8f802016-04-05 23:46:03 -0700435 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800436 for (auto&& i : mRecentEvent) {
437 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700438 if (!i.second->isEmpty()) {
439 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
440 i.second->setFormat("normal");
441 } else {
442 i.second->setFormat("mask_data");
443 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800444 // if there is events and sensor does not need special permission.
445 result.appendFormat("%s: ", s->getSensor().getName().string());
446 result.append(i.second->dump().c_str());
447 }
448 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700449
Aravind Akella444f2672015-05-07 12:40:52 -0700450 result.append("Active sensors:\n");
451 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
452 int handle = mActiveSensors.keyAt(i);
453 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
454 getSensorName(handle).string(),
455 handle,
456 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700457 }
458
Andreas Gamped4036b62015-07-28 13:49:04 -0700459 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700460 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700461 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
462 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700463 result.appendFormat("Mode :");
464 switch(mCurrentOperatingMode) {
465 case NORMAL:
466 result.appendFormat(" NORMAL\n");
467 break;
468 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700469 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700470 break;
471 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700472 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700473 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700474
Peng Xue36e3472016-11-03 11:57:10 -0700475 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella444f2672015-05-07 12:40:52 -0700476 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
477 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -0700478 if (connection != nullptr) {
Aravind Akella444f2672015-05-07 12:40:52 -0700479 result.appendFormat("Connection Number: %zu \n", i);
480 connection->dump(result);
481 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700482 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700483
Peng Xue36e3472016-11-03 11:57:10 -0700484 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
485 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
486 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
487 if (connection != nullptr) {
488 result.appendFormat("Direct connection %zu:\n", i);
489 connection->dump(result);
490 }
491 }
492
Aravind Akella18d6d512015-06-18 14:18:28 -0700493 result.appendFormat("Previous Registrations:\n");
494 // Log in the reverse chronological order.
495 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
496 SENSOR_REGISTRATIONS_BUF_SIZE;
497 const int startIndex = currentIndex;
498 do {
499 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
500 if (SensorRegistrationInfo::isSentinel(reg_info)) {
501 // Ignore sentinel, proceed to next item.
502 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
503 SENSOR_REGISTRATIONS_BUF_SIZE;
504 continue;
505 }
Peng Xu51224682017-03-10 16:57:27 -0800506 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700507 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
508 SENSOR_REGISTRATIONS_BUF_SIZE;
509 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700510 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700511 }
512 write(fd, result.string(), result.size());
513 return NO_ERROR;
514}
515
Svet Ganove752a5c2018-01-15 17:14:20 -0800516// NOTE: This is a remote API - make sure all args are validated
517status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
518 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
519 return PERMISSION_DENIED;
520 }
521 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
522 return BAD_VALUE;
523 }
524 if (args.size() == 3 && args[0] == String16("set-uid-state")) {
525 return handleSetUidState(args, err);
526 } else if (args.size() == 2 && args[0] == String16("reset-uid-state")) {
527 return handleResetUidState(args, err);
528 } else if (args.size() == 2 && args[0] == String16("get-uid-state")) {
529 return handleGetUidState(args, out, err);
530 } else if (args.size() == 1 && args[0] == String16("help")) {
531 printHelp(out);
532 return NO_ERROR;
533 }
534 printHelp(err);
535 return BAD_VALUE;
536}
537
538status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
539 PermissionController pc;
540 int uid = pc.getPackageUid(args[1], 0);
541 if (uid <= 0) {
542 ALOGE("Unknown package: '%s'", String8(args[1]).string());
543 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
544 return BAD_VALUE;
545 }
546 bool active = false;
547 if (args[2] == String16("active")) {
548 active = true;
549 } else if ((args[2] != String16("idle"))) {
550 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
551 return BAD_VALUE;
552 }
553 mUidPolicy->addOverrideUid(uid, active);
554 return NO_ERROR;
555}
556
557status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
558 PermissionController pc;
559 int uid = pc.getPackageUid(args[1], 0);
560 if (uid < 0) {
561 ALOGE("Unknown package: '%s'", String8(args[1]).string());
562 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
563 return BAD_VALUE;
564 }
565 mUidPolicy->removeOverrideUid(uid);
566 return NO_ERROR;
567}
568
569status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
570 PermissionController pc;
571 int uid = pc.getPackageUid(args[1], 0);
572 if (uid < 0) {
573 ALOGE("Unknown package: '%s'", String8(args[1]).string());
574 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
575 return BAD_VALUE;
576 }
577 if (mUidPolicy->isUidActive(uid)) {
578 return dprintf(out, "active\n");
579 } else {
580 return dprintf(out, "idle\n");
581 }
582}
583
584status_t SensorService::printHelp(int out) {
585 return dprintf(out, "Sensor service commands:\n"
586 " get-uid-state <PACKAGE> gets the uid state\n"
587 " set-uid-state <PACKAGE> <active|idle> overrides the uid state\n"
588 " reset-uid-state <PACKAGE> clears the uid state override\n"
589 " help print this message\n");
590}
591
Peng Xu0cc8f802016-04-05 23:46:03 -0700592//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800593void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700594 sensors_event_t const* buffer, const int count) {
595 for (int i=0 ; i<count ; i++) {
596 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700597 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
598 handle = buffer[i].meta_data.sensor;
599 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700600 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700601 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700602 // If this buffer has an event from a one_shot sensor and this connection is registered
603 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700604 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700605 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
606 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800607 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700608 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700609
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700610 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700611 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700612}
613
Peng Xu47e96012016-03-28 17:55:56 -0700614bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000615 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700616
Peng Xueb4d6282015-12-10 18:02:41 -0800617 // each virtual sensor could generate an event per "real" event, that's why we need to size
618 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
619 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700620 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700621 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700622 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700623
Mathias Agopianf001c922010-11-11 17:58:51 -0800624 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700625
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700626 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700627 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700628 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
629 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000630 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700631 break;
632 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700633
634 // Reset sensors_event_t.flags to zero for all events in the buffer.
635 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700636 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700637 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700638
Peng Xueb4d6282015-12-10 18:02:41 -0800639 // Make a copy of the connection vector as some connections may be removed during the course
640 // of this loop (especially when one-shot sensor events are present in the sensor_event
641 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
642 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
643 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
644 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700645 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700646 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800647
Aravind Akella9a844cf2014-02-11 18:58:52 -0800648 Mutex::Autolock _l(mLock);
649 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
650 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
651 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
652 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
653 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700654 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700655 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700656 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700657 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700658 }
659 }
660
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700661 if (wakeEvents > 0) {
662 if (!mWakeLockAcquired) {
663 setWakeLockAcquiredLocked(true);
664 }
665 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800666 }
Aravind Akella8493b792014-09-08 15:45:47 -0700667 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800668
Mathias Agopianf001c922010-11-11 17:58:51 -0800669 // handle virtual sensors
670 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700671 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700672 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800673 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700674 SensorFusion& fusion(SensorFusion::getInstance());
675 if (fusion.isEnabled()) {
676 for (size_t i=0 ; i<size_t(count) ; i++) {
677 fusion.process(event[i]);
678 }
679 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700680 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700681 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700682 if (count + k >= minBufferSize) {
683 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700684 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700685 count, k, minBufferSize);
686 break;
687 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800688 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700689 sp<SensorInterface> si = mSensors.getInterface(handle);
690 if (si == nullptr) {
691 ALOGE("handle %d is not an valid virtual sensor", handle);
692 continue;
693 }
694
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700695 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700696 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800697 k++;
698 }
699 }
700 }
701 if (k) {
702 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700703 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800704 count += k;
705 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700706 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700707 }
708 }
709 }
710
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700711 // handle backward compatibility for RotationVector sensor
712 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
713 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700714 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700715 // All the 4 components of the quaternion should be available
716 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700717 mSensorEventBuffer[i].data[4] = -1;
718 }
719 }
720 }
721
Aravind Akella8493b792014-09-08 15:45:47 -0700722 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700723 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
724 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
725 // SensorEventConnection mapped to the corresponding flush_complete_event in
726 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700727 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700728 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
729 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
730 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700731 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700732 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
733 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700734 }
735 }
Peng Xu2576cb62016-01-20 00:22:09 -0800736
737 // handle dynamic sensor meta events, process registration and unregistration of dynamic
738 // sensor based on content of event.
739 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
740 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
741 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
742 const sensor_t& dynamicSensor =
743 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
744 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
745 handle, dynamicSensor.type, dynamicSensor.name);
746
Peng Xu0cc8f802016-04-05 23:46:03 -0700747 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800748 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700749 sensor_t s = dynamicSensor;
750 // make sure the dynamic sensor flag is set
751 s.flags |= DYNAMIC_SENSOR_MASK;
752 // force the handle to be consistent
753 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800754
755 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800756
Peng Xu0cc8f802016-04-05 23:46:03 -0700757 // This will release hold on dynamic sensor meta, so it should be called
758 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700759 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800760 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700761 } else {
762 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
763 }
Peng Xu2576cb62016-01-20 00:22:09 -0800764 } else {
765 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
766 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
767
768 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800769 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800770 ALOGE("Dynamic sensor release error.");
771 }
772
773 size_t numConnections = activeConnections.size();
774 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700775 if (activeConnections[i] != nullptr) {
Peng Xu2576cb62016-01-20 00:22:09 -0800776 activeConnections[i]->removeSensor(handle);
777 }
778 }
779 }
780 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700781 }
782
Aravind Akella9a844cf2014-02-11 18:58:52 -0800783 // Send our events to clients. Check the state of wake lock for each client and release the
784 // lock if none of the clients need it.
785 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700786 size_t numConnections = activeConnections.size();
787 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700788 if (activeConnections[i] != nullptr) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700789 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700790 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700791 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700792 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
793 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700794 if (activeConnections[i]->hasOneShotSensors()) {
795 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
796 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700797 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800798 }
799 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700800
Aravind Akella9a844cf2014-02-11 18:58:52 -0800801 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700802 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800803 }
Aravind Akella8493b792014-09-08 15:45:47 -0700804 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700805
Steve Block3c20fbe2012-01-05 23:22:43 +0000806 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800807 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700808 return false;
809}
810
Aravind Akella56ae4262014-07-10 16:01:10 -0700811sp<Looper> SensorService::getLooper() const {
812 return mLooper;
813}
814
Aravind Akellab4373ac2014-10-29 17:55:20 -0700815void SensorService::resetAllWakeLockRefCounts() {
816 SortedVector< sp<SensorEventConnection> > activeConnections;
817 populateActiveConnections(&activeConnections);
818 {
819 Mutex::Autolock _l(mLock);
820 for (size_t i=0 ; i < activeConnections.size(); ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700821 if (activeConnections[i] != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700822 activeConnections[i]->resetWakeLockRefCount();
823 }
824 }
825 setWakeLockAcquiredLocked(false);
826 }
827}
828
829void SensorService::setWakeLockAcquiredLocked(bool acquire) {
830 if (acquire) {
831 if (!mWakeLockAcquired) {
832 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
833 mWakeLockAcquired = true;
834 }
835 mLooper->wake();
836 } else {
837 if (mWakeLockAcquired) {
838 release_wake_lock(WAKE_LOCK_NAME);
839 mWakeLockAcquired = false;
840 }
841 }
842}
843
Aravind Akellab4373ac2014-10-29 17:55:20 -0700844bool SensorService::isWakeLockAcquired() {
845 Mutex::Autolock _l(mLock);
846 return mWakeLockAcquired;
847}
848
Aravind Akella56ae4262014-07-10 16:01:10 -0700849bool SensorService::SensorEventAckReceiver::threadLoop() {
850 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700851 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700852 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700853 bool wakeLockAcquired = mService->isWakeLockAcquired();
854 int timeout = -1;
855 if (wakeLockAcquired) timeout = 5000;
856 int ret = looper->pollOnce(timeout);
857 if (ret == ALOOPER_POLL_TIMEOUT) {
858 mService->resetAllWakeLockRefCounts();
859 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700860 } while(!Thread::exitPending());
861 return false;
862}
863
Aravind Akella9a844cf2014-02-11 18:58:52 -0800864void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800865 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800866 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800867 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
868 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800869 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800870 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800871 }
Peng Xu2576cb62016-01-20 00:22:09 -0800872
Peng Xu6a2d3a02015-12-21 12:00:23 -0800873 auto logger = mRecentEvent.find(buffer[i].sensor);
874 if (logger != mRecentEvent.end()) {
875 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800876 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800877 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800878}
879
Peng Xu47e96012016-03-28 17:55:56 -0700880void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800881 struct compar {
882 static int cmp(void const* lhs, void const* rhs) {
883 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
884 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700885 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800886 }
887 };
888 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
889}
890
Mathias Agopian5d270722010-07-19 15:20:39 -0700891String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700892 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700893}
894
Aravind Akellab4099e72013-10-15 15:43:10 -0700895bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700896 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
897 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700898}
899
Aravind Akella9a844cf2014-02-11 18:58:52 -0800900bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700901 int handle = event.sensor;
902 if (event.type == SENSOR_TYPE_META_DATA) {
903 handle = event.meta_data.sensor;
904 }
Peng Xu755c4512016-04-07 23:15:14 -0700905 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
906 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800907}
908
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700909int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
910 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
911 // UUID is not supported for this device.
912 return 0;
913 }
914 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
915 // This sensor can be uniquely identified in the system by
916 // the combination of its type and name.
917 return -1;
918 }
919
920 // We have a dynamic sensor.
921
922 if (!sHmacGlobalKeyIsValid) {
923 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
924 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
925 return 0;
926 }
927
928 // We want each app author/publisher to get a different ID, so that the
929 // same dynamic sensor cannot be tracked across apps by multiple
930 // authors/publishers. So we use both our UUID and our User ID.
931 // Note potential confusion:
932 // UUID => Universally Unique Identifier.
933 // UID => User Identifier.
934 // We refrain from using "uid" except as needed by API to try to
935 // keep this distinction clear.
936
937 auto appUserId = IPCThreadState::self()->getCallingUid();
938 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
939 memcpy(uuidAndApp, &uuid, sizeof(uuid));
940 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
941
942 // Now we use our key on our UUID/app combo to get the hash.
943 uint8_t hash[EVP_MAX_MD_SIZE];
944 unsigned int hashLen;
945 if (HMAC(EVP_sha256(),
946 sHmacGlobalKey, sizeof(sHmacGlobalKey),
947 uuidAndApp, sizeof(uuidAndApp),
948 hash, &hashLen) == nullptr) {
949 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
950 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
951 return 0;
952 }
953
954 int32_t id = 0;
955 if (hashLen < sizeof(id)) {
956 // We never expect this case, but out of paranoia, we handle it.
957 // Our 'id' length is already quite small, we don't want the
958 // effective length of it to be even smaller.
959 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
960 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
961 return 0;
962 }
963
964 // This is almost certainly less than all of 'hash', but it's as secure
965 // as we can be with our current 'id' length.
966 memcpy(&id, hash, sizeof(id));
967
968 // Note at the beginning of the function that we return the values of
969 // 0 and -1 to represent special cases. As a result, we can't return
970 // those as dynamic sensor IDs. If we happened to hash to one of those
971 // values, we change 'id' so we report as a dynamic sensor, and not as
972 // one of those special cases.
973 if (id == -1) {
974 id = -2;
975 } else if (id == 0) {
976 id = 1;
977 }
978 return id;
979}
980
981void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
982 for (auto &sensor : sensorList) {
983 int32_t id = getIdFromUuid(sensor.getUuid());
984 sensor.setId(id);
985 }
986}
987
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800988Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -0700989 char value[PROPERTY_VALUE_MAX];
990 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000991 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700992 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000993 Vector<Sensor> accessibleSensorList;
994 for (size_t i = 0; i < initialSensorList.size(); i++) {
995 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800996 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -0700997 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700998 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +0000999 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001000}
1001
Peng Xu47e96012016-03-28 17:55:56 -07001002Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001003 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001004 mSensors.forEachSensor(
1005 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001006 if (sensor.isDynamicSensor()) {
1007 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1008 accessibleSensorList.add(sensor);
1009 } else {
1010 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1011 sensor.getName().string(),
1012 sensor.getRequiredPermission().string(),
1013 sensor.getRequiredAppOp());
1014 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001015 }
1016 return true;
1017 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001018 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001019 return accessibleSensorList;
1020}
1021
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001022sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001023 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001024 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1025 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001026 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001027 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001028
1029 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001030 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1031 // operating in DI mode.
1032 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001033 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1034 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001035 }
1036
Mathias Agopian5307d172012-09-18 17:02:43 -07001037 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001038 pid_t pid = IPCThreadState::self()->getCallingPid();
1039
1040 String8 connPackageName =
1041 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1042 String16 connOpPackageName =
1043 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001044 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001045 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001046 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001047 if (requestedMode == DATA_INJECTION) {
1048 if (mActiveConnections.indexOf(result) < 0) {
1049 mActiveConnections.add(result);
1050 }
1051 // Add the associated file descriptor to the Looper for polling whenever there is data to
1052 // be injected.
1053 result->updateLooperRegistration(mLooper);
1054 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001055 return result;
1056}
1057
Aravind Akella841a5922015-06-29 12:37:48 -07001058int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001059 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001060 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001061}
1062
Peng Xue36e3472016-11-03 11:57:10 -07001063sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1064 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1065 const native_handle *resource) {
1066 Mutex::Autolock _l(mLock);
1067
1068 struct sensors_direct_mem_t mem = {
1069 .type = type,
1070 .format = format,
1071 .size = size,
1072 .handle = resource,
1073 };
1074 uid_t uid = IPCThreadState::self()->getCallingUid();
1075
1076 if (mem.handle == nullptr) {
1077 ALOGE("Failed to clone resource handle");
1078 return nullptr;
1079 }
1080
1081 // check format
1082 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1083 ALOGE("Direct channel format %d is unsupported!", format);
1084 return nullptr;
1085 }
1086
1087 // check for duplication
1088 for (auto &i : mDirectConnections) {
1089 sp<SensorDirectConnection> connection(i.promote());
1090 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001091 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001092 return nullptr;
1093 }
1094 }
1095
1096 // check specific to memory type
1097 switch(type) {
1098 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001099 if (resource->numFds < 1) {
1100 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1101 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1102 return nullptr;
1103 }
Peng Xue36e3472016-11-03 11:57:10 -07001104 int fd = resource->data[0];
1105 int size2 = ashmem_get_size_region(fd);
1106 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001107 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001108 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1109 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001110 return nullptr;
1111 }
1112 break;
1113 }
1114 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001115 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001116 break;
1117 default:
1118 ALOGE("Unknown direct connection memory type %d", type);
1119 return nullptr;
1120 }
1121
1122 native_handle_t *clone = native_handle_clone(resource);
1123 if (!clone) {
1124 return nullptr;
1125 }
1126
1127 SensorDirectConnection* conn = nullptr;
1128 SensorDevice& dev(SensorDevice::getInstance());
1129 int channelHandle = dev.registerDirectChannel(&mem);
1130
1131 if (channelHandle <= 0) {
1132 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1133 } else {
1134 mem.handle = clone;
1135 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1136 }
1137
1138 if (conn == nullptr) {
1139 native_handle_close(clone);
1140 native_handle_delete(clone);
1141 } else {
1142 // add to list of direct connections
1143 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1144 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1145 }
1146 return conn;
1147}
1148
Peng Xudd5c5cb2017-03-16 17:39:43 -07001149int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001150 int32_t handle, int32_t type,
1151 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001152 Mutex::Autolock _l(mLock);
1153
Alexey Polyudov88711e82017-05-23 19:54:04 -07001154 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001155 return PERMISSION_DENIED;
1156 }
1157
1158 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001159 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001160 size_t expectSize = INT32_MAX;
1161 switch (type) {
1162 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1163 isFloat = true;
1164 expectSize = 3;
1165 break;
1166 case AINFO_LOCAL_GRAVITY:
1167 isFloat = true;
1168 expectSize = 1;
1169 break;
1170 case AINFO_DOCK_STATE:
1171 case AINFO_HIGH_PERFORMANCE_MODE:
1172 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1173 isFloat = false;
1174 expectSize = 1;
1175 break;
1176 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001177 // CUSTOM events must only contain float data; it may have variable size
1178 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1179 ints.size() ||
1180 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1181 handle < 0) {
1182 return BAD_VALUE;
1183 }
1184 isFloat = true;
1185 isCustom = true;
1186 expectSize = floats.size();
1187 break;
1188 }
1189
1190 if (!isCustom && handle != -1) {
1191 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001192 }
1193
1194 // three events: first one is begin tag, last one is end tag, the one in the middle
1195 // is the payload.
1196 sensors_event_t event[3];
1197 int64_t timestamp = elapsedRealtimeNano();
1198 for (sensors_event_t* i = event; i < event + 3; i++) {
1199 *i = (sensors_event_t) {
1200 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001201 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001202 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1203 .timestamp = timestamp++,
1204 .additional_info = (additional_info_event_t) {
1205 .serial = 0
1206 }
1207 };
1208 }
1209
1210 event[0].additional_info.type = AINFO_BEGIN;
1211 event[1].additional_info.type = type;
1212 event[2].additional_info.type = AINFO_END;
1213
1214 if (isFloat) {
1215 if (floats.size() != expectSize) {
1216 return BAD_VALUE;
1217 }
1218 for (size_t i = 0; i < expectSize; ++i) {
1219 event[1].additional_info.data_float[i] = floats[i];
1220 }
1221 } else {
1222 if (ints.size() != expectSize) {
1223 return BAD_VALUE;
1224 }
1225 for (size_t i = 0; i < expectSize; ++i) {
1226 event[1].additional_info.data_int32[i] = ints[i];
1227 }
1228 }
1229
1230 SensorDevice& dev(SensorDevice::getInstance());
1231 for (sensors_event_t* i = event; i < event + 3; i++) {
1232 int ret = dev.injectSensorData(i);
1233 if (ret != NO_ERROR) {
1234 return ret;
1235 }
1236 }
1237 return NO_ERROR;
1238}
1239
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001240status_t SensorService::resetToNormalMode() {
1241 Mutex::Autolock _l(mLock);
1242 return resetToNormalModeLocked();
1243}
1244
1245status_t SensorService::resetToNormalModeLocked() {
1246 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001247 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301248 if (err == NO_ERROR) {
1249 mCurrentOperatingMode = NORMAL;
1250 dev.enableAllSensors();
1251 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001252 return err;
1253}
1254
Peng Xu47e96012016-03-28 17:55:56 -07001255void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001256 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001257 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001258 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001259 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001260 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001261 int handle = mActiveSensors.keyAt(i);
1262 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001263 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001264 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1265 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001266 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001267 } else {
1268 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001269 }
Aravind Akella8a969552014-09-28 17:52:41 -07001270 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001271 }
1272 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001273 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001274 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001275 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001276 c, i, handle);
1277
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001278 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001279 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001280 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001281 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001282 delete rec;
1283 size--;
1284 } else {
1285 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001286 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001287 }
Aravind Akella8a969552014-09-28 17:52:41 -07001288 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001289 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001290 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001291 if (c->needsWakeLock()) {
1292 checkWakeLockStateLocked();
1293 }
Peng Xu4f707f82016-09-26 11:28:32 -07001294
1295 SensorDevice& dev(SensorDevice::getInstance());
1296 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001297}
1298
Peng Xue36e3472016-11-03 11:57:10 -07001299void SensorService::cleanupConnection(SensorDirectConnection* c) {
1300 Mutex::Autolock _l(mLock);
1301
1302 SensorDevice& dev(SensorDevice::getInstance());
1303 dev.unregisterDirectChannel(c->getHalChannelHandle());
1304 mDirectConnections.remove(c);
1305}
1306
Peng Xu755c4512016-04-07 23:15:14 -07001307sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001308 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001309}
1310
Mathias Agopianfc328812010-07-14 23:41:37 -07001311status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001312 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001313 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001314 if (mInitCheck != NO_ERROR)
1315 return mInitCheck;
1316
Peng Xu755c4512016-04-07 23:15:14 -07001317 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1318 if (sensor == nullptr ||
1319 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001320 return BAD_VALUE;
1321 }
1322
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001323 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001324 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001325 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001326 return INVALID_OPERATION;
1327 }
1328
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001329 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001330 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001331 rec = new SensorRecord(connection);
1332 mActiveSensors.add(handle, rec);
1333 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001334 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001335 }
1336 } else {
1337 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001338 // this sensor is already activated, but we are adding a connection that uses it.
1339 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001340 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001341 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001342 // NOTE: The wake_up flag of this event may get set to
1343 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001344
1345 auto logger = mRecentEvent.find(handle);
1346 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001347 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -07001348 // It is unlikely that this buffer is empty as the sensor is already active.
1349 // One possible corner case may be two applications activating an on-change
1350 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001351 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001352 event.sensor = handle;
1353 if (event.version == sizeof(sensors_event_t)) {
1354 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1355 setWakeLockAcquiredLocked(true);
1356 }
Yi Kong8f313e32018-07-17 14:13:29 -07001357 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001358 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1359 checkWakeLockStateLocked();
1360 }
1361 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001362 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001363 }
1364 }
1365 }
1366 }
1367
1368 if (connection->addSensor(handle)) {
1369 BatteryService::enableSensor(connection->getUid(), handle);
1370 // the sensor was added (which means it wasn't already there)
1371 // so, see if this connection becomes active
1372 if (mActiveConnections.indexOf(connection) < 0) {
1373 mActiveConnections.add(connection);
1374 }
1375 } else {
1376 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1377 handle, connection.get());
1378 }
1379
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301380 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001381 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301382 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1383 samplingPeriodNs = maxDelayNs;
1384 }
1385
Aravind Akella724d91d2013-06-27 12:04:23 -07001386 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1387 if (samplingPeriodNs < minDelayNs) {
1388 samplingPeriodNs = minDelayNs;
1389 }
1390
Aravind Akella6c2664a2014-08-13 12:24:50 -07001391 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1392 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001393 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1394
Aravind Akella4949c502015-02-11 15:54:35 -08001395 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001396 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001397
Peng Xu20483c42015-10-26 15:14:43 -07001398 // Call flush() before calling activate() on the sensor. Wait for a first
1399 // flush complete event before sending events on this connection. Ignore
1400 // one-shot sensors which don't support flush(). Ignore on-change sensors
1401 // to maintain the on-change logic (any on-change events except the initial
1402 // one should be trigger by a change in value). Also if this sensor isn't
1403 // already active, don't call flush().
1404 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001405 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001406 rec->getNumConnections() > 1) {
1407 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001408 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001409 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001410 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001411 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001412 } else {
1413 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001414 }
1415 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001416
1417 if (err == NO_ERROR) {
1418 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1419 err = sensor->activate(connection.get(), true);
1420 }
1421
Aravind Akella8a969552014-09-28 17:52:41 -07001422 if (err == NO_ERROR) {
1423 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001424
1425 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1426 SensorRegistrationInfo(handle, connection->getPackageName(),
1427 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001428 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001429 }
1430
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001431 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001432 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001433 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001434 }
1435 return err;
1436}
1437
Peng Xu47e96012016-03-28 17:55:56 -07001438status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001439 if (mInitCheck != NO_ERROR)
1440 return mInitCheck;
1441
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001442 Mutex::Autolock _l(mLock);
1443 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001444 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001445 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1446 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001447
1448 }
1449 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001450 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1451 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001452 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001453 }
1454 return err;
1455}
1456
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001457status_t SensorService::cleanupWithoutDisable(
1458 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001459 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001460 return cleanupWithoutDisableLocked(connection, handle);
1461}
1462
1463status_t SensorService::cleanupWithoutDisableLocked(
1464 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001465 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001466 if (rec) {
1467 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001468 if (connection->removeSensor(handle)) {
1469 BatteryService::disableSensor(connection->getUid(), handle);
1470 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001471 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001472 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001473 mActiveConnections.remove(connection);
1474 }
1475 // see if this sensor becomes inactive
1476 if (rec->removeConnection(connection)) {
1477 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001478 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001479 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001480 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001481 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001482 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001483 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001484}
1485
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001486status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001487 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001488 if (mInitCheck != NO_ERROR)
1489 return mInitCheck;
1490
Peng Xu755c4512016-04-07 23:15:14 -07001491 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1492 if (sensor == nullptr ||
1493 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001494 return BAD_VALUE;
1495 }
1496
Mathias Agopian1cd70002010-07-21 15:59:50 -07001497 if (ns < 0)
1498 return BAD_VALUE;
1499
Mathias Agopian62569ec2011-11-07 21:21:47 -08001500 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1501 if (ns < minDelayNs) {
1502 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001503 }
1504
Mathias Agopianf001c922010-11-11 17:58:51 -08001505 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001506}
1507
Svetoslavb412f6e2015-04-29 16:50:41 -07001508status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1509 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001510 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001511 SensorDevice& dev(SensorDevice::getInstance());
1512 const int halVersion = dev.getHalDeviceVersion();
1513 status_t err(NO_ERROR);
1514 Mutex::Autolock _l(mLock);
1515 // Loop through all sensors for this connection and call flush on each of them.
1516 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1517 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001518 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1519 if (sensor == nullptr) {
1520 continue;
1521 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001522 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1523 ALOGE("flush called on a one-shot sensor");
1524 err = INVALID_OPERATION;
1525 continue;
1526 }
Aravind Akella8493b792014-09-08 15:45:47 -07001527 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001528 // For older devices just increment pending flush count which will send a trivial
1529 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001530 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001531 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001532 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1533 err = INVALID_OPERATION;
1534 continue;
1535 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001536 status_t err_flush = sensor->flush(connection.get(), handle);
1537 if (err_flush == NO_ERROR) {
1538 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001539 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001540 }
1541 err = (err_flush != NO_ERROR) ? err_flush : err;
1542 }
Aravind Akella70018042014-04-07 22:52:37 +00001543 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001544 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001545}
Aravind Akella70018042014-04-07 22:52:37 +00001546
Svetoslavb412f6e2015-04-29 16:50:41 -07001547bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1548 const String16& opPackageName) {
1549 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001550
Svetoslavb412f6e2015-04-29 16:50:41 -07001551 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001552 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001553 }
1554
1555 bool hasPermission = false;
1556
1557 // Runtime permissions can't use the cache as they may change.
1558 if (sensor.isRequiredPermissionRuntime()) {
1559 hasPermission = checkPermission(String16(requiredPermission),
1560 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001561 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001562 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1563 }
1564
1565 if (!hasPermission) {
1566 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1567 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001568 return false;
1569 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001570
1571 const int32_t opCode = sensor.getRequiredAppOp();
1572 if (opCode >= 0) {
1573 AppOpsManager appOps;
1574 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1575 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001576 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001577 operation, sensor.getName().string(), opCode);
1578 return false;
1579 }
1580 }
1581
1582 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001583}
1584
Aravind Akella9a844cf2014-02-11 18:58:52 -08001585void SensorService::checkWakeLockState() {
1586 Mutex::Autolock _l(mLock);
1587 checkWakeLockStateLocked();
1588}
1589
1590void SensorService::checkWakeLockStateLocked() {
1591 if (!mWakeLockAcquired) {
1592 return;
1593 }
1594 bool releaseLock = true;
1595 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1596 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001597 if (connection != nullptr) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001598 if (connection->needsWakeLock()) {
1599 releaseLock = false;
1600 break;
1601 }
1602 }
1603 }
1604 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001605 setWakeLockAcquiredLocked(false);
1606 }
1607}
1608
1609void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1610 Mutex::Autolock _l(mLock);
1611 connection->writeToSocketFromCache();
1612 if (connection->needsWakeLock()) {
1613 setWakeLockAcquiredLocked(true);
1614 }
1615}
1616
1617void SensorService::populateActiveConnections(
1618 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1619 Mutex::Autolock _l(mLock);
1620 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1621 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001622 if (connection != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001623 activeConnections->add(connection);
1624 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001625 }
1626}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001627
Aravind Akella4949c502015-02-11 15:54:35 -08001628bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001629 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001630}
1631
Peng Xue36e3472016-11-03 11:57:10 -07001632bool SensorService::isOperationRestricted(const String16& opPackageName) {
1633 Mutex::Autolock _l(mLock);
1634 if (mCurrentOperatingMode != RESTRICTED) {
1635 String8 package(opPackageName);
1636 return !isWhiteListedPackage(package);
1637 }
1638 return false;
1639}
1640
Svet Ganove752a5c2018-01-15 17:14:20 -08001641void SensorService::UidPolicy::registerSelf() {
1642 ActivityManager am;
1643 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1644 | ActivityManager::UID_OBSERVER_IDLE
1645 | ActivityManager::UID_OBSERVER_ACTIVE,
1646 ActivityManager::PROCESS_STATE_UNKNOWN,
1647 String16("android"));
1648}
1649
1650void SensorService::UidPolicy::unregisterSelf() {
1651 ActivityManager am;
1652 am.unregisterUidObserver(this);
1653}
1654
1655void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1656 onUidIdle(uid, disabled);
1657}
1658
1659void SensorService::UidPolicy::onUidActive(uid_t uid) {
1660 {
1661 Mutex::Autolock _l(mUidLock);
1662 mActiveUids.insert(uid);
1663 }
1664 sp<SensorService> service = mService.promote();
1665 if (service != nullptr) {
1666 service->setSensorAccess(uid, true);
1667 }
1668}
1669
1670void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1671 bool deleted = false;
1672 {
1673 Mutex::Autolock _l(mUidLock);
1674 if (mActiveUids.erase(uid) > 0) {
1675 deleted = true;
1676 }
1677 }
1678 if (deleted) {
1679 sp<SensorService> service = mService.promote();
1680 if (service != nullptr) {
1681 service->setSensorAccess(uid, false);
1682 }
1683 }
1684}
1685
1686void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1687 updateOverrideUid(uid, active, true);
1688}
1689
1690void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1691 updateOverrideUid(uid, false, false);
1692}
1693
1694void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1695 bool wasActive = false;
1696 bool isActive = false;
1697 {
1698 Mutex::Autolock _l(mUidLock);
1699 wasActive = isUidActiveLocked(uid);
1700 mOverrideUids.erase(uid);
1701 if (insert) {
1702 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1703 }
1704 isActive = isUidActiveLocked(uid);
1705 }
1706 if (wasActive != isActive) {
1707 sp<SensorService> service = mService.promote();
1708 if (service != nullptr) {
1709 service->setSensorAccess(uid, isActive);
1710 }
1711 }
1712}
1713
1714bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1715 // Non-app UIDs are considered always active
1716 if (uid < FIRST_APPLICATION_UID) {
1717 return true;
1718 }
1719 Mutex::Autolock _l(mUidLock);
1720 return isUidActiveLocked(uid);
1721}
1722
1723bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1724 // Non-app UIDs are considered always active
1725 if (uid < FIRST_APPLICATION_UID) {
1726 return true;
1727 }
1728 auto it = mOverrideUids.find(uid);
1729 if (it != mOverrideUids.end()) {
1730 return it->second;
1731 }
1732 return mActiveUids.find(uid) != mActiveUids.end();
1733}
1734
Mathias Agopianfc328812010-07-14 23:41:37 -07001735}; // namespace android