blob: 1b9b945e531ae9b4ce73033797245f5a970a827b [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) {
Brian Stack156da082018-10-01 15:58:53 -0700636 if(count == DEAD_OBJECT && device.isReconnecting()) {
637 device.reconnect();
638 continue;
639 } else {
640 ALOGE("sensor poll failed (%s)", strerror(-count));
641 break;
642 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700643 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700644
645 // Reset sensors_event_t.flags to zero for all events in the buffer.
646 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700647 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700648 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700649
Peng Xueb4d6282015-12-10 18:02:41 -0800650 // Make a copy of the connection vector as some connections may be removed during the course
651 // of this loop (especially when one-shot sensor events are present in the sensor_event
652 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
653 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
654 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
655 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700656 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700657 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800658
Aravind Akella9a844cf2014-02-11 18:58:52 -0800659 Mutex::Autolock _l(mLock);
660 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
661 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
662 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
663 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
664 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700665 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700666 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700667 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700668 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700669 }
670 }
671
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700672 if (wakeEvents > 0) {
673 if (!mWakeLockAcquired) {
674 setWakeLockAcquiredLocked(true);
675 }
676 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800677 }
Aravind Akella8493b792014-09-08 15:45:47 -0700678 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800679
Mathias Agopianf001c922010-11-11 17:58:51 -0800680 // handle virtual sensors
681 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700682 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700683 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800684 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700685 SensorFusion& fusion(SensorFusion::getInstance());
686 if (fusion.isEnabled()) {
687 for (size_t i=0 ; i<size_t(count) ; i++) {
688 fusion.process(event[i]);
689 }
690 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700691 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700692 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700693 if (count + k >= minBufferSize) {
694 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700695 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700696 count, k, minBufferSize);
697 break;
698 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800699 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700700 sp<SensorInterface> si = mSensors.getInterface(handle);
701 if (si == nullptr) {
702 ALOGE("handle %d is not an valid virtual sensor", handle);
703 continue;
704 }
705
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700706 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700707 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800708 k++;
709 }
710 }
711 }
712 if (k) {
713 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700714 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800715 count += k;
716 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700717 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700718 }
719 }
720 }
721
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700722 // handle backward compatibility for RotationVector sensor
723 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
724 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700725 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700726 // All the 4 components of the quaternion should be available
727 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700728 mSensorEventBuffer[i].data[4] = -1;
729 }
730 }
731 }
732
Aravind Akella8493b792014-09-08 15:45:47 -0700733 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700734 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
735 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
736 // SensorEventConnection mapped to the corresponding flush_complete_event in
737 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700738 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700739 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
740 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
741 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700742 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700743 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
744 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700745 }
746 }
Peng Xu2576cb62016-01-20 00:22:09 -0800747
748 // handle dynamic sensor meta events, process registration and unregistration of dynamic
749 // sensor based on content of event.
750 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
751 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
752 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
753 const sensor_t& dynamicSensor =
754 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
755 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
756 handle, dynamicSensor.type, dynamicSensor.name);
757
Peng Xu0cc8f802016-04-05 23:46:03 -0700758 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800759 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700760 sensor_t s = dynamicSensor;
761 // make sure the dynamic sensor flag is set
762 s.flags |= DYNAMIC_SENSOR_MASK;
763 // force the handle to be consistent
764 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800765
766 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800767
Peng Xu0cc8f802016-04-05 23:46:03 -0700768 // This will release hold on dynamic sensor meta, so it should be called
769 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700770 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800771 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700772 } else {
773 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
774 }
Peng Xu2576cb62016-01-20 00:22:09 -0800775 } else {
776 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
777 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
778
779 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800780 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800781 ALOGE("Dynamic sensor release error.");
782 }
783
784 size_t numConnections = activeConnections.size();
785 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700786 if (activeConnections[i] != nullptr) {
Peng Xu2576cb62016-01-20 00:22:09 -0800787 activeConnections[i]->removeSensor(handle);
788 }
789 }
790 }
791 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700792 }
793
Aravind Akella9a844cf2014-02-11 18:58:52 -0800794 // Send our events to clients. Check the state of wake lock for each client and release the
795 // lock if none of the clients need it.
796 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700797 size_t numConnections = activeConnections.size();
798 for (size_t i=0 ; i < numConnections; ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700799 if (activeConnections[i] != nullptr) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700800 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700801 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700802 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700803 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
804 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700805 if (activeConnections[i]->hasOneShotSensors()) {
806 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
807 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700808 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800809 }
810 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700811
Aravind Akella9a844cf2014-02-11 18:58:52 -0800812 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700813 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800814 }
Aravind Akella8493b792014-09-08 15:45:47 -0700815 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700816
Steve Block3c20fbe2012-01-05 23:22:43 +0000817 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800818 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700819 return false;
820}
821
Aravind Akella56ae4262014-07-10 16:01:10 -0700822sp<Looper> SensorService::getLooper() const {
823 return mLooper;
824}
825
Aravind Akellab4373ac2014-10-29 17:55:20 -0700826void SensorService::resetAllWakeLockRefCounts() {
827 SortedVector< sp<SensorEventConnection> > activeConnections;
828 populateActiveConnections(&activeConnections);
829 {
830 Mutex::Autolock _l(mLock);
831 for (size_t i=0 ; i < activeConnections.size(); ++i) {
Yi Kong8f313e32018-07-17 14:13:29 -0700832 if (activeConnections[i] != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700833 activeConnections[i]->resetWakeLockRefCount();
834 }
835 }
836 setWakeLockAcquiredLocked(false);
837 }
838}
839
840void SensorService::setWakeLockAcquiredLocked(bool acquire) {
841 if (acquire) {
842 if (!mWakeLockAcquired) {
843 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
844 mWakeLockAcquired = true;
845 }
846 mLooper->wake();
847 } else {
848 if (mWakeLockAcquired) {
849 release_wake_lock(WAKE_LOCK_NAME);
850 mWakeLockAcquired = false;
851 }
852 }
853}
854
Aravind Akellab4373ac2014-10-29 17:55:20 -0700855bool SensorService::isWakeLockAcquired() {
856 Mutex::Autolock _l(mLock);
857 return mWakeLockAcquired;
858}
859
Aravind Akella56ae4262014-07-10 16:01:10 -0700860bool SensorService::SensorEventAckReceiver::threadLoop() {
861 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700862 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700863 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700864 bool wakeLockAcquired = mService->isWakeLockAcquired();
865 int timeout = -1;
866 if (wakeLockAcquired) timeout = 5000;
867 int ret = looper->pollOnce(timeout);
868 if (ret == ALOOPER_POLL_TIMEOUT) {
869 mService->resetAllWakeLockRefCounts();
870 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700871 } while(!Thread::exitPending());
872 return false;
873}
874
Aravind Akella9a844cf2014-02-11 18:58:52 -0800875void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800876 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800877 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800878 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
879 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800880 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800881 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800882 }
Peng Xu2576cb62016-01-20 00:22:09 -0800883
Peng Xu6a2d3a02015-12-21 12:00:23 -0800884 auto logger = mRecentEvent.find(buffer[i].sensor);
885 if (logger != mRecentEvent.end()) {
886 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800887 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800888 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800889}
890
Peng Xu47e96012016-03-28 17:55:56 -0700891void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800892 struct compar {
893 static int cmp(void const* lhs, void const* rhs) {
894 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
895 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700896 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800897 }
898 };
899 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
900}
901
Mathias Agopian5d270722010-07-19 15:20:39 -0700902String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700903 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700904}
905
Aravind Akellab4099e72013-10-15 15:43:10 -0700906bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700907 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
908 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700909}
910
Aravind Akella9a844cf2014-02-11 18:58:52 -0800911bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700912 int handle = event.sensor;
913 if (event.type == SENSOR_TYPE_META_DATA) {
914 handle = event.meta_data.sensor;
915 }
Peng Xu755c4512016-04-07 23:15:14 -0700916 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
917 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800918}
919
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700920int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
921 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
922 // UUID is not supported for this device.
923 return 0;
924 }
925 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
926 // This sensor can be uniquely identified in the system by
927 // the combination of its type and name.
928 return -1;
929 }
930
931 // We have a dynamic sensor.
932
933 if (!sHmacGlobalKeyIsValid) {
934 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
935 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
936 return 0;
937 }
938
939 // We want each app author/publisher to get a different ID, so that the
940 // same dynamic sensor cannot be tracked across apps by multiple
941 // authors/publishers. So we use both our UUID and our User ID.
942 // Note potential confusion:
943 // UUID => Universally Unique Identifier.
944 // UID => User Identifier.
945 // We refrain from using "uid" except as needed by API to try to
946 // keep this distinction clear.
947
948 auto appUserId = IPCThreadState::self()->getCallingUid();
949 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
950 memcpy(uuidAndApp, &uuid, sizeof(uuid));
951 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
952
953 // Now we use our key on our UUID/app combo to get the hash.
954 uint8_t hash[EVP_MAX_MD_SIZE];
955 unsigned int hashLen;
956 if (HMAC(EVP_sha256(),
957 sHmacGlobalKey, sizeof(sHmacGlobalKey),
958 uuidAndApp, sizeof(uuidAndApp),
959 hash, &hashLen) == nullptr) {
960 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
961 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
962 return 0;
963 }
964
965 int32_t id = 0;
966 if (hashLen < sizeof(id)) {
967 // We never expect this case, but out of paranoia, we handle it.
968 // Our 'id' length is already quite small, we don't want the
969 // effective length of it to be even smaller.
970 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
971 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
972 return 0;
973 }
974
975 // This is almost certainly less than all of 'hash', but it's as secure
976 // as we can be with our current 'id' length.
977 memcpy(&id, hash, sizeof(id));
978
979 // Note at the beginning of the function that we return the values of
980 // 0 and -1 to represent special cases. As a result, we can't return
981 // those as dynamic sensor IDs. If we happened to hash to one of those
982 // values, we change 'id' so we report as a dynamic sensor, and not as
983 // one of those special cases.
984 if (id == -1) {
985 id = -2;
986 } else if (id == 0) {
987 id = 1;
988 }
989 return id;
990}
991
992void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
993 for (auto &sensor : sensorList) {
994 int32_t id = getIdFromUuid(sensor.getUuid());
995 sensor.setId(id);
996 }
997}
998
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800999Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001000 char value[PROPERTY_VALUE_MAX];
1001 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001002 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001003 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001004 Vector<Sensor> accessibleSensorList;
1005 for (size_t i = 0; i < initialSensorList.size(); i++) {
1006 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001007 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001008 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001009 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001010 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001011}
1012
Peng Xu47e96012016-03-28 17:55:56 -07001013Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001014 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001015 mSensors.forEachSensor(
1016 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001017 if (sensor.isDynamicSensor()) {
1018 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1019 accessibleSensorList.add(sensor);
1020 } else {
1021 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1022 sensor.getName().string(),
1023 sensor.getRequiredPermission().string(),
1024 sensor.getRequiredAppOp());
1025 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001026 }
1027 return true;
1028 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001029 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001030 return accessibleSensorList;
1031}
1032
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001033sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001034 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001035 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1036 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001037 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001038 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001039
1040 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001041 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1042 // operating in DI mode.
1043 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001044 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1045 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001046 }
1047
Mathias Agopian5307d172012-09-18 17:02:43 -07001048 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001049 pid_t pid = IPCThreadState::self()->getCallingPid();
1050
1051 String8 connPackageName =
1052 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1053 String16 connOpPackageName =
1054 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001055 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001056 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001057 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001058 if (requestedMode == DATA_INJECTION) {
1059 if (mActiveConnections.indexOf(result) < 0) {
1060 mActiveConnections.add(result);
1061 }
1062 // Add the associated file descriptor to the Looper for polling whenever there is data to
1063 // be injected.
1064 result->updateLooperRegistration(mLooper);
1065 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001066 return result;
1067}
1068
Aravind Akella841a5922015-06-29 12:37:48 -07001069int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001070 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001071 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001072}
1073
Peng Xue36e3472016-11-03 11:57:10 -07001074sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1075 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1076 const native_handle *resource) {
1077 Mutex::Autolock _l(mLock);
1078
1079 struct sensors_direct_mem_t mem = {
1080 .type = type,
1081 .format = format,
1082 .size = size,
1083 .handle = resource,
1084 };
1085 uid_t uid = IPCThreadState::self()->getCallingUid();
1086
1087 if (mem.handle == nullptr) {
1088 ALOGE("Failed to clone resource handle");
1089 return nullptr;
1090 }
1091
1092 // check format
1093 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1094 ALOGE("Direct channel format %d is unsupported!", format);
1095 return nullptr;
1096 }
1097
1098 // check for duplication
1099 for (auto &i : mDirectConnections) {
1100 sp<SensorDirectConnection> connection(i.promote());
1101 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001102 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001103 return nullptr;
1104 }
1105 }
1106
1107 // check specific to memory type
1108 switch(type) {
1109 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001110 if (resource->numFds < 1) {
1111 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1112 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1113 return nullptr;
1114 }
Peng Xue36e3472016-11-03 11:57:10 -07001115 int fd = resource->data[0];
1116 int size2 = ashmem_get_size_region(fd);
1117 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001118 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001119 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1120 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001121 return nullptr;
1122 }
1123 break;
1124 }
1125 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001126 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001127 break;
1128 default:
1129 ALOGE("Unknown direct connection memory type %d", type);
1130 return nullptr;
1131 }
1132
1133 native_handle_t *clone = native_handle_clone(resource);
1134 if (!clone) {
1135 return nullptr;
1136 }
1137
1138 SensorDirectConnection* conn = nullptr;
1139 SensorDevice& dev(SensorDevice::getInstance());
1140 int channelHandle = dev.registerDirectChannel(&mem);
1141
1142 if (channelHandle <= 0) {
1143 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1144 } else {
1145 mem.handle = clone;
1146 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1147 }
1148
1149 if (conn == nullptr) {
1150 native_handle_close(clone);
1151 native_handle_delete(clone);
1152 } else {
1153 // add to list of direct connections
1154 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1155 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1156 }
1157 return conn;
1158}
1159
Peng Xudd5c5cb2017-03-16 17:39:43 -07001160int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001161 int32_t handle, int32_t type,
1162 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001163 Mutex::Autolock _l(mLock);
1164
Alexey Polyudov88711e82017-05-23 19:54:04 -07001165 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001166 return PERMISSION_DENIED;
1167 }
1168
1169 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001170 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001171 size_t expectSize = INT32_MAX;
1172 switch (type) {
1173 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1174 isFloat = true;
1175 expectSize = 3;
1176 break;
1177 case AINFO_LOCAL_GRAVITY:
1178 isFloat = true;
1179 expectSize = 1;
1180 break;
1181 case AINFO_DOCK_STATE:
1182 case AINFO_HIGH_PERFORMANCE_MODE:
1183 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1184 isFloat = false;
1185 expectSize = 1;
1186 break;
1187 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001188 // CUSTOM events must only contain float data; it may have variable size
1189 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1190 ints.size() ||
1191 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1192 handle < 0) {
1193 return BAD_VALUE;
1194 }
1195 isFloat = true;
1196 isCustom = true;
1197 expectSize = floats.size();
1198 break;
1199 }
1200
1201 if (!isCustom && handle != -1) {
1202 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001203 }
1204
1205 // three events: first one is begin tag, last one is end tag, the one in the middle
1206 // is the payload.
1207 sensors_event_t event[3];
1208 int64_t timestamp = elapsedRealtimeNano();
1209 for (sensors_event_t* i = event; i < event + 3; i++) {
1210 *i = (sensors_event_t) {
1211 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001212 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001213 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1214 .timestamp = timestamp++,
1215 .additional_info = (additional_info_event_t) {
1216 .serial = 0
1217 }
1218 };
1219 }
1220
1221 event[0].additional_info.type = AINFO_BEGIN;
1222 event[1].additional_info.type = type;
1223 event[2].additional_info.type = AINFO_END;
1224
1225 if (isFloat) {
1226 if (floats.size() != expectSize) {
1227 return BAD_VALUE;
1228 }
1229 for (size_t i = 0; i < expectSize; ++i) {
1230 event[1].additional_info.data_float[i] = floats[i];
1231 }
1232 } else {
1233 if (ints.size() != expectSize) {
1234 return BAD_VALUE;
1235 }
1236 for (size_t i = 0; i < expectSize; ++i) {
1237 event[1].additional_info.data_int32[i] = ints[i];
1238 }
1239 }
1240
1241 SensorDevice& dev(SensorDevice::getInstance());
1242 for (sensors_event_t* i = event; i < event + 3; i++) {
1243 int ret = dev.injectSensorData(i);
1244 if (ret != NO_ERROR) {
1245 return ret;
1246 }
1247 }
1248 return NO_ERROR;
1249}
1250
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001251status_t SensorService::resetToNormalMode() {
1252 Mutex::Autolock _l(mLock);
1253 return resetToNormalModeLocked();
1254}
1255
1256status_t SensorService::resetToNormalModeLocked() {
1257 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001258 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301259 if (err == NO_ERROR) {
1260 mCurrentOperatingMode = NORMAL;
1261 dev.enableAllSensors();
1262 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001263 return err;
1264}
1265
Peng Xu47e96012016-03-28 17:55:56 -07001266void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001267 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001268 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001269 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001270 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001271 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001272 int handle = mActiveSensors.keyAt(i);
1273 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001274 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001275 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1276 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001277 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001278 } else {
1279 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001280 }
Aravind Akella8a969552014-09-28 17:52:41 -07001281 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001282 }
1283 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001284 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001285 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001286 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001287 c, i, handle);
1288
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001289 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001290 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001291 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001292 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001293 delete rec;
1294 size--;
1295 } else {
1296 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001297 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001298 }
Aravind Akella8a969552014-09-28 17:52:41 -07001299 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001300 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001301 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001302 if (c->needsWakeLock()) {
1303 checkWakeLockStateLocked();
1304 }
Peng Xu4f707f82016-09-26 11:28:32 -07001305
1306 SensorDevice& dev(SensorDevice::getInstance());
1307 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001308}
1309
Peng Xue36e3472016-11-03 11:57:10 -07001310void SensorService::cleanupConnection(SensorDirectConnection* c) {
1311 Mutex::Autolock _l(mLock);
1312
1313 SensorDevice& dev(SensorDevice::getInstance());
1314 dev.unregisterDirectChannel(c->getHalChannelHandle());
1315 mDirectConnections.remove(c);
1316}
1317
Peng Xu755c4512016-04-07 23:15:14 -07001318sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001319 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001320}
1321
Mathias Agopianfc328812010-07-14 23:41:37 -07001322status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001323 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001324 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001325 if (mInitCheck != NO_ERROR)
1326 return mInitCheck;
1327
Peng Xu755c4512016-04-07 23:15:14 -07001328 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1329 if (sensor == nullptr ||
1330 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001331 return BAD_VALUE;
1332 }
1333
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001334 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001335 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001336 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001337 return INVALID_OPERATION;
1338 }
1339
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001340 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001341 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001342 rec = new SensorRecord(connection);
1343 mActiveSensors.add(handle, rec);
1344 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001345 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001346 }
1347 } else {
1348 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001349 // this sensor is already activated, but we are adding a connection that uses it.
1350 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001351 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001352 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001353 // NOTE: The wake_up flag of this event may get set to
1354 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001355
1356 auto logger = mRecentEvent.find(handle);
1357 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001358 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -07001359 // It is unlikely that this buffer is empty as the sensor is already active.
1360 // One possible corner case may be two applications activating an on-change
1361 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001362 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001363 event.sensor = handle;
1364 if (event.version == sizeof(sensors_event_t)) {
1365 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1366 setWakeLockAcquiredLocked(true);
1367 }
Yi Kong8f313e32018-07-17 14:13:29 -07001368 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001369 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1370 checkWakeLockStateLocked();
1371 }
1372 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001373 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001374 }
1375 }
1376 }
1377 }
1378
1379 if (connection->addSensor(handle)) {
1380 BatteryService::enableSensor(connection->getUid(), handle);
1381 // the sensor was added (which means it wasn't already there)
1382 // so, see if this connection becomes active
1383 if (mActiveConnections.indexOf(connection) < 0) {
1384 mActiveConnections.add(connection);
1385 }
1386 } else {
1387 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1388 handle, connection.get());
1389 }
1390
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301391 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001392 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301393 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1394 samplingPeriodNs = maxDelayNs;
1395 }
1396
Aravind Akella724d91d2013-06-27 12:04:23 -07001397 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1398 if (samplingPeriodNs < minDelayNs) {
1399 samplingPeriodNs = minDelayNs;
1400 }
1401
Aravind Akella6c2664a2014-08-13 12:24:50 -07001402 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1403 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001404 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1405
Aravind Akella4949c502015-02-11 15:54:35 -08001406 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001407 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001408
Peng Xu20483c42015-10-26 15:14:43 -07001409 // Call flush() before calling activate() on the sensor. Wait for a first
1410 // flush complete event before sending events on this connection. Ignore
1411 // one-shot sensors which don't support flush(). Ignore on-change sensors
1412 // to maintain the on-change logic (any on-change events except the initial
1413 // one should be trigger by a change in value). Also if this sensor isn't
1414 // already active, don't call flush().
1415 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001416 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001417 rec->getNumConnections() > 1) {
1418 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001419 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001420 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001421 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001422 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001423 } else {
1424 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001425 }
1426 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001427
1428 if (err == NO_ERROR) {
1429 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1430 err = sensor->activate(connection.get(), true);
1431 }
1432
Aravind Akella8a969552014-09-28 17:52:41 -07001433 if (err == NO_ERROR) {
1434 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001435
1436 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1437 SensorRegistrationInfo(handle, connection->getPackageName(),
1438 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001439 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001440 }
1441
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001442 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001443 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001444 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001445 }
1446 return err;
1447}
1448
Peng Xu47e96012016-03-28 17:55:56 -07001449status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001450 if (mInitCheck != NO_ERROR)
1451 return mInitCheck;
1452
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001453 Mutex::Autolock _l(mLock);
1454 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001455 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001456 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1457 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001458
1459 }
1460 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001461 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1462 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001463 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001464 }
1465 return err;
1466}
1467
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001468status_t SensorService::cleanupWithoutDisable(
1469 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001470 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001471 return cleanupWithoutDisableLocked(connection, handle);
1472}
1473
1474status_t SensorService::cleanupWithoutDisableLocked(
1475 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001476 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001477 if (rec) {
1478 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001479 if (connection->removeSensor(handle)) {
1480 BatteryService::disableSensor(connection->getUid(), handle);
1481 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001482 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001483 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001484 mActiveConnections.remove(connection);
1485 }
1486 // see if this sensor becomes inactive
1487 if (rec->removeConnection(connection)) {
1488 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001489 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001490 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001491 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001492 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001493 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001494 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001495}
1496
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001497status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001498 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001499 if (mInitCheck != NO_ERROR)
1500 return mInitCheck;
1501
Peng Xu755c4512016-04-07 23:15:14 -07001502 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1503 if (sensor == nullptr ||
1504 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001505 return BAD_VALUE;
1506 }
1507
Mathias Agopian1cd70002010-07-21 15:59:50 -07001508 if (ns < 0)
1509 return BAD_VALUE;
1510
Mathias Agopian62569ec2011-11-07 21:21:47 -08001511 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1512 if (ns < minDelayNs) {
1513 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001514 }
1515
Mathias Agopianf001c922010-11-11 17:58:51 -08001516 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001517}
1518
Svetoslavb412f6e2015-04-29 16:50:41 -07001519status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1520 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001521 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001522 SensorDevice& dev(SensorDevice::getInstance());
1523 const int halVersion = dev.getHalDeviceVersion();
1524 status_t err(NO_ERROR);
1525 Mutex::Autolock _l(mLock);
1526 // Loop through all sensors for this connection and call flush on each of them.
1527 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1528 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001529 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1530 if (sensor == nullptr) {
1531 continue;
1532 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001533 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1534 ALOGE("flush called on a one-shot sensor");
1535 err = INVALID_OPERATION;
1536 continue;
1537 }
Aravind Akella8493b792014-09-08 15:45:47 -07001538 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001539 // For older devices just increment pending flush count which will send a trivial
1540 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001541 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001542 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001543 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1544 err = INVALID_OPERATION;
1545 continue;
1546 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001547 status_t err_flush = sensor->flush(connection.get(), handle);
1548 if (err_flush == NO_ERROR) {
1549 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001550 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001551 }
1552 err = (err_flush != NO_ERROR) ? err_flush : err;
1553 }
Aravind Akella70018042014-04-07 22:52:37 +00001554 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001555 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001556}
Aravind Akella70018042014-04-07 22:52:37 +00001557
Svetoslavb412f6e2015-04-29 16:50:41 -07001558bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1559 const String16& opPackageName) {
1560 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001561
Svetoslavb412f6e2015-04-29 16:50:41 -07001562 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001563 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001564 }
1565
1566 bool hasPermission = false;
1567
1568 // Runtime permissions can't use the cache as they may change.
1569 if (sensor.isRequiredPermissionRuntime()) {
1570 hasPermission = checkPermission(String16(requiredPermission),
1571 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001572 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001573 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1574 }
1575
1576 if (!hasPermission) {
1577 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1578 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001579 return false;
1580 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001581
1582 const int32_t opCode = sensor.getRequiredAppOp();
1583 if (opCode >= 0) {
1584 AppOpsManager appOps;
1585 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1586 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001587 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001588 operation, sensor.getName().string(), opCode);
1589 return false;
1590 }
1591 }
1592
1593 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001594}
1595
Aravind Akella9a844cf2014-02-11 18:58:52 -08001596void SensorService::checkWakeLockState() {
1597 Mutex::Autolock _l(mLock);
1598 checkWakeLockStateLocked();
1599}
1600
1601void SensorService::checkWakeLockStateLocked() {
1602 if (!mWakeLockAcquired) {
1603 return;
1604 }
1605 bool releaseLock = true;
1606 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1607 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001608 if (connection != nullptr) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001609 if (connection->needsWakeLock()) {
1610 releaseLock = false;
1611 break;
1612 }
1613 }
1614 }
1615 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001616 setWakeLockAcquiredLocked(false);
1617 }
1618}
1619
1620void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1621 Mutex::Autolock _l(mLock);
1622 connection->writeToSocketFromCache();
1623 if (connection->needsWakeLock()) {
1624 setWakeLockAcquiredLocked(true);
1625 }
1626}
1627
1628void SensorService::populateActiveConnections(
1629 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1630 Mutex::Autolock _l(mLock);
1631 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1632 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Yi Kong8f313e32018-07-17 14:13:29 -07001633 if (connection != nullptr) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001634 activeConnections->add(connection);
1635 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001636 }
1637}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001638
Aravind Akella4949c502015-02-11 15:54:35 -08001639bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001640 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001641}
1642
Peng Xue36e3472016-11-03 11:57:10 -07001643bool SensorService::isOperationRestricted(const String16& opPackageName) {
1644 Mutex::Autolock _l(mLock);
1645 if (mCurrentOperatingMode != RESTRICTED) {
1646 String8 package(opPackageName);
1647 return !isWhiteListedPackage(package);
1648 }
1649 return false;
1650}
1651
Svet Ganove752a5c2018-01-15 17:14:20 -08001652void SensorService::UidPolicy::registerSelf() {
1653 ActivityManager am;
1654 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1655 | ActivityManager::UID_OBSERVER_IDLE
1656 | ActivityManager::UID_OBSERVER_ACTIVE,
1657 ActivityManager::PROCESS_STATE_UNKNOWN,
1658 String16("android"));
1659}
1660
1661void SensorService::UidPolicy::unregisterSelf() {
1662 ActivityManager am;
1663 am.unregisterUidObserver(this);
1664}
1665
1666void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1667 onUidIdle(uid, disabled);
1668}
1669
1670void SensorService::UidPolicy::onUidActive(uid_t uid) {
1671 {
1672 Mutex::Autolock _l(mUidLock);
1673 mActiveUids.insert(uid);
1674 }
1675 sp<SensorService> service = mService.promote();
1676 if (service != nullptr) {
1677 service->setSensorAccess(uid, true);
1678 }
1679}
1680
1681void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1682 bool deleted = false;
1683 {
1684 Mutex::Autolock _l(mUidLock);
1685 if (mActiveUids.erase(uid) > 0) {
1686 deleted = true;
1687 }
1688 }
1689 if (deleted) {
1690 sp<SensorService> service = mService.promote();
1691 if (service != nullptr) {
1692 service->setSensorAccess(uid, false);
1693 }
1694 }
1695}
1696
1697void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1698 updateOverrideUid(uid, active, true);
1699}
1700
1701void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1702 updateOverrideUid(uid, false, false);
1703}
1704
1705void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1706 bool wasActive = false;
1707 bool isActive = false;
1708 {
1709 Mutex::Autolock _l(mUidLock);
1710 wasActive = isUidActiveLocked(uid);
1711 mOverrideUids.erase(uid);
1712 if (insert) {
1713 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1714 }
1715 isActive = isUidActiveLocked(uid);
1716 }
1717 if (wasActive != isActive) {
1718 sp<SensorService> service = mService.promote();
1719 if (service != nullptr) {
1720 service->setSensorAccess(uid, isActive);
1721 }
1722 }
1723}
1724
1725bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1726 // Non-app UIDs are considered always active
1727 if (uid < FIRST_APPLICATION_UID) {
1728 return true;
1729 }
1730 Mutex::Autolock _l(mUidLock);
1731 return isUidActiveLocked(uid);
1732}
1733
1734bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1735 // Non-app UIDs are considered always active
1736 if (uid < FIRST_APPLICATION_UID) {
1737 return true;
1738 }
1739 auto it = mOverrideUids.find(uid);
1740 if (it != mOverrideUids.end()) {
1741 return it->second;
1742 }
1743 return mActiveUids.find(uid) != mActiveUids.end();
1744}
1745
Mathias Agopianfc328812010-07-14 23:41:37 -07001746}; // namespace android