blob: 372b6095ba64dbc54c0426568b118423a7a04ecf [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)){
Peng Xu6a2d3a02015-12-21 12:00:23 -0800309 mRecentEvent.emplace(handle, new 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.
654 bool bufferHasWakeUpEvent = false;
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])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800657 bufferHasWakeUpEvent = true;
658 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700659 }
660 }
661
Aravind Akella9a844cf2014-02-11 18:58:52 -0800662 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700663 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800664 }
Aravind Akella8493b792014-09-08 15:45:47 -0700665 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800666
Mathias Agopianf001c922010-11-11 17:58:51 -0800667 // handle virtual sensors
668 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700669 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700670 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800671 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700672 SensorFusion& fusion(SensorFusion::getInstance());
673 if (fusion.isEnabled()) {
674 for (size_t i=0 ; i<size_t(count) ; i++) {
675 fusion.process(event[i]);
676 }
677 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700678 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700679 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700680 if (count + k >= minBufferSize) {
681 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700682 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700683 count, k, minBufferSize);
684 break;
685 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800686 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700687 sp<SensorInterface> si = mSensors.getInterface(handle);
688 if (si == nullptr) {
689 ALOGE("handle %d is not an valid virtual sensor", handle);
690 continue;
691 }
692
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700693 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700694 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800695 k++;
696 }
697 }
698 }
699 if (k) {
700 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700701 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800702 count += k;
703 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700704 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700705 }
706 }
707 }
708
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700709 // handle backward compatibility for RotationVector sensor
710 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
711 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700712 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700713 // All the 4 components of the quaternion should be available
714 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700715 mSensorEventBuffer[i].data[4] = -1;
716 }
717 }
718 }
719
Aravind Akella8493b792014-09-08 15:45:47 -0700720 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700721 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
722 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
723 // SensorEventConnection mapped to the corresponding flush_complete_event in
724 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700725 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700726 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
727 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
728 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700729 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700730 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
731 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700732 }
733 }
Peng Xu2576cb62016-01-20 00:22:09 -0800734
735 // handle dynamic sensor meta events, process registration and unregistration of dynamic
736 // sensor based on content of event.
737 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
738 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
739 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
740 const sensor_t& dynamicSensor =
741 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
742 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
743 handle, dynamicSensor.type, dynamicSensor.name);
744
Peng Xu0cc8f802016-04-05 23:46:03 -0700745 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800746 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700747 sensor_t s = dynamicSensor;
748 // make sure the dynamic sensor flag is set
749 s.flags |= DYNAMIC_SENSOR_MASK;
750 // force the handle to be consistent
751 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800752
753 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800754
Peng Xu0cc8f802016-04-05 23:46:03 -0700755 // This will release hold on dynamic sensor meta, so it should be called
756 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700757 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800758 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700759 } else {
760 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
761 }
Peng Xu2576cb62016-01-20 00:22:09 -0800762 } else {
763 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
764 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
765
766 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800767 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800768 ALOGE("Dynamic sensor release error.");
769 }
770
771 size_t numConnections = activeConnections.size();
772 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700773 if (activeConnections[i] != nullptr) {
Peng Xu2576cb62016-01-20 00:22:09 -0800774 activeConnections[i]->removeSensor(handle);
775 }
776 }
777 }
778 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700779 }
780
Aravind Akella9a844cf2014-02-11 18:58:52 -0800781 // Send our events to clients. Check the state of wake lock for each client and release the
782 // lock if none of the clients need it.
783 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700784 size_t numConnections = activeConnections.size();
785 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700786 if (activeConnections[i] != nullptr) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700787 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700788 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700789 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700790 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
791 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700792 if (activeConnections[i]->hasOneShotSensors()) {
793 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
794 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700795 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800796 }
797 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700798
Aravind Akella9a844cf2014-02-11 18:58:52 -0800799 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700800 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800801 }
Aravind Akella8493b792014-09-08 15:45:47 -0700802 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700803
Steve Block3c20fbe2012-01-05 23:22:43 +0000804 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800805 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700806 return false;
807}
808
Aravind Akella56ae4262014-07-10 16:01:10 -0700809sp<Looper> SensorService::getLooper() const {
810 return mLooper;
811}
812
Aravind Akellab4373ac2014-10-29 17:55:20 -0700813void SensorService::resetAllWakeLockRefCounts() {
814 SortedVector< sp<SensorEventConnection> > activeConnections;
815 populateActiveConnections(&activeConnections);
816 {
817 Mutex::Autolock _l(mLock);
818 for (size_t i=0 ; i < activeConnections.size(); ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700819 if (activeConnections[i] != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700820 activeConnections[i]->resetWakeLockRefCount();
821 }
822 }
823 setWakeLockAcquiredLocked(false);
824 }
825}
826
827void SensorService::setWakeLockAcquiredLocked(bool acquire) {
828 if (acquire) {
829 if (!mWakeLockAcquired) {
830 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
831 mWakeLockAcquired = true;
832 }
833 mLooper->wake();
834 } else {
835 if (mWakeLockAcquired) {
836 release_wake_lock(WAKE_LOCK_NAME);
837 mWakeLockAcquired = false;
838 }
839 }
840}
841
Aravind Akellab4373ac2014-10-29 17:55:20 -0700842bool SensorService::isWakeLockAcquired() {
843 Mutex::Autolock _l(mLock);
844 return mWakeLockAcquired;
845}
846
Aravind Akella56ae4262014-07-10 16:01:10 -0700847bool SensorService::SensorEventAckReceiver::threadLoop() {
848 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700849 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700850 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700851 bool wakeLockAcquired = mService->isWakeLockAcquired();
852 int timeout = -1;
853 if (wakeLockAcquired) timeout = 5000;
854 int ret = looper->pollOnce(timeout);
855 if (ret == ALOOPER_POLL_TIMEOUT) {
856 mService->resetAllWakeLockRefCounts();
857 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700858 } while(!Thread::exitPending());
859 return false;
860}
861
Aravind Akella9a844cf2014-02-11 18:58:52 -0800862void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800863 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800864 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800865 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
866 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800867 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800868 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800869 }
Peng Xu2576cb62016-01-20 00:22:09 -0800870
Peng Xu6a2d3a02015-12-21 12:00:23 -0800871 auto logger = mRecentEvent.find(buffer[i].sensor);
872 if (logger != mRecentEvent.end()) {
873 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800874 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800875 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800876}
877
Peng Xu47e96012016-03-28 17:55:56 -0700878void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800879 struct compar {
880 static int cmp(void const* lhs, void const* rhs) {
881 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
882 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700883 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800884 }
885 };
886 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
887}
888
Mathias Agopian5d270722010-07-19 15:20:39 -0700889String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700890 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700891}
892
Aravind Akellab4099e72013-10-15 15:43:10 -0700893bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700894 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
895 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700896}
897
Aravind Akella9a844cf2014-02-11 18:58:52 -0800898bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700899 int handle = event.sensor;
900 if (event.type == SENSOR_TYPE_META_DATA) {
901 handle = event.meta_data.sensor;
902 }
Peng Xu755c4512016-04-07 23:15:14 -0700903 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
904 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800905}
906
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700907int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
908 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
909 // UUID is not supported for this device.
910 return 0;
911 }
912 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
913 // This sensor can be uniquely identified in the system by
914 // the combination of its type and name.
915 return -1;
916 }
917
918 // We have a dynamic sensor.
919
920 if (!sHmacGlobalKeyIsValid) {
921 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
922 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
923 return 0;
924 }
925
926 // We want each app author/publisher to get a different ID, so that the
927 // same dynamic sensor cannot be tracked across apps by multiple
928 // authors/publishers. So we use both our UUID and our User ID.
929 // Note potential confusion:
930 // UUID => Universally Unique Identifier.
931 // UID => User Identifier.
932 // We refrain from using "uid" except as needed by API to try to
933 // keep this distinction clear.
934
935 auto appUserId = IPCThreadState::self()->getCallingUid();
936 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
937 memcpy(uuidAndApp, &uuid, sizeof(uuid));
938 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
939
940 // Now we use our key on our UUID/app combo to get the hash.
941 uint8_t hash[EVP_MAX_MD_SIZE];
942 unsigned int hashLen;
943 if (HMAC(EVP_sha256(),
944 sHmacGlobalKey, sizeof(sHmacGlobalKey),
945 uuidAndApp, sizeof(uuidAndApp),
946 hash, &hashLen) == nullptr) {
947 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
948 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
949 return 0;
950 }
951
952 int32_t id = 0;
953 if (hashLen < sizeof(id)) {
954 // We never expect this case, but out of paranoia, we handle it.
955 // Our 'id' length is already quite small, we don't want the
956 // effective length of it to be even smaller.
957 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
958 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
959 return 0;
960 }
961
962 // This is almost certainly less than all of 'hash', but it's as secure
963 // as we can be with our current 'id' length.
964 memcpy(&id, hash, sizeof(id));
965
966 // Note at the beginning of the function that we return the values of
967 // 0 and -1 to represent special cases. As a result, we can't return
968 // those as dynamic sensor IDs. If we happened to hash to one of those
969 // values, we change 'id' so we report as a dynamic sensor, and not as
970 // one of those special cases.
971 if (id == -1) {
972 id = -2;
973 } else if (id == 0) {
974 id = 1;
975 }
976 return id;
977}
978
979void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
980 for (auto &sensor : sensorList) {
981 int32_t id = getIdFromUuid(sensor.getUuid());
982 sensor.setId(id);
983 }
984}
985
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800986Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -0700987 char value[PROPERTY_VALUE_MAX];
988 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000989 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700990 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000991 Vector<Sensor> accessibleSensorList;
992 for (size_t i = 0; i < initialSensorList.size(); i++) {
993 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800994 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -0700995 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700996 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +0000997 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700998}
999
Peng Xu47e96012016-03-28 17:55:56 -07001000Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001001 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001002 mSensors.forEachSensor(
1003 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001004 if (sensor.isDynamicSensor()) {
1005 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1006 accessibleSensorList.add(sensor);
1007 } else {
1008 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1009 sensor.getName().string(),
1010 sensor.getRequiredPermission().string(),
1011 sensor.getRequiredAppOp());
1012 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001013 }
1014 return true;
1015 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001016 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001017 return accessibleSensorList;
1018}
1019
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001020sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001021 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001022 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1023 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001024 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001025 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001026
1027 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001028 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1029 // operating in DI mode.
1030 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001031 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1032 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001033 }
1034
Mathias Agopian5307d172012-09-18 17:02:43 -07001035 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001036 pid_t pid = IPCThreadState::self()->getCallingPid();
1037
1038 String8 connPackageName =
1039 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1040 String16 connOpPackageName =
1041 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001042 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001043 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001044 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001045 if (requestedMode == DATA_INJECTION) {
1046 if (mActiveConnections.indexOf(result) < 0) {
1047 mActiveConnections.add(result);
1048 }
1049 // Add the associated file descriptor to the Looper for polling whenever there is data to
1050 // be injected.
1051 result->updateLooperRegistration(mLooper);
1052 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001053 return result;
1054}
1055
Aravind Akella841a5922015-06-29 12:37:48 -07001056int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001057 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001058 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001059}
1060
Peng Xue36e3472016-11-03 11:57:10 -07001061sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1062 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1063 const native_handle *resource) {
1064 Mutex::Autolock _l(mLock);
1065
1066 struct sensors_direct_mem_t mem = {
1067 .type = type,
1068 .format = format,
1069 .size = size,
1070 .handle = resource,
1071 };
1072 uid_t uid = IPCThreadState::self()->getCallingUid();
1073
1074 if (mem.handle == nullptr) {
1075 ALOGE("Failed to clone resource handle");
1076 return nullptr;
1077 }
1078
1079 // check format
1080 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1081 ALOGE("Direct channel format %d is unsupported!", format);
1082 return nullptr;
1083 }
1084
1085 // check for duplication
1086 for (auto &i : mDirectConnections) {
1087 sp<SensorDirectConnection> connection(i.promote());
1088 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001089 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001090 return nullptr;
1091 }
1092 }
1093
1094 // check specific to memory type
1095 switch(type) {
1096 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001097 if (resource->numFds < 1) {
1098 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1099 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1100 return nullptr;
1101 }
Peng Xue36e3472016-11-03 11:57:10 -07001102 int fd = resource->data[0];
1103 int size2 = ashmem_get_size_region(fd);
1104 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001105 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001106 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1107 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001108 return nullptr;
1109 }
1110 break;
1111 }
1112 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001113 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001114 break;
1115 default:
1116 ALOGE("Unknown direct connection memory type %d", type);
1117 return nullptr;
1118 }
1119
1120 native_handle_t *clone = native_handle_clone(resource);
1121 if (!clone) {
1122 return nullptr;
1123 }
1124
1125 SensorDirectConnection* conn = nullptr;
1126 SensorDevice& dev(SensorDevice::getInstance());
1127 int channelHandle = dev.registerDirectChannel(&mem);
1128
1129 if (channelHandle <= 0) {
1130 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1131 } else {
1132 mem.handle = clone;
1133 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1134 }
1135
1136 if (conn == nullptr) {
1137 native_handle_close(clone);
1138 native_handle_delete(clone);
1139 } else {
1140 // add to list of direct connections
1141 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1142 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1143 }
1144 return conn;
1145}
1146
Peng Xudd5c5cb2017-03-16 17:39:43 -07001147int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001148 int32_t handle, int32_t type,
1149 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001150 Mutex::Autolock _l(mLock);
1151
Alexey Polyudov88711e82017-05-23 19:54:04 -07001152 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001153 return PERMISSION_DENIED;
1154 }
1155
1156 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001157 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001158 size_t expectSize = INT32_MAX;
1159 switch (type) {
1160 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1161 isFloat = true;
1162 expectSize = 3;
1163 break;
1164 case AINFO_LOCAL_GRAVITY:
1165 isFloat = true;
1166 expectSize = 1;
1167 break;
1168 case AINFO_DOCK_STATE:
1169 case AINFO_HIGH_PERFORMANCE_MODE:
1170 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1171 isFloat = false;
1172 expectSize = 1;
1173 break;
1174 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001175 // CUSTOM events must only contain float data; it may have variable size
1176 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1177 ints.size() ||
1178 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1179 handle < 0) {
1180 return BAD_VALUE;
1181 }
1182 isFloat = true;
1183 isCustom = true;
1184 expectSize = floats.size();
1185 break;
1186 }
1187
1188 if (!isCustom && handle != -1) {
1189 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001190 }
1191
1192 // three events: first one is begin tag, last one is end tag, the one in the middle
1193 // is the payload.
1194 sensors_event_t event[3];
1195 int64_t timestamp = elapsedRealtimeNano();
1196 for (sensors_event_t* i = event; i < event + 3; i++) {
1197 *i = (sensors_event_t) {
1198 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001199 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001200 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1201 .timestamp = timestamp++,
1202 .additional_info = (additional_info_event_t) {
1203 .serial = 0
1204 }
1205 };
1206 }
1207
1208 event[0].additional_info.type = AINFO_BEGIN;
1209 event[1].additional_info.type = type;
1210 event[2].additional_info.type = AINFO_END;
1211
1212 if (isFloat) {
1213 if (floats.size() != expectSize) {
1214 return BAD_VALUE;
1215 }
1216 for (size_t i = 0; i < expectSize; ++i) {
1217 event[1].additional_info.data_float[i] = floats[i];
1218 }
1219 } else {
1220 if (ints.size() != expectSize) {
1221 return BAD_VALUE;
1222 }
1223 for (size_t i = 0; i < expectSize; ++i) {
1224 event[1].additional_info.data_int32[i] = ints[i];
1225 }
1226 }
1227
1228 SensorDevice& dev(SensorDevice::getInstance());
1229 for (sensors_event_t* i = event; i < event + 3; i++) {
1230 int ret = dev.injectSensorData(i);
1231 if (ret != NO_ERROR) {
1232 return ret;
1233 }
1234 }
1235 return NO_ERROR;
1236}
1237
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001238status_t SensorService::resetToNormalMode() {
1239 Mutex::Autolock _l(mLock);
1240 return resetToNormalModeLocked();
1241}
1242
1243status_t SensorService::resetToNormalModeLocked() {
1244 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001245 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301246 if (err == NO_ERROR) {
1247 mCurrentOperatingMode = NORMAL;
1248 dev.enableAllSensors();
1249 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001250 return err;
1251}
1252
Peng Xu47e96012016-03-28 17:55:56 -07001253void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001254 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001255 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001256 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001257 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001258 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001259 int handle = mActiveSensors.keyAt(i);
1260 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001261 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001262 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1263 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001264 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001265 } else {
1266 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001267 }
Aravind Akella8a969552014-09-28 17:52:41 -07001268 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001269 }
1270 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001271 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001272 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001273 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001274 c, i, handle);
1275
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001276 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001277 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001278 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001279 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001280 delete rec;
1281 size--;
1282 } else {
1283 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001284 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001285 }
Aravind Akella8a969552014-09-28 17:52:41 -07001286 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001287 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001288 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001289 if (c->needsWakeLock()) {
1290 checkWakeLockStateLocked();
1291 }
Peng Xu4f707f82016-09-26 11:28:32 -07001292
1293 SensorDevice& dev(SensorDevice::getInstance());
1294 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001295}
1296
Peng Xue36e3472016-11-03 11:57:10 -07001297void SensorService::cleanupConnection(SensorDirectConnection* c) {
1298 Mutex::Autolock _l(mLock);
1299
1300 SensorDevice& dev(SensorDevice::getInstance());
1301 dev.unregisterDirectChannel(c->getHalChannelHandle());
1302 mDirectConnections.remove(c);
1303}
1304
Peng Xu755c4512016-04-07 23:15:14 -07001305sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001306 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001307}
1308
Mathias Agopianfc328812010-07-14 23:41:37 -07001309status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001310 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001311 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001312 if (mInitCheck != NO_ERROR)
1313 return mInitCheck;
1314
Peng Xu755c4512016-04-07 23:15:14 -07001315 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1316 if (sensor == nullptr ||
1317 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001318 return BAD_VALUE;
1319 }
1320
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001321 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001322 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001323 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001324 return INVALID_OPERATION;
1325 }
1326
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001327 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001328 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001329 rec = new SensorRecord(connection);
1330 mActiveSensors.add(handle, rec);
1331 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001332 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001333 }
1334 } else {
1335 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001336 // this sensor is already activated, but we are adding a connection that uses it.
1337 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001338 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001339 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001340 // NOTE: The wake_up flag of this event may get set to
1341 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001342
1343 auto logger = mRecentEvent.find(handle);
1344 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001345 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -07001346 // It is unlikely that this buffer is empty as the sensor is already active.
1347 // One possible corner case may be two applications activating an on-change
1348 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001349 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001350 event.sensor = handle;
1351 if (event.version == sizeof(sensors_event_t)) {
1352 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1353 setWakeLockAcquiredLocked(true);
1354 }
Yi Kong8f313e32018-07-17 14:13:29 -07001355 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001356 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1357 checkWakeLockStateLocked();
1358 }
1359 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001360 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001361 }
1362 }
1363 }
1364 }
1365
1366 if (connection->addSensor(handle)) {
1367 BatteryService::enableSensor(connection->getUid(), handle);
1368 // the sensor was added (which means it wasn't already there)
1369 // so, see if this connection becomes active
1370 if (mActiveConnections.indexOf(connection) < 0) {
1371 mActiveConnections.add(connection);
1372 }
1373 } else {
1374 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1375 handle, connection.get());
1376 }
1377
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301378 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001379 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301380 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1381 samplingPeriodNs = maxDelayNs;
1382 }
1383
Aravind Akella724d91d2013-06-27 12:04:23 -07001384 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1385 if (samplingPeriodNs < minDelayNs) {
1386 samplingPeriodNs = minDelayNs;
1387 }
1388
Aravind Akella6c2664a2014-08-13 12:24:50 -07001389 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1390 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001391 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1392
Aravind Akella4949c502015-02-11 15:54:35 -08001393 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001394 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001395
Peng Xu20483c42015-10-26 15:14:43 -07001396 // Call flush() before calling activate() on the sensor. Wait for a first
1397 // flush complete event before sending events on this connection. Ignore
1398 // one-shot sensors which don't support flush(). Ignore on-change sensors
1399 // to maintain the on-change logic (any on-change events except the initial
1400 // one should be trigger by a change in value). Also if this sensor isn't
1401 // already active, don't call flush().
1402 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001403 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001404 rec->getNumConnections() > 1) {
1405 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001406 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001407 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001408 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001409 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001410 } else {
1411 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001412 }
1413 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001414
1415 if (err == NO_ERROR) {
1416 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1417 err = sensor->activate(connection.get(), true);
1418 }
1419
Aravind Akella8a969552014-09-28 17:52:41 -07001420 if (err == NO_ERROR) {
1421 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001422
1423 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1424 SensorRegistrationInfo(handle, connection->getPackageName(),
1425 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001426 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001427 }
1428
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001429 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001430 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001431 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001432 }
1433 return err;
1434}
1435
Peng Xu47e96012016-03-28 17:55:56 -07001436status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001437 if (mInitCheck != NO_ERROR)
1438 return mInitCheck;
1439
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001440 Mutex::Autolock _l(mLock);
1441 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001442 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001443 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1444 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001445
1446 }
1447 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001448 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1449 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001450 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001451 }
1452 return err;
1453}
1454
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001455status_t SensorService::cleanupWithoutDisable(
1456 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001457 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001458 return cleanupWithoutDisableLocked(connection, handle);
1459}
1460
1461status_t SensorService::cleanupWithoutDisableLocked(
1462 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001463 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001464 if (rec) {
1465 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001466 if (connection->removeSensor(handle)) {
1467 BatteryService::disableSensor(connection->getUid(), handle);
1468 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001469 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001470 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001471 mActiveConnections.remove(connection);
1472 }
1473 // see if this sensor becomes inactive
1474 if (rec->removeConnection(connection)) {
1475 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001476 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001477 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001478 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001479 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001480 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001481 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001482}
1483
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001484status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001485 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001486 if (mInitCheck != NO_ERROR)
1487 return mInitCheck;
1488
Peng Xu755c4512016-04-07 23:15:14 -07001489 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1490 if (sensor == nullptr ||
1491 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001492 return BAD_VALUE;
1493 }
1494
Mathias Agopian1cd70002010-07-21 15:59:50 -07001495 if (ns < 0)
1496 return BAD_VALUE;
1497
Mathias Agopian62569ec2011-11-07 21:21:47 -08001498 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1499 if (ns < minDelayNs) {
1500 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001501 }
1502
Mathias Agopianf001c922010-11-11 17:58:51 -08001503 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001504}
1505
Svetoslavb412f6e2015-04-29 16:50:41 -07001506status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1507 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001508 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001509 SensorDevice& dev(SensorDevice::getInstance());
1510 const int halVersion = dev.getHalDeviceVersion();
1511 status_t err(NO_ERROR);
1512 Mutex::Autolock _l(mLock);
1513 // Loop through all sensors for this connection and call flush on each of them.
1514 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1515 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001516 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1517 if (sensor == nullptr) {
1518 continue;
1519 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001520 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1521 ALOGE("flush called on a one-shot sensor");
1522 err = INVALID_OPERATION;
1523 continue;
1524 }
Aravind Akella8493b792014-09-08 15:45:47 -07001525 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001526 // For older devices just increment pending flush count which will send a trivial
1527 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001528 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001529 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001530 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1531 err = INVALID_OPERATION;
1532 continue;
1533 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001534 status_t err_flush = sensor->flush(connection.get(), handle);
1535 if (err_flush == NO_ERROR) {
1536 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001537 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001538 }
1539 err = (err_flush != NO_ERROR) ? err_flush : err;
1540 }
Aravind Akella70018042014-04-07 22:52:37 +00001541 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001542 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001543}
Aravind Akella70018042014-04-07 22:52:37 +00001544
Svetoslavb412f6e2015-04-29 16:50:41 -07001545bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1546 const String16& opPackageName) {
1547 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001548
Svetoslavb412f6e2015-04-29 16:50:41 -07001549 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001550 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001551 }
1552
1553 bool hasPermission = false;
1554
1555 // Runtime permissions can't use the cache as they may change.
1556 if (sensor.isRequiredPermissionRuntime()) {
1557 hasPermission = checkPermission(String16(requiredPermission),
1558 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001559 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001560 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1561 }
1562
1563 if (!hasPermission) {
1564 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1565 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001566 return false;
1567 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001568
1569 const int32_t opCode = sensor.getRequiredAppOp();
1570 if (opCode >= 0) {
1571 AppOpsManager appOps;
1572 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1573 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001574 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001575 operation, sensor.getName().string(), opCode);
1576 return false;
1577 }
1578 }
1579
1580 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001581}
1582
Aravind Akella9a844cf2014-02-11 18:58:52 -08001583void SensorService::checkWakeLockState() {
1584 Mutex::Autolock _l(mLock);
1585 checkWakeLockStateLocked();
1586}
1587
1588void SensorService::checkWakeLockStateLocked() {
1589 if (!mWakeLockAcquired) {
1590 return;
1591 }
1592 bool releaseLock = true;
1593 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1594 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001595 if (connection != nullptr) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001596 if (connection->needsWakeLock()) {
1597 releaseLock = false;
1598 break;
1599 }
1600 }
1601 }
1602 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001603 setWakeLockAcquiredLocked(false);
1604 }
1605}
1606
1607void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1608 Mutex::Autolock _l(mLock);
1609 connection->writeToSocketFromCache();
1610 if (connection->needsWakeLock()) {
1611 setWakeLockAcquiredLocked(true);
1612 }
1613}
1614
1615void SensorService::populateActiveConnections(
1616 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1617 Mutex::Autolock _l(mLock);
1618 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1619 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001620 if (connection != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001621 activeConnections->add(connection);
1622 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001623 }
1624}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001625
Aravind Akella4949c502015-02-11 15:54:35 -08001626bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001627 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001628}
1629
Peng Xue36e3472016-11-03 11:57:10 -07001630bool SensorService::isOperationRestricted(const String16& opPackageName) {
1631 Mutex::Autolock _l(mLock);
1632 if (mCurrentOperatingMode != RESTRICTED) {
1633 String8 package(opPackageName);
1634 return !isWhiteListedPackage(package);
1635 }
1636 return false;
1637}
1638
Svet Ganove752a5c2018-01-15 17:14:20 -08001639void SensorService::UidPolicy::registerSelf() {
1640 ActivityManager am;
1641 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1642 | ActivityManager::UID_OBSERVER_IDLE
1643 | ActivityManager::UID_OBSERVER_ACTIVE,
1644 ActivityManager::PROCESS_STATE_UNKNOWN,
1645 String16("android"));
1646}
1647
1648void SensorService::UidPolicy::unregisterSelf() {
1649 ActivityManager am;
1650 am.unregisterUidObserver(this);
1651}
1652
1653void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1654 onUidIdle(uid, disabled);
1655}
1656
1657void SensorService::UidPolicy::onUidActive(uid_t uid) {
1658 {
1659 Mutex::Autolock _l(mUidLock);
1660 mActiveUids.insert(uid);
1661 }
1662 sp<SensorService> service = mService.promote();
1663 if (service != nullptr) {
1664 service->setSensorAccess(uid, true);
1665 }
1666}
1667
1668void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1669 bool deleted = false;
1670 {
1671 Mutex::Autolock _l(mUidLock);
1672 if (mActiveUids.erase(uid) > 0) {
1673 deleted = true;
1674 }
1675 }
1676 if (deleted) {
1677 sp<SensorService> service = mService.promote();
1678 if (service != nullptr) {
1679 service->setSensorAccess(uid, false);
1680 }
1681 }
1682}
1683
1684void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1685 updateOverrideUid(uid, active, true);
1686}
1687
1688void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1689 updateOverrideUid(uid, false, false);
1690}
1691
1692void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1693 bool wasActive = false;
1694 bool isActive = false;
1695 {
1696 Mutex::Autolock _l(mUidLock);
1697 wasActive = isUidActiveLocked(uid);
1698 mOverrideUids.erase(uid);
1699 if (insert) {
1700 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1701 }
1702 isActive = isUidActiveLocked(uid);
1703 }
1704 if (wasActive != isActive) {
1705 sp<SensorService> service = mService.promote();
1706 if (service != nullptr) {
1707 service->setSensorAccess(uid, isActive);
1708 }
1709 }
1710}
1711
1712bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1713 // Non-app UIDs are considered always active
1714 if (uid < FIRST_APPLICATION_UID) {
1715 return true;
1716 }
1717 Mutex::Autolock _l(mUidLock);
1718 return isUidActiveLocked(uid);
1719}
1720
1721bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1722 // Non-app UIDs are considered always active
1723 if (uid < FIRST_APPLICATION_UID) {
1724 return true;
1725 }
1726 auto it = mOverrideUids.find(uid);
1727 if (it != mOverrideUids.end()) {
1728 return it->second;
1729 }
1730 return mActiveUids.find(uid) != mActiveUids.end();
1731}
1732
Mathias Agopianfc328812010-07-14 23:41:37 -07001733}; // namespace android