blob: f4e728bc3620f1556280bcd6acbb19faeddfc47d [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
Brian Stack51498e62018-10-03 10:52:21 -070050#include <ctime>
Peng Xueb4d6282015-12-10 18:02:41 -080051#include <inttypes.h>
52#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070053#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080054#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080055#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070056#include <sys/stat.h>
57#include <sys/types.h>
58#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070059
Svet Ganove752a5c2018-01-15 17:14:20 -080060#include <private/android_filesystem_config.h>
61
Mathias Agopianfc328812010-07-14 23:41:37 -070062namespace android {
63// ---------------------------------------------------------------------------
64
Mathias Agopian33015422011-05-27 18:18:13 -070065/*
66 * Notes:
67 *
68 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070069 * - run mag sensor from time to time to force calibration
70 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
71 *
72 */
73
Aravind Akella8ef3c892015-07-10 11:24:28 -070074const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070075uint8_t SensorService::sHmacGlobalKey[128] = {};
76bool SensorService::sHmacGlobalKeyIsValid = false;
77
78#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
79#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070080#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070081
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070082// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070083static const String16 sDumpPermission("android.permission.DUMP");
84static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080085static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070086
Mathias Agopianfc328812010-07-14 23:41:37 -070087SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070088 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070089 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +090090 mUidPolicy = new UidPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -070091}
92
Greg Kaiser53ca2e02016-06-21 16:11:14 -070093bool SensorService::initializeHmacKey() {
94 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
95 if (fd != -1) {
96 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
97 close(fd);
98 if (result == sizeof(sHmacGlobalKey)) {
99 return true;
100 }
101 ALOGW("Unable to read HMAC key; generating new one.");
102 }
103
104 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
105 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
106 return false;
107 }
108
109 // We need to make sure this is only readable to us.
110 bool wroteKey = false;
111 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
112 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
113 S_IRUSR|S_IWUSR);
114 if (fd != -1) {
115 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
116 close(fd);
117 wroteKey = (result == sizeof(sHmacGlobalKey));
118 }
119 if (wroteKey) {
120 ALOGI("Generated new HMAC key.");
121 } else {
122 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
123 "after reboot.");
124 }
125 // Even if we failed to write the key we return true, because we did
126 // initialize the HMAC key.
127 return true;
128}
129
Peng Xu98d30f62016-08-01 18:12:11 -0700130// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
131void SensorService::enableSchedFifoMode() {
132 struct sched_param param = {0};
133 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
134 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
135 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
136 }
137}
138
Peng Xu47e96012016-03-28 17:55:56 -0700139void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000140 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800141 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700142
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700143 sHmacGlobalKeyIsValid = initializeHmacKey();
144
Mathias Agopianf001c922010-11-11 17:58:51 -0800145 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800146 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700147 ssize_t count = dev.getSensorList(&list);
148 if (count > 0) {
149 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700150 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700151 uint32_t virtualSensorsNeeds =
152 (1<<SENSOR_TYPE_GRAVITY) |
153 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700154 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
155 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
156 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700157
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700158 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700159 bool useThisSensor=true;
160
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700161 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700162 case SENSOR_TYPE_ACCELEROMETER:
163 hasAccel = true;
164 break;
165 case SENSOR_TYPE_MAGNETIC_FIELD:
166 hasMag = true;
167 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700168 case SENSOR_TYPE_ORIENTATION:
169 orientationIndex = i;
170 break;
171 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700172 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700173 hasGyro = true;
174 break;
175 case SENSOR_TYPE_GRAVITY:
176 case SENSOR_TYPE_LINEAR_ACCELERATION:
177 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700178 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
179 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
180 if (IGNORE_HARDWARE_FUSION) {
181 useThisSensor = false;
182 } else {
183 virtualSensorsNeeds &= ~(1<<list[i].type);
184 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700185 break;
186 }
Peng Xuf66684a2015-07-23 11:41:53 -0700187 if (useThisSensor) {
188 registerSensor( new HardwareSensor(list[i]) );
189 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700190 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700191
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700192 // it's safe to instantiate the SensorFusion object here
193 // (it wants to be instantiated after h/w sensors have been
194 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700195 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700196
Aravind Akellaf5047892015-07-20 17:29:33 -0700197 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700198 // Add Android virtual sensors if they're not already
199 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700200 bool needRotationVector =
201 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700202
Peng Xu0cc8f802016-04-05 23:46:03 -0700203 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
204 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700205
Peng Xu0cc8f802016-04-05 23:46:03 -0700206 bool needLinearAcceleration =
207 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700208
Peng Xu0cc8f802016-04-05 23:46:03 -0700209 registerSensor(new LinearAccelerationSensor(list, count),
210 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700211
Peng Xu0cc8f802016-04-05 23:46:03 -0700212 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700213 registerSensor( new CorrectedGyroSensor(list, count), true, true);
214 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700215 }
216
Peng Xuf66684a2015-07-23 11:41:53 -0700217 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700218 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
219 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700220
Peng Xu0cc8f802016-04-05 23:46:03 -0700221 bool needGameRotationVector =
222 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
223 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700224 }
225
226 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700227 bool needGeoMagRotationVector =
228 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
229 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700230 }
231
Aravind Akella5466c3d2014-08-22 16:11:10 -0700232 // Check if the device really supports batching by looking at the FIFO event
233 // counts for each sensor.
234 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700235 mSensors.forEachSensor(
236 [&batchingSupported] (const Sensor& s) -> bool {
237 if (s.getFifoMaxEventCount() > 0) {
238 batchingSupported = true;
239 }
240 return !batchingSupported;
241 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700242
243 if (batchingSupported) {
244 // Increase socket buffer size to a max of 100 KB for batching capabilities.
245 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
246 } else {
247 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
248 }
249
250 // Compare the socketBufferSize value against the system limits and limit
251 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700252 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
253 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700254 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700255 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700256 size_t maxSystemSocketBufferSize;
257 sscanf(line, "%zu", &maxSystemSocketBufferSize);
258 if (mSocketBufferSize > maxSystemSocketBufferSize) {
259 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700260 }
261 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700262 if (fp) {
263 fclose(fp);
264 }
265
Aravind Akella9a844cf2014-02-11 18:58:52 -0800266 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700267 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700268 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
269 mSensorEventBuffer = new sensors_event_t[minBufferSize];
270 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700271 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700272 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700273
Aravind Akella18d6d512015-06-18 14:18:28 -0700274 mNextSensorRegIndex = 0;
275 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
276 mLastNSensorRegistrations.push();
277 }
278
279 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700280 mAckReceiver = new SensorEventAckReceiver(this);
281 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700282 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700283
284 // priority can only be changed after run
285 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800286
287 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800288 mUidPolicy->registerSelf();
289 }
290 }
291}
292
293void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
294 SortedVector< sp<SensorEventConnection> > activeConnections;
295 populateActiveConnections(&activeConnections);
296 {
297 Mutex::Autolock _l(mLock);
298 for (size_t i = 0 ; i < activeConnections.size(); i++) {
Yi Kong8f313e32018-07-17 14:13:29 -0700299 if (activeConnections[i] != nullptr && activeConnections[i]->getUid() == uid) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800300 activeConnections[i]->setSensorAccess(hasAccess);
301 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700302 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700303 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700304}
305
Peng Xu0cc8f802016-04-05 23:46:03 -0700306const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
307 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800308 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700309 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700310 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700311 return s->getSensor();
312 } else {
313 return mSensors.getNonSensor();
314 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800315}
316
Peng Xu6a2d3a02015-12-21 12:00:23 -0800317const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700318 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800319}
320
Peng Xu6a2d3a02015-12-21 12:00:23 -0800321bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700322 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800323
324 const auto i = mRecentEvent.find(handle);
325 if (i != mRecentEvent.end()) {
326 delete i->second;
327 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800328 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700329 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800330}
331
Peng Xu0cc8f802016-04-05 23:46:03 -0700332const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
333 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700334}
335
Peng Xu47e96012016-03-28 17:55:56 -0700336SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800337 for (auto && entry : mRecentEvent) {
338 delete entry.second;
339 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800340 mUidPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700341}
342
343status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700344 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700345 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800346 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700347 IPCThreadState::self()->getCallingPid(),
348 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700349 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700350 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700351 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800352 return INVALID_OPERATION;
353 }
354 Mutex::Autolock _l(mLock);
355 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700356 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700357 // If already in restricted mode. Ignore.
358 if (mCurrentOperatingMode == RESTRICTED) {
359 return status_t(NO_ERROR);
360 }
361 // If in any mode other than normal, ignore.
362 if (mCurrentOperatingMode != NORMAL) {
363 return INVALID_OPERATION;
364 }
Peng Xue36e3472016-11-03 11:57:10 -0700365
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700366 mCurrentOperatingMode = RESTRICTED;
Peng Xue36e3472016-11-03 11:57:10 -0700367 // temporarily stop all sensor direct report
368 for (auto &i : mDirectConnections) {
369 sp<SensorDirectConnection> connection(i.promote());
370 if (connection != nullptr) {
371 connection->stopAll(true /* backupRecord */);
372 }
373 }
374
Aravind Akella4949c502015-02-11 15:54:35 -0800375 dev.disableAllSensors();
376 // Clear all pending flush connections for all active sensors. If one of the active
377 // connections has called flush() and the underlying sensor has been disabled before a
378 // flush complete event is returned, we need to remove the connection from this queue.
379 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
380 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
381 }
Aravind Akella841a5922015-06-29 12:37:48 -0700382 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700383 return status_t(NO_ERROR);
384 } else if (args.size() == 1 && args[0] == String16("enable")) {
385 // If currently in restricted mode, reset back to NORMAL mode else ignore.
386 if (mCurrentOperatingMode == RESTRICTED) {
387 mCurrentOperatingMode = NORMAL;
388 dev.enableAllSensors();
Peng Xue36e3472016-11-03 11:57:10 -0700389 // recover all sensor direct report
390 for (auto &i : mDirectConnections) {
391 sp<SensorDirectConnection> connection(i.promote());
392 if (connection != nullptr) {
393 connection->recoverAll();
394 }
395 }
Aravind Akella444f2672015-05-07 12:40:52 -0700396 }
Aravind Akella841a5922015-06-29 12:37:48 -0700397 if (mCurrentOperatingMode == DATA_INJECTION) {
398 resetToNormalModeLocked();
399 }
400 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700401 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700402 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
403 if (mCurrentOperatingMode == NORMAL) {
404 dev.disableAllSensors();
405 status_t err = dev.setMode(DATA_INJECTION);
406 if (err == NO_ERROR) {
407 mCurrentOperatingMode = DATA_INJECTION;
408 } else {
409 // Re-enable sensors.
410 dev.enableAllSensors();
411 }
412 mWhiteListedPackage.setTo(String8(args[1]));
413 return NO_ERROR;
414 } else if (mCurrentOperatingMode == DATA_INJECTION) {
415 // Already in DATA_INJECTION mode. Treat this as a no_op.
416 return NO_ERROR;
417 } else {
418 // Transition to data injection mode supported only from NORMAL mode.
419 return INVALID_OPERATION;
420 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700421 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700422 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700423 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700424 } else {
425 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700426 //
Brian Stack51498e62018-10-03 10:52:21 -0700427 timespec curTime;
428 clock_gettime(CLOCK_REALTIME, &curTime);
429 struct tm* timeinfo = localtime(&(curTime.tv_sec));
430 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
431 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800432 result.append("Sensor Device:\n");
433 result.append(SensorDevice::getInstance().dump().c_str());
434
435 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700436 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700437
Peng Xu6a2d3a02015-12-21 12:00:23 -0800438 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700439 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700440
Peng Xu0cc8f802016-04-05 23:46:03 -0700441 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800442 for (auto&& i : mRecentEvent) {
443 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700444 if (!i.second->isEmpty()) {
445 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
446 i.second->setFormat("normal");
447 } else {
448 i.second->setFormat("mask_data");
449 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800450 // if there is events and sensor does not need special permission.
451 result.appendFormat("%s: ", s->getSensor().getName().string());
452 result.append(i.second->dump().c_str());
453 }
454 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700455
Aravind Akella444f2672015-05-07 12:40:52 -0700456 result.append("Active sensors:\n");
457 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
458 int handle = mActiveSensors.keyAt(i);
459 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
460 getSensorName(handle).string(),
461 handle,
462 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700463 }
464
Andreas Gamped4036b62015-07-28 13:49:04 -0700465 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700466 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700467 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
468 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700469 result.appendFormat("Mode :");
470 switch(mCurrentOperatingMode) {
471 case NORMAL:
472 result.appendFormat(" NORMAL\n");
473 break;
474 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700475 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700476 break;
477 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700478 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700479 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700480
Peng Xue36e3472016-11-03 11:57:10 -0700481 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella444f2672015-05-07 12:40:52 -0700482 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
483 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -0700484 if (connection != nullptr) {
Aravind Akella444f2672015-05-07 12:40:52 -0700485 result.appendFormat("Connection Number: %zu \n", i);
486 connection->dump(result);
487 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700488 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700489
Peng Xue36e3472016-11-03 11:57:10 -0700490 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
491 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
492 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
493 if (connection != nullptr) {
494 result.appendFormat("Direct connection %zu:\n", i);
495 connection->dump(result);
496 }
497 }
498
Aravind Akella18d6d512015-06-18 14:18:28 -0700499 result.appendFormat("Previous Registrations:\n");
500 // Log in the reverse chronological order.
501 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
502 SENSOR_REGISTRATIONS_BUF_SIZE;
503 const int startIndex = currentIndex;
504 do {
505 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
506 if (SensorRegistrationInfo::isSentinel(reg_info)) {
507 // Ignore sentinel, proceed to next item.
508 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
509 SENSOR_REGISTRATIONS_BUF_SIZE;
510 continue;
511 }
Peng Xu51224682017-03-10 16:57:27 -0800512 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700513 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
514 SENSOR_REGISTRATIONS_BUF_SIZE;
515 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700516 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700517 }
518 write(fd, result.string(), result.size());
519 return NO_ERROR;
520}
521
Svet Ganove752a5c2018-01-15 17:14:20 -0800522// NOTE: This is a remote API - make sure all args are validated
523status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
524 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
525 return PERMISSION_DENIED;
526 }
527 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
528 return BAD_VALUE;
529 }
530 if (args.size() == 3 && args[0] == String16("set-uid-state")) {
531 return handleSetUidState(args, err);
532 } else if (args.size() == 2 && args[0] == String16("reset-uid-state")) {
533 return handleResetUidState(args, err);
534 } else if (args.size() == 2 && args[0] == String16("get-uid-state")) {
535 return handleGetUidState(args, out, err);
536 } else if (args.size() == 1 && args[0] == String16("help")) {
537 printHelp(out);
538 return NO_ERROR;
539 }
540 printHelp(err);
541 return BAD_VALUE;
542}
543
544status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
545 PermissionController pc;
546 int uid = pc.getPackageUid(args[1], 0);
547 if (uid <= 0) {
548 ALOGE("Unknown package: '%s'", String8(args[1]).string());
549 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
550 return BAD_VALUE;
551 }
552 bool active = false;
553 if (args[2] == String16("active")) {
554 active = true;
555 } else if ((args[2] != String16("idle"))) {
556 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
557 return BAD_VALUE;
558 }
559 mUidPolicy->addOverrideUid(uid, active);
560 return NO_ERROR;
561}
562
563status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
564 PermissionController pc;
565 int uid = pc.getPackageUid(args[1], 0);
566 if (uid < 0) {
567 ALOGE("Unknown package: '%s'", String8(args[1]).string());
568 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
569 return BAD_VALUE;
570 }
571 mUidPolicy->removeOverrideUid(uid);
572 return NO_ERROR;
573}
574
575status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
576 PermissionController pc;
577 int uid = pc.getPackageUid(args[1], 0);
578 if (uid < 0) {
579 ALOGE("Unknown package: '%s'", String8(args[1]).string());
580 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
581 return BAD_VALUE;
582 }
583 if (mUidPolicy->isUidActive(uid)) {
584 return dprintf(out, "active\n");
585 } else {
586 return dprintf(out, "idle\n");
587 }
588}
589
590status_t SensorService::printHelp(int out) {
591 return dprintf(out, "Sensor service commands:\n"
592 " get-uid-state <PACKAGE> gets the uid state\n"
593 " set-uid-state <PACKAGE> <active|idle> overrides the uid state\n"
594 " reset-uid-state <PACKAGE> clears the uid state override\n"
595 " help print this message\n");
596}
597
Peng Xu0cc8f802016-04-05 23:46:03 -0700598//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800599void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700600 sensors_event_t const* buffer, const int count) {
601 for (int i=0 ; i<count ; i++) {
602 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700603 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
604 handle = buffer[i].meta_data.sensor;
605 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700606 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700607 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700608 // If this buffer has an event from a one_shot sensor and this connection is registered
609 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700610 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700611 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
612 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800613 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700614 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700615
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700616 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700617 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700618}
619
Peng Xu47e96012016-03-28 17:55:56 -0700620bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000621 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700622
Peng Xueb4d6282015-12-10 18:02:41 -0800623 // each virtual sensor could generate an event per "real" event, that's why we need to size
624 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
625 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700626 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700627 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700628 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700629
Mathias Agopianf001c922010-11-11 17:58:51 -0800630 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700631
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700632 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700633 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700634 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
635 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000636 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700637 break;
638 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700639
640 // Reset sensors_event_t.flags to zero for all events in the buffer.
641 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700642 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700643 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700644
Peng Xueb4d6282015-12-10 18:02:41 -0800645 // Make a copy of the connection vector as some connections may be removed during the course
646 // of this loop (especially when one-shot sensor events are present in the sensor_event
647 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
648 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
649 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
650 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700651 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700652 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800653
Aravind Akella9a844cf2014-02-11 18:58:52 -0800654 Mutex::Autolock _l(mLock);
655 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
656 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
657 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
658 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
659 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700660 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700661 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700662 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700663 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700664 }
665 }
666
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700667 if (wakeEvents > 0) {
668 if (!mWakeLockAcquired) {
669 setWakeLockAcquiredLocked(true);
670 }
671 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800672 }
Aravind Akella8493b792014-09-08 15:45:47 -0700673 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800674
Mathias Agopianf001c922010-11-11 17:58:51 -0800675 // handle virtual sensors
676 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700677 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700678 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800679 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700680 SensorFusion& fusion(SensorFusion::getInstance());
681 if (fusion.isEnabled()) {
682 for (size_t i=0 ; i<size_t(count) ; i++) {
683 fusion.process(event[i]);
684 }
685 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700686 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700687 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700688 if (count + k >= minBufferSize) {
689 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700690 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700691 count, k, minBufferSize);
692 break;
693 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800694 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700695 sp<SensorInterface> si = mSensors.getInterface(handle);
696 if (si == nullptr) {
697 ALOGE("handle %d is not an valid virtual sensor", handle);
698 continue;
699 }
700
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700701 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700702 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800703 k++;
704 }
705 }
706 }
707 if (k) {
708 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700709 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800710 count += k;
711 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700712 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700713 }
714 }
715 }
716
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700717 // handle backward compatibility for RotationVector sensor
718 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
719 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700720 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700721 // All the 4 components of the quaternion should be available
722 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700723 mSensorEventBuffer[i].data[4] = -1;
724 }
725 }
726 }
727
Aravind Akella8493b792014-09-08 15:45:47 -0700728 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700729 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
730 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
731 // SensorEventConnection mapped to the corresponding flush_complete_event in
732 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700733 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700734 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
735 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
736 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700737 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700738 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
739 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700740 }
741 }
Peng Xu2576cb62016-01-20 00:22:09 -0800742
743 // handle dynamic sensor meta events, process registration and unregistration of dynamic
744 // sensor based on content of event.
745 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
746 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
747 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
748 const sensor_t& dynamicSensor =
749 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
750 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
751 handle, dynamicSensor.type, dynamicSensor.name);
752
Peng Xu0cc8f802016-04-05 23:46:03 -0700753 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800754 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700755 sensor_t s = dynamicSensor;
756 // make sure the dynamic sensor flag is set
757 s.flags |= DYNAMIC_SENSOR_MASK;
758 // force the handle to be consistent
759 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800760
761 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800762
Peng Xu0cc8f802016-04-05 23:46:03 -0700763 // This will release hold on dynamic sensor meta, so it should be called
764 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700765 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800766 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700767 } else {
768 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
769 }
Peng Xu2576cb62016-01-20 00:22:09 -0800770 } else {
771 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
772 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
773
774 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800775 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800776 ALOGE("Dynamic sensor release error.");
777 }
778
779 size_t numConnections = activeConnections.size();
780 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700781 if (activeConnections[i] != nullptr) {
Peng Xu2576cb62016-01-20 00:22:09 -0800782 activeConnections[i]->removeSensor(handle);
783 }
784 }
785 }
786 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700787 }
788
Aravind Akella9a844cf2014-02-11 18:58:52 -0800789 // Send our events to clients. Check the state of wake lock for each client and release the
790 // lock if none of the clients need it.
791 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700792 size_t numConnections = activeConnections.size();
793 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700794 if (activeConnections[i] != nullptr) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700795 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700796 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700797 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700798 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
799 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700800 if (activeConnections[i]->hasOneShotSensors()) {
801 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
802 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700803 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800804 }
805 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700806
Aravind Akella9a844cf2014-02-11 18:58:52 -0800807 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700808 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800809 }
Aravind Akella8493b792014-09-08 15:45:47 -0700810 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700811
Steve Block3c20fbe2012-01-05 23:22:43 +0000812 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800813 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700814 return false;
815}
816
Aravind Akella56ae4262014-07-10 16:01:10 -0700817sp<Looper> SensorService::getLooper() const {
818 return mLooper;
819}
820
Aravind Akellab4373ac2014-10-29 17:55:20 -0700821void SensorService::resetAllWakeLockRefCounts() {
822 SortedVector< sp<SensorEventConnection> > activeConnections;
823 populateActiveConnections(&activeConnections);
824 {
825 Mutex::Autolock _l(mLock);
826 for (size_t i=0 ; i < activeConnections.size(); ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700827 if (activeConnections[i] != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700828 activeConnections[i]->resetWakeLockRefCount();
829 }
830 }
831 setWakeLockAcquiredLocked(false);
832 }
833}
834
835void SensorService::setWakeLockAcquiredLocked(bool acquire) {
836 if (acquire) {
837 if (!mWakeLockAcquired) {
838 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
839 mWakeLockAcquired = true;
840 }
841 mLooper->wake();
842 } else {
843 if (mWakeLockAcquired) {
844 release_wake_lock(WAKE_LOCK_NAME);
845 mWakeLockAcquired = false;
846 }
847 }
848}
849
Aravind Akellab4373ac2014-10-29 17:55:20 -0700850bool SensorService::isWakeLockAcquired() {
851 Mutex::Autolock _l(mLock);
852 return mWakeLockAcquired;
853}
854
Aravind Akella56ae4262014-07-10 16:01:10 -0700855bool SensorService::SensorEventAckReceiver::threadLoop() {
856 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700857 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700858 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700859 bool wakeLockAcquired = mService->isWakeLockAcquired();
860 int timeout = -1;
861 if (wakeLockAcquired) timeout = 5000;
862 int ret = looper->pollOnce(timeout);
863 if (ret == ALOOPER_POLL_TIMEOUT) {
864 mService->resetAllWakeLockRefCounts();
865 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700866 } while(!Thread::exitPending());
867 return false;
868}
869
Aravind Akella9a844cf2014-02-11 18:58:52 -0800870void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800871 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800872 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800873 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
874 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800875 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800876 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800877 }
Peng Xu2576cb62016-01-20 00:22:09 -0800878
Peng Xu6a2d3a02015-12-21 12:00:23 -0800879 auto logger = mRecentEvent.find(buffer[i].sensor);
880 if (logger != mRecentEvent.end()) {
881 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800882 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800883 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800884}
885
Peng Xu47e96012016-03-28 17:55:56 -0700886void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800887 struct compar {
888 static int cmp(void const* lhs, void const* rhs) {
889 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
890 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700891 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800892 }
893 };
894 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
895}
896
Mathias Agopian5d270722010-07-19 15:20:39 -0700897String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700898 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700899}
900
Aravind Akellab4099e72013-10-15 15:43:10 -0700901bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700902 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
903 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700904}
905
Aravind Akella9a844cf2014-02-11 18:58:52 -0800906bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700907 int handle = event.sensor;
908 if (event.type == SENSOR_TYPE_META_DATA) {
909 handle = event.meta_data.sensor;
910 }
Peng Xu755c4512016-04-07 23:15:14 -0700911 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
912 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800913}
914
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700915int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
916 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
917 // UUID is not supported for this device.
918 return 0;
919 }
920 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
921 // This sensor can be uniquely identified in the system by
922 // the combination of its type and name.
923 return -1;
924 }
925
926 // We have a dynamic sensor.
927
928 if (!sHmacGlobalKeyIsValid) {
929 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
930 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
931 return 0;
932 }
933
934 // We want each app author/publisher to get a different ID, so that the
935 // same dynamic sensor cannot be tracked across apps by multiple
936 // authors/publishers. So we use both our UUID and our User ID.
937 // Note potential confusion:
938 // UUID => Universally Unique Identifier.
939 // UID => User Identifier.
940 // We refrain from using "uid" except as needed by API to try to
941 // keep this distinction clear.
942
943 auto appUserId = IPCThreadState::self()->getCallingUid();
944 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
945 memcpy(uuidAndApp, &uuid, sizeof(uuid));
946 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
947
948 // Now we use our key on our UUID/app combo to get the hash.
949 uint8_t hash[EVP_MAX_MD_SIZE];
950 unsigned int hashLen;
951 if (HMAC(EVP_sha256(),
952 sHmacGlobalKey, sizeof(sHmacGlobalKey),
953 uuidAndApp, sizeof(uuidAndApp),
954 hash, &hashLen) == nullptr) {
955 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
956 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
957 return 0;
958 }
959
960 int32_t id = 0;
961 if (hashLen < sizeof(id)) {
962 // We never expect this case, but out of paranoia, we handle it.
963 // Our 'id' length is already quite small, we don't want the
964 // effective length of it to be even smaller.
965 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
966 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
967 return 0;
968 }
969
970 // This is almost certainly less than all of 'hash', but it's as secure
971 // as we can be with our current 'id' length.
972 memcpy(&id, hash, sizeof(id));
973
974 // Note at the beginning of the function that we return the values of
975 // 0 and -1 to represent special cases. As a result, we can't return
976 // those as dynamic sensor IDs. If we happened to hash to one of those
977 // values, we change 'id' so we report as a dynamic sensor, and not as
978 // one of those special cases.
979 if (id == -1) {
980 id = -2;
981 } else if (id == 0) {
982 id = 1;
983 }
984 return id;
985}
986
987void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
988 for (auto &sensor : sensorList) {
989 int32_t id = getIdFromUuid(sensor.getUuid());
990 sensor.setId(id);
991 }
992}
993
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800994Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -0700995 char value[PROPERTY_VALUE_MAX];
996 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000997 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700998 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000999 Vector<Sensor> accessibleSensorList;
1000 for (size_t i = 0; i < initialSensorList.size(); i++) {
1001 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001002 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001003 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001004 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001005 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001006}
1007
Peng Xu47e96012016-03-28 17:55:56 -07001008Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001009 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001010 mSensors.forEachSensor(
1011 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001012 if (sensor.isDynamicSensor()) {
1013 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1014 accessibleSensorList.add(sensor);
1015 } else {
1016 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1017 sensor.getName().string(),
1018 sensor.getRequiredPermission().string(),
1019 sensor.getRequiredAppOp());
1020 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001021 }
1022 return true;
1023 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001024 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001025 return accessibleSensorList;
1026}
1027
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001028sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001029 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001030 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1031 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001032 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001033 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001034
1035 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001036 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1037 // operating in DI mode.
1038 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001039 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1040 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001041 }
1042
Mathias Agopian5307d172012-09-18 17:02:43 -07001043 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001044 pid_t pid = IPCThreadState::self()->getCallingPid();
1045
1046 String8 connPackageName =
1047 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1048 String16 connOpPackageName =
1049 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001050 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001051 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001052 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001053 if (requestedMode == DATA_INJECTION) {
1054 if (mActiveConnections.indexOf(result) < 0) {
1055 mActiveConnections.add(result);
1056 }
1057 // Add the associated file descriptor to the Looper for polling whenever there is data to
1058 // be injected.
1059 result->updateLooperRegistration(mLooper);
1060 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001061 return result;
1062}
1063
Aravind Akella841a5922015-06-29 12:37:48 -07001064int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001065 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001066 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001067}
1068
Peng Xue36e3472016-11-03 11:57:10 -07001069sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1070 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1071 const native_handle *resource) {
1072 Mutex::Autolock _l(mLock);
1073
1074 struct sensors_direct_mem_t mem = {
1075 .type = type,
1076 .format = format,
1077 .size = size,
1078 .handle = resource,
1079 };
1080 uid_t uid = IPCThreadState::self()->getCallingUid();
1081
1082 if (mem.handle == nullptr) {
1083 ALOGE("Failed to clone resource handle");
1084 return nullptr;
1085 }
1086
1087 // check format
1088 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1089 ALOGE("Direct channel format %d is unsupported!", format);
1090 return nullptr;
1091 }
1092
1093 // check for duplication
1094 for (auto &i : mDirectConnections) {
1095 sp<SensorDirectConnection> connection(i.promote());
1096 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001097 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001098 return nullptr;
1099 }
1100 }
1101
1102 // check specific to memory type
1103 switch(type) {
1104 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001105 if (resource->numFds < 1) {
1106 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1107 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1108 return nullptr;
1109 }
Peng Xue36e3472016-11-03 11:57:10 -07001110 int fd = resource->data[0];
1111 int size2 = ashmem_get_size_region(fd);
1112 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001113 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001114 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1115 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001116 return nullptr;
1117 }
1118 break;
1119 }
1120 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001121 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001122 break;
1123 default:
1124 ALOGE("Unknown direct connection memory type %d", type);
1125 return nullptr;
1126 }
1127
1128 native_handle_t *clone = native_handle_clone(resource);
1129 if (!clone) {
1130 return nullptr;
1131 }
1132
1133 SensorDirectConnection* conn = nullptr;
1134 SensorDevice& dev(SensorDevice::getInstance());
1135 int channelHandle = dev.registerDirectChannel(&mem);
1136
1137 if (channelHandle <= 0) {
1138 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1139 } else {
1140 mem.handle = clone;
1141 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1142 }
1143
1144 if (conn == nullptr) {
1145 native_handle_close(clone);
1146 native_handle_delete(clone);
1147 } else {
1148 // add to list of direct connections
1149 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1150 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1151 }
1152 return conn;
1153}
1154
Peng Xudd5c5cb2017-03-16 17:39:43 -07001155int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001156 int32_t handle, int32_t type,
1157 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001158 Mutex::Autolock _l(mLock);
1159
Alexey Polyudov88711e82017-05-23 19:54:04 -07001160 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001161 return PERMISSION_DENIED;
1162 }
1163
1164 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001165 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001166 size_t expectSize = INT32_MAX;
1167 switch (type) {
1168 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1169 isFloat = true;
1170 expectSize = 3;
1171 break;
1172 case AINFO_LOCAL_GRAVITY:
1173 isFloat = true;
1174 expectSize = 1;
1175 break;
1176 case AINFO_DOCK_STATE:
1177 case AINFO_HIGH_PERFORMANCE_MODE:
1178 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1179 isFloat = false;
1180 expectSize = 1;
1181 break;
1182 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001183 // CUSTOM events must only contain float data; it may have variable size
1184 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1185 ints.size() ||
1186 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1187 handle < 0) {
1188 return BAD_VALUE;
1189 }
1190 isFloat = true;
1191 isCustom = true;
1192 expectSize = floats.size();
1193 break;
1194 }
1195
1196 if (!isCustom && handle != -1) {
1197 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001198 }
1199
1200 // three events: first one is begin tag, last one is end tag, the one in the middle
1201 // is the payload.
1202 sensors_event_t event[3];
1203 int64_t timestamp = elapsedRealtimeNano();
1204 for (sensors_event_t* i = event; i < event + 3; i++) {
1205 *i = (sensors_event_t) {
1206 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001207 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001208 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1209 .timestamp = timestamp++,
1210 .additional_info = (additional_info_event_t) {
1211 .serial = 0
1212 }
1213 };
1214 }
1215
1216 event[0].additional_info.type = AINFO_BEGIN;
1217 event[1].additional_info.type = type;
1218 event[2].additional_info.type = AINFO_END;
1219
1220 if (isFloat) {
1221 if (floats.size() != expectSize) {
1222 return BAD_VALUE;
1223 }
1224 for (size_t i = 0; i < expectSize; ++i) {
1225 event[1].additional_info.data_float[i] = floats[i];
1226 }
1227 } else {
1228 if (ints.size() != expectSize) {
1229 return BAD_VALUE;
1230 }
1231 for (size_t i = 0; i < expectSize; ++i) {
1232 event[1].additional_info.data_int32[i] = ints[i];
1233 }
1234 }
1235
1236 SensorDevice& dev(SensorDevice::getInstance());
1237 for (sensors_event_t* i = event; i < event + 3; i++) {
1238 int ret = dev.injectSensorData(i);
1239 if (ret != NO_ERROR) {
1240 return ret;
1241 }
1242 }
1243 return NO_ERROR;
1244}
1245
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001246status_t SensorService::resetToNormalMode() {
1247 Mutex::Autolock _l(mLock);
1248 return resetToNormalModeLocked();
1249}
1250
1251status_t SensorService::resetToNormalModeLocked() {
1252 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001253 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301254 if (err == NO_ERROR) {
1255 mCurrentOperatingMode = NORMAL;
1256 dev.enableAllSensors();
1257 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001258 return err;
1259}
1260
Peng Xu47e96012016-03-28 17:55:56 -07001261void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001262 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001263 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001264 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001265 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001266 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001267 int handle = mActiveSensors.keyAt(i);
1268 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001269 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001270 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1271 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001272 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001273 } else {
1274 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001275 }
Aravind Akella8a969552014-09-28 17:52:41 -07001276 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001277 }
1278 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001279 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001280 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001281 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001282 c, i, handle);
1283
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001284 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001285 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001286 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001287 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001288 delete rec;
1289 size--;
1290 } else {
1291 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001292 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001293 }
Aravind Akella8a969552014-09-28 17:52:41 -07001294 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001295 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001296 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001297 if (c->needsWakeLock()) {
1298 checkWakeLockStateLocked();
1299 }
Peng Xu4f707f82016-09-26 11:28:32 -07001300
1301 SensorDevice& dev(SensorDevice::getInstance());
1302 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001303}
1304
Peng Xue36e3472016-11-03 11:57:10 -07001305void SensorService::cleanupConnection(SensorDirectConnection* c) {
1306 Mutex::Autolock _l(mLock);
1307
1308 SensorDevice& dev(SensorDevice::getInstance());
1309 dev.unregisterDirectChannel(c->getHalChannelHandle());
1310 mDirectConnections.remove(c);
1311}
1312
Peng Xu755c4512016-04-07 23:15:14 -07001313sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001314 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001315}
1316
Mathias Agopianfc328812010-07-14 23:41:37 -07001317status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001318 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001319 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001320 if (mInitCheck != NO_ERROR)
1321 return mInitCheck;
1322
Peng Xu755c4512016-04-07 23:15:14 -07001323 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1324 if (sensor == nullptr ||
1325 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001326 return BAD_VALUE;
1327 }
1328
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001329 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001330 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001331 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001332 return INVALID_OPERATION;
1333 }
1334
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001335 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001336 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001337 rec = new SensorRecord(connection);
1338 mActiveSensors.add(handle, rec);
1339 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001340 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001341 }
1342 } else {
1343 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001344 // this sensor is already activated, but we are adding a connection that uses it.
1345 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001346 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001347 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001348 // NOTE: The wake_up flag of this event may get set to
1349 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001350
1351 auto logger = mRecentEvent.find(handle);
1352 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001353 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -07001354 // It is unlikely that this buffer is empty as the sensor is already active.
1355 // One possible corner case may be two applications activating an on-change
1356 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001357 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001358 event.sensor = handle;
1359 if (event.version == sizeof(sensors_event_t)) {
1360 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1361 setWakeLockAcquiredLocked(true);
1362 }
Yi Kong8f313e32018-07-17 14:13:29 -07001363 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001364 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1365 checkWakeLockStateLocked();
1366 }
1367 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001368 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001369 }
1370 }
1371 }
1372 }
1373
1374 if (connection->addSensor(handle)) {
1375 BatteryService::enableSensor(connection->getUid(), handle);
1376 // the sensor was added (which means it wasn't already there)
1377 // so, see if this connection becomes active
1378 if (mActiveConnections.indexOf(connection) < 0) {
1379 mActiveConnections.add(connection);
1380 }
1381 } else {
1382 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1383 handle, connection.get());
1384 }
1385
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301386 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001387 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301388 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1389 samplingPeriodNs = maxDelayNs;
1390 }
1391
Aravind Akella724d91d2013-06-27 12:04:23 -07001392 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1393 if (samplingPeriodNs < minDelayNs) {
1394 samplingPeriodNs = minDelayNs;
1395 }
1396
Aravind Akella6c2664a2014-08-13 12:24:50 -07001397 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1398 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001399 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1400
Aravind Akella4949c502015-02-11 15:54:35 -08001401 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001402 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001403
Peng Xu20483c42015-10-26 15:14:43 -07001404 // Call flush() before calling activate() on the sensor. Wait for a first
1405 // flush complete event before sending events on this connection. Ignore
1406 // one-shot sensors which don't support flush(). Ignore on-change sensors
1407 // to maintain the on-change logic (any on-change events except the initial
1408 // one should be trigger by a change in value). Also if this sensor isn't
1409 // already active, don't call flush().
1410 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001411 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001412 rec->getNumConnections() > 1) {
1413 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001414 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001415 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001416 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001417 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001418 } else {
1419 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001420 }
1421 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001422
1423 if (err == NO_ERROR) {
1424 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1425 err = sensor->activate(connection.get(), true);
1426 }
1427
Aravind Akella8a969552014-09-28 17:52:41 -07001428 if (err == NO_ERROR) {
1429 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001430
1431 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1432 SensorRegistrationInfo(handle, connection->getPackageName(),
1433 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001434 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001435 }
1436
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001437 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001438 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001439 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001440 }
1441 return err;
1442}
1443
Peng Xu47e96012016-03-28 17:55:56 -07001444status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001445 if (mInitCheck != NO_ERROR)
1446 return mInitCheck;
1447
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001448 Mutex::Autolock _l(mLock);
1449 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001450 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001451 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1452 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001453
1454 }
1455 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001456 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1457 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001458 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001459 }
1460 return err;
1461}
1462
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001463status_t SensorService::cleanupWithoutDisable(
1464 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001465 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001466 return cleanupWithoutDisableLocked(connection, handle);
1467}
1468
1469status_t SensorService::cleanupWithoutDisableLocked(
1470 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001471 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001472 if (rec) {
1473 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001474 if (connection->removeSensor(handle)) {
1475 BatteryService::disableSensor(connection->getUid(), handle);
1476 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001477 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001478 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001479 mActiveConnections.remove(connection);
1480 }
1481 // see if this sensor becomes inactive
1482 if (rec->removeConnection(connection)) {
1483 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001484 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001485 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001486 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001487 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001488 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001489 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001490}
1491
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001492status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001493 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001494 if (mInitCheck != NO_ERROR)
1495 return mInitCheck;
1496
Peng Xu755c4512016-04-07 23:15:14 -07001497 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1498 if (sensor == nullptr ||
1499 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001500 return BAD_VALUE;
1501 }
1502
Mathias Agopian1cd70002010-07-21 15:59:50 -07001503 if (ns < 0)
1504 return BAD_VALUE;
1505
Mathias Agopian62569ec2011-11-07 21:21:47 -08001506 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1507 if (ns < minDelayNs) {
1508 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001509 }
1510
Mathias Agopianf001c922010-11-11 17:58:51 -08001511 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001512}
1513
Svetoslavb412f6e2015-04-29 16:50:41 -07001514status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1515 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001516 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001517 SensorDevice& dev(SensorDevice::getInstance());
1518 const int halVersion = dev.getHalDeviceVersion();
1519 status_t err(NO_ERROR);
1520 Mutex::Autolock _l(mLock);
1521 // Loop through all sensors for this connection and call flush on each of them.
1522 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1523 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001524 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1525 if (sensor == nullptr) {
1526 continue;
1527 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001528 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1529 ALOGE("flush called on a one-shot sensor");
1530 err = INVALID_OPERATION;
1531 continue;
1532 }
Aravind Akella8493b792014-09-08 15:45:47 -07001533 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001534 // For older devices just increment pending flush count which will send a trivial
1535 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001536 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001537 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001538 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1539 err = INVALID_OPERATION;
1540 continue;
1541 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001542 status_t err_flush = sensor->flush(connection.get(), handle);
1543 if (err_flush == NO_ERROR) {
1544 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001545 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001546 }
1547 err = (err_flush != NO_ERROR) ? err_flush : err;
1548 }
Aravind Akella70018042014-04-07 22:52:37 +00001549 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001550 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001551}
Aravind Akella70018042014-04-07 22:52:37 +00001552
Svetoslavb412f6e2015-04-29 16:50:41 -07001553bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1554 const String16& opPackageName) {
1555 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001556
Svetoslavb412f6e2015-04-29 16:50:41 -07001557 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001558 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001559 }
1560
1561 bool hasPermission = false;
1562
1563 // Runtime permissions can't use the cache as they may change.
1564 if (sensor.isRequiredPermissionRuntime()) {
1565 hasPermission = checkPermission(String16(requiredPermission),
1566 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001567 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001568 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1569 }
1570
1571 if (!hasPermission) {
1572 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1573 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001574 return false;
1575 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001576
1577 const int32_t opCode = sensor.getRequiredAppOp();
1578 if (opCode >= 0) {
1579 AppOpsManager appOps;
1580 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1581 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001582 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001583 operation, sensor.getName().string(), opCode);
1584 return false;
1585 }
1586 }
1587
1588 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001589}
1590
Aravind Akella9a844cf2014-02-11 18:58:52 -08001591void SensorService::checkWakeLockState() {
1592 Mutex::Autolock _l(mLock);
1593 checkWakeLockStateLocked();
1594}
1595
1596void SensorService::checkWakeLockStateLocked() {
1597 if (!mWakeLockAcquired) {
1598 return;
1599 }
1600 bool releaseLock = true;
1601 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1602 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001603 if (connection != nullptr) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001604 if (connection->needsWakeLock()) {
1605 releaseLock = false;
1606 break;
1607 }
1608 }
1609 }
1610 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001611 setWakeLockAcquiredLocked(false);
1612 }
1613}
1614
1615void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1616 Mutex::Autolock _l(mLock);
1617 connection->writeToSocketFromCache();
1618 if (connection->needsWakeLock()) {
1619 setWakeLockAcquiredLocked(true);
1620 }
1621}
1622
1623void SensorService::populateActiveConnections(
1624 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1625 Mutex::Autolock _l(mLock);
1626 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1627 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001628 if (connection != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001629 activeConnections->add(connection);
1630 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001631 }
1632}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001633
Aravind Akella4949c502015-02-11 15:54:35 -08001634bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001635 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001636}
1637
Peng Xue36e3472016-11-03 11:57:10 -07001638bool SensorService::isOperationRestricted(const String16& opPackageName) {
1639 Mutex::Autolock _l(mLock);
1640 if (mCurrentOperatingMode != RESTRICTED) {
1641 String8 package(opPackageName);
1642 return !isWhiteListedPackage(package);
1643 }
1644 return false;
1645}
1646
Svet Ganove752a5c2018-01-15 17:14:20 -08001647void SensorService::UidPolicy::registerSelf() {
1648 ActivityManager am;
1649 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1650 | ActivityManager::UID_OBSERVER_IDLE
1651 | ActivityManager::UID_OBSERVER_ACTIVE,
1652 ActivityManager::PROCESS_STATE_UNKNOWN,
1653 String16("android"));
1654}
1655
1656void SensorService::UidPolicy::unregisterSelf() {
1657 ActivityManager am;
1658 am.unregisterUidObserver(this);
1659}
1660
1661void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1662 onUidIdle(uid, disabled);
1663}
1664
1665void SensorService::UidPolicy::onUidActive(uid_t uid) {
1666 {
1667 Mutex::Autolock _l(mUidLock);
1668 mActiveUids.insert(uid);
1669 }
1670 sp<SensorService> service = mService.promote();
1671 if (service != nullptr) {
1672 service->setSensorAccess(uid, true);
1673 }
1674}
1675
1676void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1677 bool deleted = false;
1678 {
1679 Mutex::Autolock _l(mUidLock);
1680 if (mActiveUids.erase(uid) > 0) {
1681 deleted = true;
1682 }
1683 }
1684 if (deleted) {
1685 sp<SensorService> service = mService.promote();
1686 if (service != nullptr) {
1687 service->setSensorAccess(uid, false);
1688 }
1689 }
1690}
1691
1692void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1693 updateOverrideUid(uid, active, true);
1694}
1695
1696void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1697 updateOverrideUid(uid, false, false);
1698}
1699
1700void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1701 bool wasActive = false;
1702 bool isActive = false;
1703 {
1704 Mutex::Autolock _l(mUidLock);
1705 wasActive = isUidActiveLocked(uid);
1706 mOverrideUids.erase(uid);
1707 if (insert) {
1708 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1709 }
1710 isActive = isUidActiveLocked(uid);
1711 }
1712 if (wasActive != isActive) {
1713 sp<SensorService> service = mService.promote();
1714 if (service != nullptr) {
1715 service->setSensorAccess(uid, isActive);
1716 }
1717 }
1718}
1719
1720bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1721 // Non-app UIDs are considered always active
1722 if (uid < FIRST_APPLICATION_UID) {
1723 return true;
1724 }
1725 Mutex::Autolock _l(mUidLock);
1726 return isUidActiveLocked(uid);
1727}
1728
1729bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1730 // Non-app UIDs are considered always active
1731 if (uid < FIRST_APPLICATION_UID) {
1732 return true;
1733 }
1734 auto it = mOverrideUids.find(uid);
1735 if (it != mOverrideUids.end()) {
1736 return it->second;
1737 }
1738 return mActiveUids.find(uid) != mActiveUids.end();
1739}
1740
Mathias Agopianfc328812010-07-14 23:41:37 -07001741}; // namespace android