blob: c32ffb9c41fdf541bc3573bfbffab38b24e6c2e3 [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>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070027#include <openssl/digest.h>
28#include <openssl/hmac.h>
29#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070030#include <sensor/SensorEventQueue.h>
31#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070032
Mathias Agopian787ac1b2012-09-18 18:49:18 -070033#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070034#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080035#include "GravitySensor.h"
36#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070037#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080038#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070039#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070040#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080041
Mathias Agopian984826c2011-05-17 22:54:42 -070042#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070043#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080044#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080045#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080046#include "SensorRecord.h"
47#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048
49#include <inttypes.h>
50#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070051#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080052#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080053#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070054#include <sys/stat.h>
55#include <sys/types.h>
56#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070057
Svet Ganove752a5c2018-01-15 17:14:20 -080058#include <private/android_filesystem_config.h>
59
Mathias Agopianfc328812010-07-14 23:41:37 -070060namespace android {
61// ---------------------------------------------------------------------------
62
Mathias Agopian33015422011-05-27 18:18:13 -070063/*
64 * Notes:
65 *
66 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070067 * - run mag sensor from time to time to force calibration
68 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
69 *
70 */
71
Aravind Akella8ef3c892015-07-10 11:24:28 -070072const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070073uint8_t SensorService::sHmacGlobalKey[128] = {};
74bool SensorService::sHmacGlobalKeyIsValid = false;
75
76#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
77#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070078#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070079
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070080// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070081static const String16 sDumpPermission("android.permission.DUMP");
82static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080083static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070084
Mathias Agopianfc328812010-07-14 23:41:37 -070085SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070086 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070087 mWakeLockAcquired(false) {
Mathias Agopianfc328812010-07-14 23:41:37 -070088}
89
Greg Kaiser53ca2e02016-06-21 16:11:14 -070090bool SensorService::initializeHmacKey() {
91 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
92 if (fd != -1) {
93 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
94 close(fd);
95 if (result == sizeof(sHmacGlobalKey)) {
96 return true;
97 }
98 ALOGW("Unable to read HMAC key; generating new one.");
99 }
100
101 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
102 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
103 return false;
104 }
105
106 // We need to make sure this is only readable to us.
107 bool wroteKey = false;
108 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
109 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
110 S_IRUSR|S_IWUSR);
111 if (fd != -1) {
112 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
113 close(fd);
114 wroteKey = (result == sizeof(sHmacGlobalKey));
115 }
116 if (wroteKey) {
117 ALOGI("Generated new HMAC key.");
118 } else {
119 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
120 "after reboot.");
121 }
122 // Even if we failed to write the key we return true, because we did
123 // initialize the HMAC key.
124 return true;
125}
126
Peng Xu98d30f62016-08-01 18:12:11 -0700127// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
128void SensorService::enableSchedFifoMode() {
129 struct sched_param param = {0};
130 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
131 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
132 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
133 }
134}
135
Peng Xu47e96012016-03-28 17:55:56 -0700136void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000137 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800138 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700139
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700140 sHmacGlobalKeyIsValid = initializeHmacKey();
141
Mathias Agopianf001c922010-11-11 17:58:51 -0800142 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800143 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700144 ssize_t count = dev.getSensorList(&list);
145 if (count > 0) {
146 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700147 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700148 uint32_t virtualSensorsNeeds =
149 (1<<SENSOR_TYPE_GRAVITY) |
150 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700151 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
152 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
153 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700154
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700155 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700156 bool useThisSensor=true;
157
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700158 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700159 case SENSOR_TYPE_ACCELEROMETER:
160 hasAccel = true;
161 break;
162 case SENSOR_TYPE_MAGNETIC_FIELD:
163 hasMag = true;
164 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700165 case SENSOR_TYPE_ORIENTATION:
166 orientationIndex = i;
167 break;
168 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700169 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700170 hasGyro = true;
171 break;
172 case SENSOR_TYPE_GRAVITY:
173 case SENSOR_TYPE_LINEAR_ACCELERATION:
174 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700175 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
176 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
177 if (IGNORE_HARDWARE_FUSION) {
178 useThisSensor = false;
179 } else {
180 virtualSensorsNeeds &= ~(1<<list[i].type);
181 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700182 break;
183 }
Peng Xuf66684a2015-07-23 11:41:53 -0700184 if (useThisSensor) {
185 registerSensor( new HardwareSensor(list[i]) );
186 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700187 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700188
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700189 // it's safe to instantiate the SensorFusion object here
190 // (it wants to be instantiated after h/w sensors have been
191 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700192 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700193
Aravind Akellaf5047892015-07-20 17:29:33 -0700194 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700195 // Add Android virtual sensors if they're not already
196 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700197 bool needRotationVector =
198 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700199
Peng Xu0cc8f802016-04-05 23:46:03 -0700200 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
201 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700202
Peng Xu0cc8f802016-04-05 23:46:03 -0700203 bool needLinearAcceleration =
204 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700205
Peng Xu0cc8f802016-04-05 23:46:03 -0700206 registerSensor(new LinearAccelerationSensor(list, count),
207 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700208
Peng Xu0cc8f802016-04-05 23:46:03 -0700209 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700210 registerSensor( new CorrectedGyroSensor(list, count), true, true);
211 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700212 }
213
Peng Xuf66684a2015-07-23 11:41:53 -0700214 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700215 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
216 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700217
Peng Xu0cc8f802016-04-05 23:46:03 -0700218 bool needGameRotationVector =
219 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
220 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700221 }
222
223 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700224 bool needGeoMagRotationVector =
225 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
226 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700227 }
228
Aravind Akella5466c3d2014-08-22 16:11:10 -0700229 // Check if the device really supports batching by looking at the FIFO event
230 // counts for each sensor.
231 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700232 mSensors.forEachSensor(
233 [&batchingSupported] (const Sensor& s) -> bool {
234 if (s.getFifoMaxEventCount() > 0) {
235 batchingSupported = true;
236 }
237 return !batchingSupported;
238 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700239
240 if (batchingSupported) {
241 // Increase socket buffer size to a max of 100 KB for batching capabilities.
242 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
243 } else {
244 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
245 }
246
247 // Compare the socketBufferSize value against the system limits and limit
248 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700249 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
250 char line[128];
251 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
252 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700253 size_t maxSystemSocketBufferSize;
254 sscanf(line, "%zu", &maxSystemSocketBufferSize);
255 if (mSocketBufferSize > maxSystemSocketBufferSize) {
256 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700257 }
258 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700259 if (fp) {
260 fclose(fp);
261 }
262
Aravind Akella9a844cf2014-02-11 18:58:52 -0800263 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700264 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700265 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
266 mSensorEventBuffer = new sensors_event_t[minBufferSize];
267 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700268 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700269 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700270
Aravind Akella18d6d512015-06-18 14:18:28 -0700271 mNextSensorRegIndex = 0;
272 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
273 mLastNSensorRegistrations.push();
274 }
275
276 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700277 mAckReceiver = new SensorEventAckReceiver(this);
278 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700279 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700280
281 // priority can only be changed after run
282 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800283
284 // Start watching UID changes to apply policy.
285 mUidPolicy = new UidPolicy(this);
286 mUidPolicy->registerSelf();
287 }
288 }
289}
290
291void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
292 SortedVector< sp<SensorEventConnection> > activeConnections;
293 populateActiveConnections(&activeConnections);
294 {
295 Mutex::Autolock _l(mLock);
296 for (size_t i = 0 ; i < activeConnections.size(); i++) {
297 if (activeConnections[i] != 0 && activeConnections[i]->getUid() == uid) {
298 activeConnections[i]->setSensorAccess(hasAccess);
299 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700300 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700301 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700302}
303
Peng Xu0cc8f802016-04-05 23:46:03 -0700304const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
305 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800306 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700307 if (mSensors.add(handle, s, isDebug, isVirtual)){
Peng Xu6a2d3a02015-12-21 12:00:23 -0800308 mRecentEvent.emplace(handle, new RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700309 return s->getSensor();
310 } else {
311 return mSensors.getNonSensor();
312 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800313}
314
Peng Xu6a2d3a02015-12-21 12:00:23 -0800315const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700316 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800317}
318
Peng Xu6a2d3a02015-12-21 12:00:23 -0800319bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700320 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800321
322 const auto i = mRecentEvent.find(handle);
323 if (i != mRecentEvent.end()) {
324 delete i->second;
325 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800326 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700327 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800328}
329
Peng Xu0cc8f802016-04-05 23:46:03 -0700330const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
331 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700332}
333
Peng Xu47e96012016-03-28 17:55:56 -0700334SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800335 for (auto && entry : mRecentEvent) {
336 delete entry.second;
337 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800338 mUidPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700339}
340
341status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700342 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700343 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800344 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700345 IPCThreadState::self()->getCallingPid(),
346 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700347 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700348 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700349 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800350 return INVALID_OPERATION;
351 }
352 Mutex::Autolock _l(mLock);
353 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700354 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700355 // If already in restricted mode. Ignore.
356 if (mCurrentOperatingMode == RESTRICTED) {
357 return status_t(NO_ERROR);
358 }
359 // If in any mode other than normal, ignore.
360 if (mCurrentOperatingMode != NORMAL) {
361 return INVALID_OPERATION;
362 }
Peng Xue36e3472016-11-03 11:57:10 -0700363
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700364 mCurrentOperatingMode = RESTRICTED;
Peng Xue36e3472016-11-03 11:57:10 -0700365 // temporarily stop all sensor direct report
366 for (auto &i : mDirectConnections) {
367 sp<SensorDirectConnection> connection(i.promote());
368 if (connection != nullptr) {
369 connection->stopAll(true /* backupRecord */);
370 }
371 }
372
Aravind Akella4949c502015-02-11 15:54:35 -0800373 dev.disableAllSensors();
374 // Clear all pending flush connections for all active sensors. If one of the active
375 // connections has called flush() and the underlying sensor has been disabled before a
376 // flush complete event is returned, we need to remove the connection from this queue.
377 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
378 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
379 }
Aravind Akella841a5922015-06-29 12:37:48 -0700380 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700381 return status_t(NO_ERROR);
382 } else if (args.size() == 1 && args[0] == String16("enable")) {
383 // If currently in restricted mode, reset back to NORMAL mode else ignore.
384 if (mCurrentOperatingMode == RESTRICTED) {
385 mCurrentOperatingMode = NORMAL;
386 dev.enableAllSensors();
Peng Xue36e3472016-11-03 11:57:10 -0700387 // recover all sensor direct report
388 for (auto &i : mDirectConnections) {
389 sp<SensorDirectConnection> connection(i.promote());
390 if (connection != nullptr) {
391 connection->recoverAll();
392 }
393 }
Aravind Akella444f2672015-05-07 12:40:52 -0700394 }
Aravind Akella841a5922015-06-29 12:37:48 -0700395 if (mCurrentOperatingMode == DATA_INJECTION) {
396 resetToNormalModeLocked();
397 }
398 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700399 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700400 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
401 if (mCurrentOperatingMode == NORMAL) {
402 dev.disableAllSensors();
403 status_t err = dev.setMode(DATA_INJECTION);
404 if (err == NO_ERROR) {
405 mCurrentOperatingMode = DATA_INJECTION;
406 } else {
407 // Re-enable sensors.
408 dev.enableAllSensors();
409 }
410 mWhiteListedPackage.setTo(String8(args[1]));
411 return NO_ERROR;
412 } else if (mCurrentOperatingMode == DATA_INJECTION) {
413 // Already in DATA_INJECTION mode. Treat this as a no_op.
414 return NO_ERROR;
415 } else {
416 // Transition to data injection mode supported only from NORMAL mode.
417 return INVALID_OPERATION;
418 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700419 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700420 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700421 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700422 } else {
423 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700424 //
Peng Xu6a2d3a02015-12-21 12:00:23 -0800425 result.append("Sensor Device:\n");
426 result.append(SensorDevice::getInstance().dump().c_str());
427
428 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700429 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700430
Peng Xu6a2d3a02015-12-21 12:00:23 -0800431 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700432 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700433
Peng Xu0cc8f802016-04-05 23:46:03 -0700434 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800435 for (auto&& i : mRecentEvent) {
436 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700437 if (!i.second->isEmpty()) {
438 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
439 i.second->setFormat("normal");
440 } else {
441 i.second->setFormat("mask_data");
442 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800443 // if there is events and sensor does not need special permission.
444 result.appendFormat("%s: ", s->getSensor().getName().string());
445 result.append(i.second->dump().c_str());
446 }
447 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700448
Aravind Akella444f2672015-05-07 12:40:52 -0700449 result.append("Active sensors:\n");
450 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
451 int handle = mActiveSensors.keyAt(i);
452 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
453 getSensorName(handle).string(),
454 handle,
455 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700456 }
457
Andreas Gamped4036b62015-07-28 13:49:04 -0700458 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700459 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700460 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
461 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700462 result.appendFormat("Mode :");
463 switch(mCurrentOperatingMode) {
464 case NORMAL:
465 result.appendFormat(" NORMAL\n");
466 break;
467 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700468 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700469 break;
470 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700471 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700472 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700473
Peng Xue36e3472016-11-03 11:57:10 -0700474 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella444f2672015-05-07 12:40:52 -0700475 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
476 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
477 if (connection != 0) {
478 result.appendFormat("Connection Number: %zu \n", i);
479 connection->dump(result);
480 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700481 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700482
Peng Xue36e3472016-11-03 11:57:10 -0700483 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
484 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
485 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
486 if (connection != nullptr) {
487 result.appendFormat("Direct connection %zu:\n", i);
488 connection->dump(result);
489 }
490 }
491
Aravind Akella18d6d512015-06-18 14:18:28 -0700492 result.appendFormat("Previous Registrations:\n");
493 // Log in the reverse chronological order.
494 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
495 SENSOR_REGISTRATIONS_BUF_SIZE;
496 const int startIndex = currentIndex;
497 do {
498 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
499 if (SensorRegistrationInfo::isSentinel(reg_info)) {
500 // Ignore sentinel, proceed to next item.
501 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
502 SENSOR_REGISTRATIONS_BUF_SIZE;
503 continue;
504 }
Peng Xu51224682017-03-10 16:57:27 -0800505 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700506 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
507 SENSOR_REGISTRATIONS_BUF_SIZE;
508 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700509 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700510 }
511 write(fd, result.string(), result.size());
512 return NO_ERROR;
513}
514
Svet Ganove752a5c2018-01-15 17:14:20 -0800515// NOTE: This is a remote API - make sure all args are validated
516status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
517 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
518 return PERMISSION_DENIED;
519 }
520 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
521 return BAD_VALUE;
522 }
523 if (args.size() == 3 && args[0] == String16("set-uid-state")) {
524 return handleSetUidState(args, err);
525 } else if (args.size() == 2 && args[0] == String16("reset-uid-state")) {
526 return handleResetUidState(args, err);
527 } else if (args.size() == 2 && args[0] == String16("get-uid-state")) {
528 return handleGetUidState(args, out, err);
529 } else if (args.size() == 1 && args[0] == String16("help")) {
530 printHelp(out);
531 return NO_ERROR;
532 }
533 printHelp(err);
534 return BAD_VALUE;
535}
536
537status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
538 PermissionController pc;
539 int uid = pc.getPackageUid(args[1], 0);
540 if (uid <= 0) {
541 ALOGE("Unknown package: '%s'", String8(args[1]).string());
542 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
543 return BAD_VALUE;
544 }
545 bool active = false;
546 if (args[2] == String16("active")) {
547 active = true;
548 } else if ((args[2] != String16("idle"))) {
549 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
550 return BAD_VALUE;
551 }
552 mUidPolicy->addOverrideUid(uid, active);
553 return NO_ERROR;
554}
555
556status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
557 PermissionController pc;
558 int uid = pc.getPackageUid(args[1], 0);
559 if (uid < 0) {
560 ALOGE("Unknown package: '%s'", String8(args[1]).string());
561 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
562 return BAD_VALUE;
563 }
564 mUidPolicy->removeOverrideUid(uid);
565 return NO_ERROR;
566}
567
568status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
569 PermissionController pc;
570 int uid = pc.getPackageUid(args[1], 0);
571 if (uid < 0) {
572 ALOGE("Unknown package: '%s'", String8(args[1]).string());
573 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
574 return BAD_VALUE;
575 }
576 if (mUidPolicy->isUidActive(uid)) {
577 return dprintf(out, "active\n");
578 } else {
579 return dprintf(out, "idle\n");
580 }
581}
582
583status_t SensorService::printHelp(int out) {
584 return dprintf(out, "Sensor service commands:\n"
585 " get-uid-state <PACKAGE> gets the uid state\n"
586 " set-uid-state <PACKAGE> <active|idle> overrides the uid state\n"
587 " reset-uid-state <PACKAGE> clears the uid state override\n"
588 " help print this message\n");
589}
590
Peng Xu0cc8f802016-04-05 23:46:03 -0700591//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800592void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700593 sensors_event_t const* buffer, const int count) {
594 for (int i=0 ; i<count ; i++) {
595 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700596 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
597 handle = buffer[i].meta_data.sensor;
598 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700599 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700600 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700601 // If this buffer has an event from a one_shot sensor and this connection is registered
602 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700603 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700604 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
605 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800606 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700607 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700608
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700609 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700610 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700611}
612
Peng Xu47e96012016-03-28 17:55:56 -0700613bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000614 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700615
Peng Xueb4d6282015-12-10 18:02:41 -0800616 // each virtual sensor could generate an event per "real" event, that's why we need to size
617 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
618 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700619 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700620 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700621 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700622
Mathias Agopianf001c922010-11-11 17:58:51 -0800623 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700624
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700625 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700626 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700627 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
628 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000629 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700630 break;
631 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700632
633 // Reset sensors_event_t.flags to zero for all events in the buffer.
634 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700635 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700636 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700637
Peng Xueb4d6282015-12-10 18:02:41 -0800638 // Make a copy of the connection vector as some connections may be removed during the course
639 // of this loop (especially when one-shot sensor events are present in the sensor_event
640 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
641 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
642 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
643 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700644 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700645 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800646
Aravind Akella9a844cf2014-02-11 18:58:52 -0800647 Mutex::Autolock _l(mLock);
648 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
649 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
650 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
651 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
652 // releasing the wakelock.
653 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700654 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700655 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800656 bufferHasWakeUpEvent = true;
657 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700658 }
659 }
660
Aravind Akella9a844cf2014-02-11 18:58:52 -0800661 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700662 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800663 }
Aravind Akella8493b792014-09-08 15:45:47 -0700664 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800665
Mathias Agopianf001c922010-11-11 17:58:51 -0800666 // handle virtual sensors
667 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700668 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700669 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800670 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700671 SensorFusion& fusion(SensorFusion::getInstance());
672 if (fusion.isEnabled()) {
673 for (size_t i=0 ; i<size_t(count) ; i++) {
674 fusion.process(event[i]);
675 }
676 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700677 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700678 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700679 if (count + k >= minBufferSize) {
680 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700681 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700682 count, k, minBufferSize);
683 break;
684 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800685 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700686 sp<SensorInterface> si = mSensors.getInterface(handle);
687 if (si == nullptr) {
688 ALOGE("handle %d is not an valid virtual sensor", handle);
689 continue;
690 }
691
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700692 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700693 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800694 k++;
695 }
696 }
697 }
698 if (k) {
699 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700700 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800701 count += k;
702 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700703 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700704 }
705 }
706 }
707
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700708 // handle backward compatibility for RotationVector sensor
709 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
710 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700711 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700712 // All the 4 components of the quaternion should be available
713 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700714 mSensorEventBuffer[i].data[4] = -1;
715 }
716 }
717 }
718
Aravind Akella8493b792014-09-08 15:45:47 -0700719 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700720 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
721 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
722 // SensorEventConnection mapped to the corresponding flush_complete_event in
723 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700724 mMapFlushEventsToConnections[i] = NULL;
725 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
726 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
727 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
728 if (rec != NULL) {
729 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
730 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700731 }
732 }
Peng Xu2576cb62016-01-20 00:22:09 -0800733
734 // handle dynamic sensor meta events, process registration and unregistration of dynamic
735 // sensor based on content of event.
736 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
737 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
738 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
739 const sensor_t& dynamicSensor =
740 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
741 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
742 handle, dynamicSensor.type, dynamicSensor.name);
743
Peng Xu0cc8f802016-04-05 23:46:03 -0700744 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800745 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700746 sensor_t s = dynamicSensor;
747 // make sure the dynamic sensor flag is set
748 s.flags |= DYNAMIC_SENSOR_MASK;
749 // force the handle to be consistent
750 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800751
752 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800753
Peng Xu0cc8f802016-04-05 23:46:03 -0700754 // This will release hold on dynamic sensor meta, so it should be called
755 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700756 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800757 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700758 } else {
759 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
760 }
Peng Xu2576cb62016-01-20 00:22:09 -0800761 } else {
762 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
763 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
764
765 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800766 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800767 ALOGE("Dynamic sensor release error.");
768 }
769
770 size_t numConnections = activeConnections.size();
771 for (size_t i=0 ; i < numConnections; ++i) {
772 if (activeConnections[i] != NULL) {
773 activeConnections[i]->removeSensor(handle);
774 }
775 }
776 }
777 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700778 }
779
Aravind Akella9a844cf2014-02-11 18:58:52 -0800780 // Send our events to clients. Check the state of wake lock for each client and release the
781 // lock if none of the clients need it.
782 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700783 size_t numConnections = activeConnections.size();
784 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700785 if (activeConnections[i] != 0) {
786 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700787 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700788 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700789 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
790 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700791 if (activeConnections[i]->hasOneShotSensors()) {
792 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
793 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700794 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800795 }
796 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700797
Aravind Akella9a844cf2014-02-11 18:58:52 -0800798 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700799 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800800 }
Aravind Akella8493b792014-09-08 15:45:47 -0700801 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700802
Steve Block3c20fbe2012-01-05 23:22:43 +0000803 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800804 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700805 return false;
806}
807
Aravind Akella56ae4262014-07-10 16:01:10 -0700808sp<Looper> SensorService::getLooper() const {
809 return mLooper;
810}
811
Aravind Akellab4373ac2014-10-29 17:55:20 -0700812void SensorService::resetAllWakeLockRefCounts() {
813 SortedVector< sp<SensorEventConnection> > activeConnections;
814 populateActiveConnections(&activeConnections);
815 {
816 Mutex::Autolock _l(mLock);
817 for (size_t i=0 ; i < activeConnections.size(); ++i) {
818 if (activeConnections[i] != 0) {
819 activeConnections[i]->resetWakeLockRefCount();
820 }
821 }
822 setWakeLockAcquiredLocked(false);
823 }
824}
825
826void SensorService::setWakeLockAcquiredLocked(bool acquire) {
827 if (acquire) {
828 if (!mWakeLockAcquired) {
829 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
830 mWakeLockAcquired = true;
831 }
832 mLooper->wake();
833 } else {
834 if (mWakeLockAcquired) {
835 release_wake_lock(WAKE_LOCK_NAME);
836 mWakeLockAcquired = false;
837 }
838 }
839}
840
Aravind Akellab4373ac2014-10-29 17:55:20 -0700841bool SensorService::isWakeLockAcquired() {
842 Mutex::Autolock _l(mLock);
843 return mWakeLockAcquired;
844}
845
Aravind Akella56ae4262014-07-10 16:01:10 -0700846bool SensorService::SensorEventAckReceiver::threadLoop() {
847 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700848 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700849 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700850 bool wakeLockAcquired = mService->isWakeLockAcquired();
851 int timeout = -1;
852 if (wakeLockAcquired) timeout = 5000;
853 int ret = looper->pollOnce(timeout);
854 if (ret == ALOOPER_POLL_TIMEOUT) {
855 mService->resetAllWakeLockRefCounts();
856 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700857 } while(!Thread::exitPending());
858 return false;
859}
860
Aravind Akella9a844cf2014-02-11 18:58:52 -0800861void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800862 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800863 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800864 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
865 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800866 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800867 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800868 }
Peng Xu2576cb62016-01-20 00:22:09 -0800869
Peng Xu6a2d3a02015-12-21 12:00:23 -0800870 auto logger = mRecentEvent.find(buffer[i].sensor);
871 if (logger != mRecentEvent.end()) {
872 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800873 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800874 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800875}
876
Peng Xu47e96012016-03-28 17:55:56 -0700877void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800878 struct compar {
879 static int cmp(void const* lhs, void const* rhs) {
880 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
881 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700882 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800883 }
884 };
885 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
886}
887
Mathias Agopian5d270722010-07-19 15:20:39 -0700888String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700889 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700890}
891
Aravind Akellab4099e72013-10-15 15:43:10 -0700892bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700893 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
894 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700895}
896
Aravind Akella9a844cf2014-02-11 18:58:52 -0800897bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700898 int handle = event.sensor;
899 if (event.type == SENSOR_TYPE_META_DATA) {
900 handle = event.meta_data.sensor;
901 }
Peng Xu755c4512016-04-07 23:15:14 -0700902 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
903 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800904}
905
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700906int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
907 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
908 // UUID is not supported for this device.
909 return 0;
910 }
911 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
912 // This sensor can be uniquely identified in the system by
913 // the combination of its type and name.
914 return -1;
915 }
916
917 // We have a dynamic sensor.
918
919 if (!sHmacGlobalKeyIsValid) {
920 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
921 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
922 return 0;
923 }
924
925 // We want each app author/publisher to get a different ID, so that the
926 // same dynamic sensor cannot be tracked across apps by multiple
927 // authors/publishers. So we use both our UUID and our User ID.
928 // Note potential confusion:
929 // UUID => Universally Unique Identifier.
930 // UID => User Identifier.
931 // We refrain from using "uid" except as needed by API to try to
932 // keep this distinction clear.
933
934 auto appUserId = IPCThreadState::self()->getCallingUid();
935 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
936 memcpy(uuidAndApp, &uuid, sizeof(uuid));
937 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
938
939 // Now we use our key on our UUID/app combo to get the hash.
940 uint8_t hash[EVP_MAX_MD_SIZE];
941 unsigned int hashLen;
942 if (HMAC(EVP_sha256(),
943 sHmacGlobalKey, sizeof(sHmacGlobalKey),
944 uuidAndApp, sizeof(uuidAndApp),
945 hash, &hashLen) == nullptr) {
946 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
947 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
948 return 0;
949 }
950
951 int32_t id = 0;
952 if (hashLen < sizeof(id)) {
953 // We never expect this case, but out of paranoia, we handle it.
954 // Our 'id' length is already quite small, we don't want the
955 // effective length of it to be even smaller.
956 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
957 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
958 return 0;
959 }
960
961 // This is almost certainly less than all of 'hash', but it's as secure
962 // as we can be with our current 'id' length.
963 memcpy(&id, hash, sizeof(id));
964
965 // Note at the beginning of the function that we return the values of
966 // 0 and -1 to represent special cases. As a result, we can't return
967 // those as dynamic sensor IDs. If we happened to hash to one of those
968 // values, we change 'id' so we report as a dynamic sensor, and not as
969 // one of those special cases.
970 if (id == -1) {
971 id = -2;
972 } else if (id == 0) {
973 id = 1;
974 }
975 return id;
976}
977
978void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
979 for (auto &sensor : sensorList) {
980 int32_t id = getIdFromUuid(sensor.getUuid());
981 sensor.setId(id);
982 }
983}
984
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800985Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -0700986 char value[PROPERTY_VALUE_MAX];
987 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000988 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700989 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000990 Vector<Sensor> accessibleSensorList;
991 for (size_t i = 0; i < initialSensorList.size(); i++) {
992 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800993 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -0700994 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700995 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +0000996 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700997}
998
Peng Xu47e96012016-03-28 17:55:56 -0700999Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001000 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001001 mSensors.forEachSensor(
1002 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001003 if (sensor.isDynamicSensor()) {
1004 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1005 accessibleSensorList.add(sensor);
1006 } else {
1007 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1008 sensor.getName().string(),
1009 sensor.getRequiredPermission().string(),
1010 sensor.getRequiredAppOp());
1011 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001012 }
1013 return true;
1014 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001015 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001016 return accessibleSensorList;
1017}
1018
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001019sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001020 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001021 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1022 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
1023 return NULL;
1024 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001025
1026 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001027 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1028 // operating in DI mode.
1029 if (requestedMode == DATA_INJECTION) {
1030 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
1031 if (!isWhiteListedPackage(packageName)) return NULL;
1032 }
1033
Mathias Agopian5307d172012-09-18 17:02:43 -07001034 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001035 pid_t pid = IPCThreadState::self()->getCallingPid();
1036
1037 String8 connPackageName =
1038 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1039 String16 connOpPackageName =
1040 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001041 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001042 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001043 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001044 if (requestedMode == DATA_INJECTION) {
1045 if (mActiveConnections.indexOf(result) < 0) {
1046 mActiveConnections.add(result);
1047 }
1048 // Add the associated file descriptor to the Looper for polling whenever there is data to
1049 // be injected.
1050 result->updateLooperRegistration(mLooper);
1051 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001052 return result;
1053}
1054
Aravind Akella841a5922015-06-29 12:37:48 -07001055int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001056 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001057 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001058}
1059
Peng Xue36e3472016-11-03 11:57:10 -07001060sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1061 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1062 const native_handle *resource) {
1063 Mutex::Autolock _l(mLock);
1064
1065 struct sensors_direct_mem_t mem = {
1066 .type = type,
1067 .format = format,
1068 .size = size,
1069 .handle = resource,
1070 };
1071 uid_t uid = IPCThreadState::self()->getCallingUid();
1072
1073 if (mem.handle == nullptr) {
1074 ALOGE("Failed to clone resource handle");
1075 return nullptr;
1076 }
1077
1078 // check format
1079 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1080 ALOGE("Direct channel format %d is unsupported!", format);
1081 return nullptr;
1082 }
1083
1084 // check for duplication
1085 for (auto &i : mDirectConnections) {
1086 sp<SensorDirectConnection> connection(i.promote());
1087 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001088 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001089 return nullptr;
1090 }
1091 }
1092
1093 // check specific to memory type
1094 switch(type) {
1095 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
1096 int fd = resource->data[0];
1097 int size2 = ashmem_get_size_region(fd);
1098 // check size consistency
Peng Xuf88e2b92017-04-10 15:52:58 -07001099 if (size2 < static_cast<int>(size)) {
1100 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1101 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001102 return nullptr;
1103 }
1104 break;
1105 }
1106 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001107 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001108 break;
1109 default:
1110 ALOGE("Unknown direct connection memory type %d", type);
1111 return nullptr;
1112 }
1113
1114 native_handle_t *clone = native_handle_clone(resource);
1115 if (!clone) {
1116 return nullptr;
1117 }
1118
1119 SensorDirectConnection* conn = nullptr;
1120 SensorDevice& dev(SensorDevice::getInstance());
1121 int channelHandle = dev.registerDirectChannel(&mem);
1122
1123 if (channelHandle <= 0) {
1124 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1125 } else {
1126 mem.handle = clone;
1127 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1128 }
1129
1130 if (conn == nullptr) {
1131 native_handle_close(clone);
1132 native_handle_delete(clone);
1133 } else {
1134 // add to list of direct connections
1135 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1136 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1137 }
1138 return conn;
1139}
1140
Peng Xudd5c5cb2017-03-16 17:39:43 -07001141int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001142 int32_t handle, int32_t type,
1143 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001144 Mutex::Autolock _l(mLock);
1145
Alexey Polyudov88711e82017-05-23 19:54:04 -07001146 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001147 return PERMISSION_DENIED;
1148 }
1149
1150 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001151 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001152 size_t expectSize = INT32_MAX;
1153 switch (type) {
1154 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1155 isFloat = true;
1156 expectSize = 3;
1157 break;
1158 case AINFO_LOCAL_GRAVITY:
1159 isFloat = true;
1160 expectSize = 1;
1161 break;
1162 case AINFO_DOCK_STATE:
1163 case AINFO_HIGH_PERFORMANCE_MODE:
1164 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1165 isFloat = false;
1166 expectSize = 1;
1167 break;
1168 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001169 // CUSTOM events must only contain float data; it may have variable size
1170 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1171 ints.size() ||
1172 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1173 handle < 0) {
1174 return BAD_VALUE;
1175 }
1176 isFloat = true;
1177 isCustom = true;
1178 expectSize = floats.size();
1179 break;
1180 }
1181
1182 if (!isCustom && handle != -1) {
1183 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001184 }
1185
1186 // three events: first one is begin tag, last one is end tag, the one in the middle
1187 // is the payload.
1188 sensors_event_t event[3];
1189 int64_t timestamp = elapsedRealtimeNano();
1190 for (sensors_event_t* i = event; i < event + 3; i++) {
1191 *i = (sensors_event_t) {
1192 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001193 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001194 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1195 .timestamp = timestamp++,
1196 .additional_info = (additional_info_event_t) {
1197 .serial = 0
1198 }
1199 };
1200 }
1201
1202 event[0].additional_info.type = AINFO_BEGIN;
1203 event[1].additional_info.type = type;
1204 event[2].additional_info.type = AINFO_END;
1205
1206 if (isFloat) {
1207 if (floats.size() != expectSize) {
1208 return BAD_VALUE;
1209 }
1210 for (size_t i = 0; i < expectSize; ++i) {
1211 event[1].additional_info.data_float[i] = floats[i];
1212 }
1213 } else {
1214 if (ints.size() != expectSize) {
1215 return BAD_VALUE;
1216 }
1217 for (size_t i = 0; i < expectSize; ++i) {
1218 event[1].additional_info.data_int32[i] = ints[i];
1219 }
1220 }
1221
1222 SensorDevice& dev(SensorDevice::getInstance());
1223 for (sensors_event_t* i = event; i < event + 3; i++) {
1224 int ret = dev.injectSensorData(i);
1225 if (ret != NO_ERROR) {
1226 return ret;
1227 }
1228 }
1229 return NO_ERROR;
1230}
1231
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001232status_t SensorService::resetToNormalMode() {
1233 Mutex::Autolock _l(mLock);
1234 return resetToNormalModeLocked();
1235}
1236
1237status_t SensorService::resetToNormalModeLocked() {
1238 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001239 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301240 if (err == NO_ERROR) {
1241 mCurrentOperatingMode = NORMAL;
1242 dev.enableAllSensors();
1243 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001244 return err;
1245}
1246
Peng Xu47e96012016-03-28 17:55:56 -07001247void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001248 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001249 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001250 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001251 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001252 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001253 int handle = mActiveSensors.keyAt(i);
1254 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001255 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001256 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1257 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001258 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001259 } else {
1260 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001261 }
Aravind Akella8a969552014-09-28 17:52:41 -07001262 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001263 }
1264 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001265 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001266 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001267 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001268 c, i, handle);
1269
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001270 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001271 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001272 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001273 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001274 delete rec;
1275 size--;
1276 } else {
1277 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001278 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001279 }
Aravind Akella8a969552014-09-28 17:52:41 -07001280 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001281 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001282 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001283 if (c->needsWakeLock()) {
1284 checkWakeLockStateLocked();
1285 }
Peng Xu4f707f82016-09-26 11:28:32 -07001286
1287 SensorDevice& dev(SensorDevice::getInstance());
1288 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001289}
1290
Peng Xue36e3472016-11-03 11:57:10 -07001291void SensorService::cleanupConnection(SensorDirectConnection* c) {
1292 Mutex::Autolock _l(mLock);
1293
1294 SensorDevice& dev(SensorDevice::getInstance());
1295 dev.unregisterDirectChannel(c->getHalChannelHandle());
1296 mDirectConnections.remove(c);
1297}
1298
Peng Xu755c4512016-04-07 23:15:14 -07001299sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001300 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001301}
1302
Mathias Agopianfc328812010-07-14 23:41:37 -07001303status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001304 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001305 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001306 if (mInitCheck != NO_ERROR)
1307 return mInitCheck;
1308
Peng Xu755c4512016-04-07 23:15:14 -07001309 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1310 if (sensor == nullptr ||
1311 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001312 return BAD_VALUE;
1313 }
1314
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001315 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001316 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001317 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001318 return INVALID_OPERATION;
1319 }
1320
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001321 SensorRecord* rec = mActiveSensors.valueFor(handle);
1322 if (rec == 0) {
1323 rec = new SensorRecord(connection);
1324 mActiveSensors.add(handle, rec);
1325 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001326 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001327 }
1328 } else {
1329 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001330 // this sensor is already activated, but we are adding a connection that uses it.
1331 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001332 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001333 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001334 // NOTE: The wake_up flag of this event may get set to
1335 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001336
1337 auto logger = mRecentEvent.find(handle);
1338 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001339 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -07001340 // It is unlikely that this buffer is empty as the sensor is already active.
1341 // One possible corner case may be two applications activating an on-change
1342 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001343 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001344 event.sensor = handle;
1345 if (event.version == sizeof(sensors_event_t)) {
1346 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1347 setWakeLockAcquiredLocked(true);
1348 }
1349 connection->sendEvents(&event, 1, NULL);
1350 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1351 checkWakeLockStateLocked();
1352 }
1353 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001354 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001355 }
1356 }
1357 }
1358 }
1359
1360 if (connection->addSensor(handle)) {
1361 BatteryService::enableSensor(connection->getUid(), handle);
1362 // the sensor was added (which means it wasn't already there)
1363 // so, see if this connection becomes active
1364 if (mActiveConnections.indexOf(connection) < 0) {
1365 mActiveConnections.add(connection);
1366 }
1367 } else {
1368 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1369 handle, connection.get());
1370 }
1371
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301372 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001373 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301374 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1375 samplingPeriodNs = maxDelayNs;
1376 }
1377
Aravind Akella724d91d2013-06-27 12:04:23 -07001378 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1379 if (samplingPeriodNs < minDelayNs) {
1380 samplingPeriodNs = minDelayNs;
1381 }
1382
Aravind Akella6c2664a2014-08-13 12:24:50 -07001383 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1384 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001385 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1386
Aravind Akella4949c502015-02-11 15:54:35 -08001387 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001388 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001389
Peng Xu20483c42015-10-26 15:14:43 -07001390 // Call flush() before calling activate() on the sensor. Wait for a first
1391 // flush complete event before sending events on this connection. Ignore
1392 // one-shot sensors which don't support flush(). Ignore on-change sensors
1393 // to maintain the on-change logic (any on-change events except the initial
1394 // one should be trigger by a change in value). Also if this sensor isn't
1395 // already active, don't call flush().
1396 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001397 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001398 rec->getNumConnections() > 1) {
1399 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001400 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001401 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001402 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001403 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001404 } else {
1405 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001406 }
1407 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001408
1409 if (err == NO_ERROR) {
1410 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1411 err = sensor->activate(connection.get(), true);
1412 }
1413
Aravind Akella8a969552014-09-28 17:52:41 -07001414 if (err == NO_ERROR) {
1415 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001416
1417 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1418 SensorRegistrationInfo(handle, connection->getPackageName(),
1419 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001420 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001421 }
1422
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001423 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001424 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001425 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001426 }
1427 return err;
1428}
1429
Peng Xu47e96012016-03-28 17:55:56 -07001430status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001431 if (mInitCheck != NO_ERROR)
1432 return mInitCheck;
1433
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001434 Mutex::Autolock _l(mLock);
1435 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001436 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001437 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1438 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001439
1440 }
1441 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001442 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1443 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001444 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001445 }
1446 return err;
1447}
1448
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001449status_t SensorService::cleanupWithoutDisable(
1450 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001451 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001452 return cleanupWithoutDisableLocked(connection, handle);
1453}
1454
1455status_t SensorService::cleanupWithoutDisableLocked(
1456 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001457 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001458 if (rec) {
1459 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001460 if (connection->removeSensor(handle)) {
1461 BatteryService::disableSensor(connection->getUid(), handle);
1462 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001463 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001464 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001465 mActiveConnections.remove(connection);
1466 }
1467 // see if this sensor becomes inactive
1468 if (rec->removeConnection(connection)) {
1469 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001470 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001471 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001472 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001473 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001474 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001475 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001476}
1477
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001478status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001479 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001480 if (mInitCheck != NO_ERROR)
1481 return mInitCheck;
1482
Peng Xu755c4512016-04-07 23:15:14 -07001483 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1484 if (sensor == nullptr ||
1485 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001486 return BAD_VALUE;
1487 }
1488
Mathias Agopian1cd70002010-07-21 15:59:50 -07001489 if (ns < 0)
1490 return BAD_VALUE;
1491
Mathias Agopian62569ec2011-11-07 21:21:47 -08001492 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1493 if (ns < minDelayNs) {
1494 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001495 }
1496
Mathias Agopianf001c922010-11-11 17:58:51 -08001497 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001498}
1499
Svetoslavb412f6e2015-04-29 16:50:41 -07001500status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1501 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001502 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001503 SensorDevice& dev(SensorDevice::getInstance());
1504 const int halVersion = dev.getHalDeviceVersion();
1505 status_t err(NO_ERROR);
1506 Mutex::Autolock _l(mLock);
1507 // Loop through all sensors for this connection and call flush on each of them.
1508 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1509 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001510 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1511 if (sensor == nullptr) {
1512 continue;
1513 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001514 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1515 ALOGE("flush called on a one-shot sensor");
1516 err = INVALID_OPERATION;
1517 continue;
1518 }
Aravind Akella8493b792014-09-08 15:45:47 -07001519 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001520 // For older devices just increment pending flush count which will send a trivial
1521 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001522 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001523 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001524 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1525 err = INVALID_OPERATION;
1526 continue;
1527 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001528 status_t err_flush = sensor->flush(connection.get(), handle);
1529 if (err_flush == NO_ERROR) {
1530 SensorRecord* rec = mActiveSensors.valueFor(handle);
1531 if (rec != NULL) rec->addPendingFlushConnection(connection);
1532 }
1533 err = (err_flush != NO_ERROR) ? err_flush : err;
1534 }
Aravind Akella70018042014-04-07 22:52:37 +00001535 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001536 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001537}
Aravind Akella70018042014-04-07 22:52:37 +00001538
Svetoslavb412f6e2015-04-29 16:50:41 -07001539bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1540 const String16& opPackageName) {
1541 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001542
Svetoslavb412f6e2015-04-29 16:50:41 -07001543 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001544 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001545 }
1546
1547 bool hasPermission = false;
1548
1549 // Runtime permissions can't use the cache as they may change.
1550 if (sensor.isRequiredPermissionRuntime()) {
1551 hasPermission = checkPermission(String16(requiredPermission),
1552 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001553 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001554 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1555 }
1556
1557 if (!hasPermission) {
1558 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1559 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001560 return false;
1561 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001562
1563 const int32_t opCode = sensor.getRequiredAppOp();
1564 if (opCode >= 0) {
1565 AppOpsManager appOps;
1566 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1567 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001568 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001569 operation, sensor.getName().string(), opCode);
1570 return false;
1571 }
1572 }
1573
1574 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001575}
1576
Aravind Akella9a844cf2014-02-11 18:58:52 -08001577void SensorService::checkWakeLockState() {
1578 Mutex::Autolock _l(mLock);
1579 checkWakeLockStateLocked();
1580}
1581
1582void SensorService::checkWakeLockStateLocked() {
1583 if (!mWakeLockAcquired) {
1584 return;
1585 }
1586 bool releaseLock = true;
1587 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1588 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1589 if (connection != 0) {
1590 if (connection->needsWakeLock()) {
1591 releaseLock = false;
1592 break;
1593 }
1594 }
1595 }
1596 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001597 setWakeLockAcquiredLocked(false);
1598 }
1599}
1600
1601void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1602 Mutex::Autolock _l(mLock);
1603 connection->writeToSocketFromCache();
1604 if (connection->needsWakeLock()) {
1605 setWakeLockAcquiredLocked(true);
1606 }
1607}
1608
1609void SensorService::populateActiveConnections(
1610 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1611 Mutex::Autolock _l(mLock);
1612 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1613 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1614 if (connection != 0) {
1615 activeConnections->add(connection);
1616 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001617 }
1618}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001619
Aravind Akella4949c502015-02-11 15:54:35 -08001620bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001621 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001622}
1623
Peng Xue36e3472016-11-03 11:57:10 -07001624bool SensorService::isOperationRestricted(const String16& opPackageName) {
1625 Mutex::Autolock _l(mLock);
1626 if (mCurrentOperatingMode != RESTRICTED) {
1627 String8 package(opPackageName);
1628 return !isWhiteListedPackage(package);
1629 }
1630 return false;
1631}
1632
Svet Ganove752a5c2018-01-15 17:14:20 -08001633void SensorService::UidPolicy::registerSelf() {
1634 ActivityManager am;
1635 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1636 | ActivityManager::UID_OBSERVER_IDLE
1637 | ActivityManager::UID_OBSERVER_ACTIVE,
1638 ActivityManager::PROCESS_STATE_UNKNOWN,
1639 String16("android"));
1640}
1641
1642void SensorService::UidPolicy::unregisterSelf() {
1643 ActivityManager am;
1644 am.unregisterUidObserver(this);
1645}
1646
1647void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1648 onUidIdle(uid, disabled);
1649}
1650
1651void SensorService::UidPolicy::onUidActive(uid_t uid) {
1652 {
1653 Mutex::Autolock _l(mUidLock);
1654 mActiveUids.insert(uid);
1655 }
1656 sp<SensorService> service = mService.promote();
1657 if (service != nullptr) {
1658 service->setSensorAccess(uid, true);
1659 }
1660}
1661
1662void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1663 bool deleted = false;
1664 {
1665 Mutex::Autolock _l(mUidLock);
1666 if (mActiveUids.erase(uid) > 0) {
1667 deleted = true;
1668 }
1669 }
1670 if (deleted) {
1671 sp<SensorService> service = mService.promote();
1672 if (service != nullptr) {
1673 service->setSensorAccess(uid, false);
1674 }
1675 }
1676}
1677
1678void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1679 updateOverrideUid(uid, active, true);
1680}
1681
1682void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1683 updateOverrideUid(uid, false, false);
1684}
1685
1686void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1687 bool wasActive = false;
1688 bool isActive = false;
1689 {
1690 Mutex::Autolock _l(mUidLock);
1691 wasActive = isUidActiveLocked(uid);
1692 mOverrideUids.erase(uid);
1693 if (insert) {
1694 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1695 }
1696 isActive = isUidActiveLocked(uid);
1697 }
1698 if (wasActive != isActive) {
1699 sp<SensorService> service = mService.promote();
1700 if (service != nullptr) {
1701 service->setSensorAccess(uid, isActive);
1702 }
1703 }
1704}
1705
1706bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1707 // Non-app UIDs are considered always active
1708 if (uid < FIRST_APPLICATION_UID) {
1709 return true;
1710 }
1711 Mutex::Autolock _l(mUidLock);
1712 return isUidActiveLocked(uid);
1713}
1714
1715bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1716 // Non-app UIDs are considered always active
1717 if (uid < FIRST_APPLICATION_UID) {
1718 return true;
1719 }
1720 auto it = mOverrideUids.find(uid);
1721 if (it != mOverrideUids.end()) {
1722 return it->second;
1723 }
1724 return mActiveUids.find(uid) != mActiveUids.end();
1725}
1726
Mathias Agopianfc328812010-07-14 23:41:37 -07001727}; // namespace android