blob: 92c27b1c259f3e41b1c89f4ef65739122acbd9a8 [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 */
Brian Stack793f4642019-04-18 17:21:34 -070016#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080017#include <android/util/ProtoOutputStream.h>
18#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080019#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070021#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070022#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080023#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070024#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080025#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070026#include <cutils/properties.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070027#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070028#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080029#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070030#include <openssl/digest.h>
31#include <openssl/hmac.h>
32#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070033#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080034#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070035#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070036
Mathias Agopian787ac1b2012-09-18 18:49:18 -070037#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070038#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080039#include "GravitySensor.h"
40#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070041#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080042#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070043#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070044#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080045
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070047#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080049#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080050#include "SensorRecord.h"
51#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080052
Brian Stack51498e62018-10-03 10:52:21 -070053#include <ctime>
Peng Xueb4d6282015-12-10 18:02:41 -080054#include <inttypes.h>
55#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070056#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080057#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080058#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070059#include <sys/stat.h>
60#include <sys/types.h>
61#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070062
Svet Ganove752a5c2018-01-15 17:14:20 -080063#include <private/android_filesystem_config.h>
64
Mathias Agopianfc328812010-07-14 23:41:37 -070065namespace android {
66// ---------------------------------------------------------------------------
67
Mathias Agopian33015422011-05-27 18:18:13 -070068/*
69 * Notes:
70 *
71 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070072 * - run mag sensor from time to time to force calibration
73 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
74 *
75 */
76
Aravind Akella8ef3c892015-07-10 11:24:28 -070077const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070078uint8_t SensorService::sHmacGlobalKey[128] = {};
79bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070080std::map<String16, int> SensorService::sPackageTargetVersion;
81Mutex SensorService::sPackageTargetVersionLock;
82AppOpsManager SensorService::sAppOpsManager;
Greg Kaiser53ca2e02016-06-21 16:11:14 -070083
84#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
85#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070086#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070087
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070088// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070089static const String16 sDumpPermission("android.permission.DUMP");
90static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080091static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070092
Mathias Agopianfc328812010-07-14 23:41:37 -070093SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070094 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070095 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +090096 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -080097 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -070098}
99
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700100bool SensorService::initializeHmacKey() {
101 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
102 if (fd != -1) {
103 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
104 close(fd);
105 if (result == sizeof(sHmacGlobalKey)) {
106 return true;
107 }
108 ALOGW("Unable to read HMAC key; generating new one.");
109 }
110
111 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
112 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
113 return false;
114 }
115
116 // We need to make sure this is only readable to us.
117 bool wroteKey = false;
118 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
119 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
120 S_IRUSR|S_IWUSR);
121 if (fd != -1) {
122 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
123 close(fd);
124 wroteKey = (result == sizeof(sHmacGlobalKey));
125 }
126 if (wroteKey) {
127 ALOGI("Generated new HMAC key.");
128 } else {
129 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
130 "after reboot.");
131 }
132 // Even if we failed to write the key we return true, because we did
133 // initialize the HMAC key.
134 return true;
135}
136
Peng Xu98d30f62016-08-01 18:12:11 -0700137// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
138void SensorService::enableSchedFifoMode() {
139 struct sched_param param = {0};
140 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
141 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
142 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
143 }
144}
145
Peng Xu47e96012016-03-28 17:55:56 -0700146void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000147 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800148 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700149
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700150 sHmacGlobalKeyIsValid = initializeHmacKey();
151
Mathias Agopianf001c922010-11-11 17:58:51 -0800152 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800153 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700154 ssize_t count = dev.getSensorList(&list);
155 if (count > 0) {
156 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700157 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700158 uint32_t virtualSensorsNeeds =
159 (1<<SENSOR_TYPE_GRAVITY) |
160 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700161 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
162 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
163 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700164
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700165 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700166 bool useThisSensor=true;
167
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700168 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700169 case SENSOR_TYPE_ACCELEROMETER:
170 hasAccel = true;
171 break;
172 case SENSOR_TYPE_MAGNETIC_FIELD:
173 hasMag = true;
174 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700175 case SENSOR_TYPE_ORIENTATION:
176 orientationIndex = i;
177 break;
178 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700179 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700180 hasGyro = true;
181 break;
182 case SENSOR_TYPE_GRAVITY:
183 case SENSOR_TYPE_LINEAR_ACCELERATION:
184 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700185 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
186 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
187 if (IGNORE_HARDWARE_FUSION) {
188 useThisSensor = false;
189 } else {
190 virtualSensorsNeeds &= ~(1<<list[i].type);
191 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700192 break;
193 }
Peng Xuf66684a2015-07-23 11:41:53 -0700194 if (useThisSensor) {
195 registerSensor( new HardwareSensor(list[i]) );
196 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700197 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700198
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700199 // it's safe to instantiate the SensorFusion object here
200 // (it wants to be instantiated after h/w sensors have been
201 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700202 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700203
Aravind Akellaf5047892015-07-20 17:29:33 -0700204 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700205 // Add Android virtual sensors if they're not already
206 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700207 bool needRotationVector =
208 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700209
Peng Xu0cc8f802016-04-05 23:46:03 -0700210 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
211 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700212
Peng Xu0cc8f802016-04-05 23:46:03 -0700213 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700214 registerSensor( new CorrectedGyroSensor(list, count), true, true);
215 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700216 }
217
Peng Xuf66684a2015-07-23 11:41:53 -0700218 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700219 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
220 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700221
Pierre Fite-Georgel63daa662019-12-17 16:52:29 -0800222 bool needLinearAcceleration =
223 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
224 registerSensor(new LinearAccelerationSensor(list, count),
225 !needLinearAcceleration, true);
226
Peng Xu0cc8f802016-04-05 23:46:03 -0700227 bool needGameRotationVector =
228 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
229 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700230 }
231
232 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700233 bool needGeoMagRotationVector =
234 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
235 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700236 }
237
Aravind Akella5466c3d2014-08-22 16:11:10 -0700238 // Check if the device really supports batching by looking at the FIFO event
239 // counts for each sensor.
240 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700241 mSensors.forEachSensor(
242 [&batchingSupported] (const Sensor& s) -> bool {
243 if (s.getFifoMaxEventCount() > 0) {
244 batchingSupported = true;
245 }
246 return !batchingSupported;
247 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700248
249 if (batchingSupported) {
250 // Increase socket buffer size to a max of 100 KB for batching capabilities.
251 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
252 } else {
253 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
254 }
255
256 // Compare the socketBufferSize value against the system limits and limit
257 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700258 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
259 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700260 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700261 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700262 size_t maxSystemSocketBufferSize;
263 sscanf(line, "%zu", &maxSystemSocketBufferSize);
264 if (mSocketBufferSize > maxSystemSocketBufferSize) {
265 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700266 }
267 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700268 if (fp) {
269 fclose(fp);
270 }
271
Aravind Akella9a844cf2014-02-11 18:58:52 -0800272 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700273 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700274 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
275 mSensorEventBuffer = new sensors_event_t[minBufferSize];
276 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700277 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700278 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700279
Aravind Akella18d6d512015-06-18 14:18:28 -0700280 mNextSensorRegIndex = 0;
281 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
282 mLastNSensorRegistrations.push();
283 }
284
285 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700286 mAckReceiver = new SensorEventAckReceiver(this);
287 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700288 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700289
290 // priority can only be changed after run
291 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800292
293 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800294 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800295
296 // Start watching sensor privacy changes
297 mSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800298 }
299 }
300}
301
302void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
Brian Duddie967ce172019-06-10 11:08:27 -0700303 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700304 const auto& connections = connLock.getActiveConnections();
Arthur Ishiguro14c96b12020-03-26 15:09:03 -0700305 const auto& directConnections = connLock.getDirectConnections();
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700306
307 mLock.unlock();
308 for (const sp<SensorEventConnection>& conn : connections) {
Brian Duddie967ce172019-06-10 11:08:27 -0700309 if (conn->getUid() == uid) {
310 conn->setSensorAccess(hasAccess);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700311 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700312 }
Arthur Ishiguro14c96b12020-03-26 15:09:03 -0700313
314 for (const sp<SensorDirectConnection>& conn : directConnections) {
315 if (conn->getUid() == uid) {
316 conn->setSensorAccess(hasAccess);
317 }
318 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700319}
320
Peng Xu0cc8f802016-04-05 23:46:03 -0700321const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
322 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800323 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700324 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700325 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700326 return s->getSensor();
327 } else {
328 return mSensors.getNonSensor();
329 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800330}
331
Peng Xu6a2d3a02015-12-21 12:00:23 -0800332const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700333 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800334}
335
Peng Xu6a2d3a02015-12-21 12:00:23 -0800336bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700337 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800338
339 const auto i = mRecentEvent.find(handle);
340 if (i != mRecentEvent.end()) {
341 delete i->second;
342 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800343 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700344 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800345}
346
Peng Xu0cc8f802016-04-05 23:46:03 -0700347const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
348 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700349}
350
Peng Xu47e96012016-03-28 17:55:56 -0700351SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800352 for (auto && entry : mRecentEvent) {
353 delete entry.second;
354 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800355 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800356 mSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700357}
358
359status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700360 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700361 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800362 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700363 IPCThreadState::self()->getCallingPid(),
364 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700365 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700366 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700367 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800368 return INVALID_OPERATION;
369 }
Brian Duddie967ce172019-06-10 11:08:27 -0700370 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800371 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700372 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700373 // If already in restricted mode. Ignore.
374 if (mCurrentOperatingMode == RESTRICTED) {
375 return status_t(NO_ERROR);
376 }
377 // If in any mode other than normal, ignore.
378 if (mCurrentOperatingMode != NORMAL) {
379 return INVALID_OPERATION;
380 }
Peng Xue36e3472016-11-03 11:57:10 -0700381
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700382 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800383 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700384 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700385 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700386 return status_t(NO_ERROR);
387 } else if (args.size() == 1 && args[0] == String16("enable")) {
388 // If currently in restricted mode, reset back to NORMAL mode else ignore.
389 if (mCurrentOperatingMode == RESTRICTED) {
390 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800391 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700392 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700393 }
Aravind Akella841a5922015-06-29 12:37:48 -0700394 if (mCurrentOperatingMode == DATA_INJECTION) {
395 resetToNormalModeLocked();
396 }
397 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700398 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700399 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
400 if (mCurrentOperatingMode == NORMAL) {
401 dev.disableAllSensors();
402 status_t err = dev.setMode(DATA_INJECTION);
403 if (err == NO_ERROR) {
404 mCurrentOperatingMode = DATA_INJECTION;
405 } else {
406 // Re-enable sensors.
407 dev.enableAllSensors();
408 }
409 mWhiteListedPackage.setTo(String8(args[1]));
410 return NO_ERROR;
411 } else if (mCurrentOperatingMode == DATA_INJECTION) {
412 // Already in DATA_INJECTION mode. Treat this as a no_op.
413 return NO_ERROR;
414 } else {
415 // Transition to data injection mode supported only from NORMAL mode.
416 return INVALID_OPERATION;
417 }
Mike Ma24743862020-01-29 00:36:55 -0800418 } else if (args.size() == 1 && args[0] == String16("--proto")) {
419 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700420 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700421 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700422 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700423 } else {
424 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700425 //
Brian Stack51498e62018-10-03 10:52:21 -0700426 timespec curTime;
427 clock_gettime(CLOCK_REALTIME, &curTime);
428 struct tm* timeinfo = localtime(&(curTime.tv_sec));
429 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
430 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800431 result.append("Sensor Device:\n");
432 result.append(SensorDevice::getInstance().dump().c_str());
433
434 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700435 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700436
Peng Xu6a2d3a02015-12-21 12:00:23 -0800437 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700438 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700439
Peng Xu0cc8f802016-04-05 23:46:03 -0700440 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800441 for (auto&& i : mRecentEvent) {
442 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700443 if (!i.second->isEmpty()) {
444 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
445 i.second->setFormat("normal");
446 } else {
447 i.second->setFormat("mask_data");
448 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800449 // if there is events and sensor does not need special permission.
450 result.appendFormat("%s: ", s->getSensor().getName().string());
451 result.append(i.second->dump().c_str());
452 }
453 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700454
Aravind Akella444f2672015-05-07 12:40:52 -0700455 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700456 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700457 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
458 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700459 if (dev.isSensorActive(handle)) {
460 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
461 getSensorName(handle).string(),
462 handle,
463 mActiveSensors.valueAt(i)->getNumConnections());
464 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700465 }
466
Andreas Gamped4036b62015-07-28 13:49:04 -0700467 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700468 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700469 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
470 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700471 result.appendFormat("Mode :");
472 switch(mCurrentOperatingMode) {
473 case NORMAL:
474 result.appendFormat(" NORMAL\n");
475 break;
476 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700477 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700478 break;
479 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700480 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700481 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800482 result.appendFormat("Sensor Privacy: %s\n",
483 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700484
Brian Duddie967ce172019-06-10 11:08:27 -0700485 const auto& activeConnections = connLock.getActiveConnections();
486 result.appendFormat("%zd active connections\n", activeConnections.size());
487 for (size_t i=0 ; i < activeConnections.size() ; i++) {
488 result.appendFormat("Connection Number: %zu \n", i);
489 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700490 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700491
Brian Duddie967ce172019-06-10 11:08:27 -0700492 const auto& directConnections = connLock.getDirectConnections();
493 result.appendFormat("%zd direct connections\n", directConnections.size());
494 for (size_t i = 0 ; i < directConnections.size() ; i++) {
495 result.appendFormat("Direct connection %zu:\n", i);
496 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700497 }
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
Mike Ma24743862020-01-29 00:36:55 -0800522/**
523 * Dump debugging information as android.service.SensorServiceProto protobuf message using
524 * ProtoOutputStream.
525 *
526 * See proto definition and some notes about ProtoOutputStream in
527 * frameworks/base/core/proto/android/service/sensor_service.proto
528 */
529status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
530 using namespace service::SensorServiceProto;
531 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800532 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
533 if (!mSensors.hasAnySensor()) {
534 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
535 }
Mike Ma24743862020-01-29 00:36:55 -0800536 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
537
538 timespec curTime;
539 clock_gettime(CLOCK_REALTIME, &curTime);
540 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
541
542 // Write SensorDeviceProto
543 uint64_t token = proto.start(SENSOR_DEVICE);
544 SensorDevice::getInstance().dump(&proto);
545 proto.end(token);
546
547 // Write SensorListProto
548 token = proto.start(SENSORS);
549 mSensors.dump(&proto);
550 proto.end(token);
551
552 // Write SensorFusionProto
553 token = proto.start(FUSION_STATE);
554 SensorFusion::getInstance().dump(&proto);
555 proto.end(token);
556
557 // Write SensorEventsProto
558 token = proto.start(SENSOR_EVENTS);
559 for (auto&& i : mRecentEvent) {
560 sp<SensorInterface> s = mSensors.getInterface(i.first);
561 if (!i.second->isEmpty()) {
562 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
563 "normal" : "mask_data");
564 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
565 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
566 std::string(s->getSensor().getName().string()));
567 i.second->dump(&proto);
568 proto.end(mToken);
569 }
570 }
571 proto.end(token);
572
573 // Write ActiveSensorProto
574 SensorDevice& dev = SensorDevice::getInstance();
575 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
576 int handle = mActiveSensors.keyAt(i);
577 if (dev.isSensorActive(handle)) {
578 token = proto.start(ACTIVE_SENSORS);
579 proto.write(service::ActiveSensorProto::NAME,
580 std::string(getSensorName(handle).string()));
581 proto.write(service::ActiveSensorProto::HANDLE, handle);
582 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
583 int(mActiveSensors.valueAt(i)->getNumConnections()));
584 proto.end(token);
585 }
586 }
587
588 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
589 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
590 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
591
592 switch(mCurrentOperatingMode) {
593 case NORMAL:
594 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
595 break;
596 case RESTRICTED:
597 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
598 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
599 break;
600 case DATA_INJECTION:
601 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
602 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
603 break;
604 default:
605 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
606 }
607 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
608
609 // Write repeated SensorEventConnectionProto
610 const auto& activeConnections = connLock->getActiveConnections();
611 for (size_t i = 0; i < activeConnections.size(); i++) {
612 token = proto.start(ACTIVE_CONNECTIONS);
613 activeConnections[i]->dump(&proto);
614 proto.end(token);
615 }
616
617 // Write repeated SensorDirectConnectionProto
618 const auto& directConnections = connLock->getDirectConnections();
619 for (size_t i = 0 ; i < directConnections.size() ; i++) {
620 token = proto.start(DIRECT_CONNECTIONS);
621 directConnections[i]->dump(&proto);
622 proto.end(token);
623 }
624
625 // Write repeated SensorRegistrationInfoProto
626 const int startIndex = mNextSensorRegIndex;
627 int curr = startIndex;
628 do {
629 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
630 if (SensorRegistrationInfo::isSentinel(reg_info)) {
631 // Ignore sentinel, proceed to next item.
632 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
633 continue;
634 }
635 token = proto.start(PREVIOUS_REGISTRATIONS);
636 reg_info.dump(&proto);
637 proto.end(token);
638 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
639 } while (startIndex != curr);
640
641 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
642}
643
Michael Groover5e1f60b2018-12-04 22:34:29 -0800644void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700645 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
646 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800647}
648
Brian Duddie967ce172019-06-10 11:08:27 -0700649void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800650 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700651 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
652 connection->updateSensorSubscriptions();
653 }
Brian Duddie967ce172019-06-10 11:08:27 -0700654 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
Arthur Ishiguro14c96b12020-03-26 15:09:03 -0700655 connection->updateSensorSubscriptions();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800656 }
657 dev.disableAllSensors();
658 // Clear all pending flush connections for all active sensors. If one of the active
659 // connections has called flush() and the underlying sensor has been disabled before a
660 // flush complete event is returned, we need to remove the connection from this queue.
661 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
662 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
663 }
664}
665
666void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700667 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
668 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800669}
670
Brian Duddie967ce172019-06-10 11:08:27 -0700671void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800672 // sensors should only be enabled if the operating state is not restricted and sensor
673 // privacy is not enabled.
674 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
675 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
676 mCurrentOperatingMode,
677 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
678 return;
679 }
680 SensorDevice& dev(SensorDevice::getInstance());
681 dev.enableAllSensors();
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700682 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
683 connection->updateSensorSubscriptions();
684 }
Brian Duddie967ce172019-06-10 11:08:27 -0700685 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
Arthur Ishiguro14c96b12020-03-26 15:09:03 -0700686 connection->updateSensorSubscriptions();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800687 }
688}
689
Brian Duddie967ce172019-06-10 11:08:27 -0700690
Svet Ganove752a5c2018-01-15 17:14:20 -0800691// NOTE: This is a remote API - make sure all args are validated
692status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
693 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
694 return PERMISSION_DENIED;
695 }
696 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
697 return BAD_VALUE;
698 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700699 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800700 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700701 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800702 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700703 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800704 return handleGetUidState(args, out, err);
705 } else if (args.size() == 1 && args[0] == String16("help")) {
706 printHelp(out);
707 return NO_ERROR;
708 }
709 printHelp(err);
710 return BAD_VALUE;
711}
712
Tanmay Patild33a1822019-04-11 18:38:55 -0700713static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800714 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700715 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800716 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700717 ALOGE("Unknown package: '%s'", String8(packageName).string());
718 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800719 return BAD_VALUE;
720 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700721
722 if (userId < 0) {
723 ALOGE("Invalid user: %d", userId);
724 dprintf(err, "Invalid user: %d\n", userId);
725 return BAD_VALUE;
726 }
727
728 uid = multiuser_get_uid(userId, uid);
729 return NO_ERROR;
730}
731
732status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
733 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
734 if (!(args.size() == 3 || args.size() == 5)) {
735 printHelp(err);
736 return BAD_VALUE;
737 }
738
Svet Ganove752a5c2018-01-15 17:14:20 -0800739 bool active = false;
740 if (args[2] == String16("active")) {
741 active = true;
742 } else if ((args[2] != String16("idle"))) {
743 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
744 return BAD_VALUE;
745 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700746
747 int userId = 0;
748 if (args.size() == 5 && args[3] == String16("--user")) {
749 userId = atoi(String8(args[4]));
750 }
751
752 uid_t uid;
753 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
754 return BAD_VALUE;
755 }
756
Svet Ganove752a5c2018-01-15 17:14:20 -0800757 mUidPolicy->addOverrideUid(uid, active);
758 return NO_ERROR;
759}
760
761status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700762 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
763 if (!(args.size() == 2 || args.size() == 4)) {
764 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800765 return BAD_VALUE;
766 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700767
768 int userId = 0;
769 if (args.size() == 4 && args[2] == String16("--user")) {
770 userId = atoi(String8(args[3]));
771 }
772
773 uid_t uid;
774 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
775 return BAD_VALUE;
776 }
777
Svet Ganove752a5c2018-01-15 17:14:20 -0800778 mUidPolicy->removeOverrideUid(uid);
779 return NO_ERROR;
780}
781
782status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700783 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
784 if (!(args.size() == 2 || args.size() == 4)) {
785 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800786 return BAD_VALUE;
787 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700788
789 int userId = 0;
790 if (args.size() == 4 && args[2] == String16("--user")) {
791 userId = atoi(String8(args[3]));
792 }
793
794 uid_t uid;
795 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
796 return BAD_VALUE;
797 }
798
Svet Ganove752a5c2018-01-15 17:14:20 -0800799 if (mUidPolicy->isUidActive(uid)) {
800 return dprintf(out, "active\n");
801 } else {
802 return dprintf(out, "idle\n");
803 }
804}
805
806status_t SensorService::printHelp(int out) {
807 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700808 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
809 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
810 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800811 " help print this message\n");
812}
813
Peng Xu0cc8f802016-04-05 23:46:03 -0700814//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800815void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700816 sensors_event_t const* buffer, const int count) {
817 for (int i=0 ; i<count ; i++) {
818 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700819 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
820 handle = buffer[i].meta_data.sensor;
821 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700822 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700823 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700824 // If this buffer has an event from a one_shot sensor and this connection is registered
825 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700826 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700827 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
828 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800829 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700830 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700831
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700832 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700833 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700834}
835
Peng Xu47e96012016-03-28 17:55:56 -0700836bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000837 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700838
Peng Xueb4d6282015-12-10 18:02:41 -0800839 // each virtual sensor could generate an event per "real" event, that's why we need to size
840 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
841 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700842 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700843 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700844 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700845
Mathias Agopianf001c922010-11-11 17:58:51 -0800846 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700847
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700848 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700849 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700850 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
851 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700852 if(count == DEAD_OBJECT && device.isReconnecting()) {
853 device.reconnect();
854 continue;
855 } else {
856 ALOGE("sensor poll failed (%s)", strerror(-count));
857 break;
858 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700859 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700860
861 // Reset sensors_event_t.flags to zero for all events in the buffer.
862 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700863 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700864 }
Brian Duddie967ce172019-06-10 11:08:27 -0700865 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700866
Aravind Akella9a844cf2014-02-11 18:58:52 -0800867 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
868 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
869 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
870 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
871 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700872 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700873 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700874 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700875 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700876 }
877 }
878
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700879 if (wakeEvents > 0) {
880 if (!mWakeLockAcquired) {
881 setWakeLockAcquiredLocked(true);
882 }
883 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800884 }
Aravind Akella8493b792014-09-08 15:45:47 -0700885 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800886
Mathias Agopianf001c922010-11-11 17:58:51 -0800887 // handle virtual sensors
888 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700889 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700890 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800891 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700892 SensorFusion& fusion(SensorFusion::getInstance());
893 if (fusion.isEnabled()) {
894 for (size_t i=0 ; i<size_t(count) ; i++) {
895 fusion.process(event[i]);
896 }
897 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700898 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700899 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700900 if (count + k >= minBufferSize) {
901 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700902 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700903 count, k, minBufferSize);
904 break;
905 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800906 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700907 sp<SensorInterface> si = mSensors.getInterface(handle);
908 if (si == nullptr) {
909 ALOGE("handle %d is not an valid virtual sensor", handle);
910 continue;
911 }
912
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700913 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700914 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800915 k++;
916 }
917 }
918 }
919 if (k) {
920 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700921 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800922 count += k;
923 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700924 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700925 }
926 }
927 }
928
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700929 // handle backward compatibility for RotationVector sensor
930 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
931 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700932 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700933 // All the 4 components of the quaternion should be available
934 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700935 mSensorEventBuffer[i].data[4] = -1;
936 }
937 }
938 }
939
Brian Duddie967ce172019-06-10 11:08:27 -0700940 // Cache the list of active connections, since we use it in multiple places below but won't
941 // modify it here
942 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
943
Aravind Akella8493b792014-09-08 15:45:47 -0700944 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700945 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
946 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
947 // SensorEventConnection mapped to the corresponding flush_complete_event in
948 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700949 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700950 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
951 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
952 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700953 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700954 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
955 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700956 }
957 }
Peng Xu2576cb62016-01-20 00:22:09 -0800958
959 // handle dynamic sensor meta events, process registration and unregistration of dynamic
960 // sensor based on content of event.
961 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
962 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
963 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
964 const sensor_t& dynamicSensor =
965 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
966 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
967 handle, dynamicSensor.type, dynamicSensor.name);
968
Peng Xu0cc8f802016-04-05 23:46:03 -0700969 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800970 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700971 sensor_t s = dynamicSensor;
972 // make sure the dynamic sensor flag is set
973 s.flags |= DYNAMIC_SENSOR_MASK;
974 // force the handle to be consistent
975 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800976
977 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800978
Peng Xu0cc8f802016-04-05 23:46:03 -0700979 // This will release hold on dynamic sensor meta, so it should be called
980 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700981 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800982 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700983 } else {
984 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
985 }
Peng Xu2576cb62016-01-20 00:22:09 -0800986 } else {
987 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
988 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
989
990 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800991 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800992 ALOGE("Dynamic sensor release error.");
993 }
994
Brian Duddie967ce172019-06-10 11:08:27 -0700995 for (const sp<SensorEventConnection>& connection : activeConnections) {
996 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -0800997 }
998 }
999 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001000 }
1001
Aravind Akella9a844cf2014-02-11 18:58:52 -08001002 // Send our events to clients. Check the state of wake lock for each client and release the
1003 // lock if none of the clients need it.
1004 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -07001005 for (const sp<SensorEventConnection>& connection : activeConnections) {
1006 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1007 mMapFlushEventsToConnections);
1008 needsWakeLock |= connection->needsWakeLock();
1009 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1010 // Early check for one-shot sensors.
1011 if (connection->hasOneShotSensors()) {
1012 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001013 }
1014 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001015
Aravind Akella9a844cf2014-02-11 18:58:52 -08001016 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001017 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001018 }
Aravind Akella8493b792014-09-08 15:45:47 -07001019 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001020
Steve Block3c20fbe2012-01-05 23:22:43 +00001021 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001022 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001023 return false;
1024}
1025
Aravind Akella56ae4262014-07-10 16:01:10 -07001026sp<Looper> SensorService::getLooper() const {
1027 return mLooper;
1028}
1029
Aravind Akellab4373ac2014-10-29 17:55:20 -07001030void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001031 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1032 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1033 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001034 }
Brian Duddie967ce172019-06-10 11:08:27 -07001035 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001036}
1037
1038void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1039 if (acquire) {
1040 if (!mWakeLockAcquired) {
1041 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1042 mWakeLockAcquired = true;
1043 }
1044 mLooper->wake();
1045 } else {
1046 if (mWakeLockAcquired) {
1047 release_wake_lock(WAKE_LOCK_NAME);
1048 mWakeLockAcquired = false;
1049 }
1050 }
1051}
1052
Aravind Akellab4373ac2014-10-29 17:55:20 -07001053bool SensorService::isWakeLockAcquired() {
1054 Mutex::Autolock _l(mLock);
1055 return mWakeLockAcquired;
1056}
1057
Aravind Akella56ae4262014-07-10 16:01:10 -07001058bool SensorService::SensorEventAckReceiver::threadLoop() {
1059 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001060 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001061 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001062 bool wakeLockAcquired = mService->isWakeLockAcquired();
1063 int timeout = -1;
1064 if (wakeLockAcquired) timeout = 5000;
1065 int ret = looper->pollOnce(timeout);
1066 if (ret == ALOOPER_POLL_TIMEOUT) {
1067 mService->resetAllWakeLockRefCounts();
1068 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001069 } while(!Thread::exitPending());
1070 return false;
1071}
1072
Aravind Akella9a844cf2014-02-11 18:58:52 -08001073void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001074 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001075 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001076 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1077 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001078 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001079 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001080 }
Peng Xu2576cb62016-01-20 00:22:09 -08001081
Peng Xu6a2d3a02015-12-21 12:00:23 -08001082 auto logger = mRecentEvent.find(buffer[i].sensor);
1083 if (logger != mRecentEvent.end()) {
1084 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001085 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001086 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001087}
1088
Peng Xu47e96012016-03-28 17:55:56 -07001089void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001090 struct compar {
1091 static int cmp(void const* lhs, void const* rhs) {
1092 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1093 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001094 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001095 }
1096 };
1097 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1098}
1099
Mathias Agopian5d270722010-07-19 15:20:39 -07001100String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001101 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001102}
1103
Aravind Akellab4099e72013-10-15 15:43:10 -07001104bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001105 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1106 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001107}
1108
Aravind Akella9a844cf2014-02-11 18:58:52 -08001109bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001110 int handle = event.sensor;
1111 if (event.type == SENSOR_TYPE_META_DATA) {
1112 handle = event.meta_data.sensor;
1113 }
Peng Xu755c4512016-04-07 23:15:14 -07001114 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1115 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001116}
1117
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001118int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1119 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1120 // UUID is not supported for this device.
1121 return 0;
1122 }
1123 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1124 // This sensor can be uniquely identified in the system by
1125 // the combination of its type and name.
1126 return -1;
1127 }
1128
1129 // We have a dynamic sensor.
1130
1131 if (!sHmacGlobalKeyIsValid) {
1132 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1133 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1134 return 0;
1135 }
1136
1137 // We want each app author/publisher to get a different ID, so that the
1138 // same dynamic sensor cannot be tracked across apps by multiple
1139 // authors/publishers. So we use both our UUID and our User ID.
1140 // Note potential confusion:
1141 // UUID => Universally Unique Identifier.
1142 // UID => User Identifier.
1143 // We refrain from using "uid" except as needed by API to try to
1144 // keep this distinction clear.
1145
1146 auto appUserId = IPCThreadState::self()->getCallingUid();
1147 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1148 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1149 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1150
1151 // Now we use our key on our UUID/app combo to get the hash.
1152 uint8_t hash[EVP_MAX_MD_SIZE];
1153 unsigned int hashLen;
1154 if (HMAC(EVP_sha256(),
1155 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1156 uuidAndApp, sizeof(uuidAndApp),
1157 hash, &hashLen) == nullptr) {
1158 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1159 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1160 return 0;
1161 }
1162
1163 int32_t id = 0;
1164 if (hashLen < sizeof(id)) {
1165 // We never expect this case, but out of paranoia, we handle it.
1166 // Our 'id' length is already quite small, we don't want the
1167 // effective length of it to be even smaller.
1168 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1169 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1170 return 0;
1171 }
1172
1173 // This is almost certainly less than all of 'hash', but it's as secure
1174 // as we can be with our current 'id' length.
1175 memcpy(&id, hash, sizeof(id));
1176
1177 // Note at the beginning of the function that we return the values of
1178 // 0 and -1 to represent special cases. As a result, we can't return
1179 // those as dynamic sensor IDs. If we happened to hash to one of those
1180 // values, we change 'id' so we report as a dynamic sensor, and not as
1181 // one of those special cases.
1182 if (id == -1) {
1183 id = -2;
1184 } else if (id == 0) {
1185 id = 1;
1186 }
1187 return id;
1188}
1189
1190void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1191 for (auto &sensor : sensorList) {
1192 int32_t id = getIdFromUuid(sensor.getUuid());
1193 sensor.setId(id);
1194 }
1195}
1196
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001197Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001198 char value[PROPERTY_VALUE_MAX];
1199 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001200 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001201 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001202 Vector<Sensor> accessibleSensorList;
1203 for (size_t i = 0; i < initialSensorList.size(); i++) {
1204 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001205 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001206 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001207 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001208 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001209}
1210
Peng Xu47e96012016-03-28 17:55:56 -07001211Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001212 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001213 mSensors.forEachSensor(
1214 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001215 if (sensor.isDynamicSensor()) {
1216 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1217 accessibleSensorList.add(sensor);
1218 } else {
1219 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1220 sensor.getName().string(),
1221 sensor.getRequiredPermission().string(),
1222 sensor.getRequiredAppOp());
1223 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001224 }
1225 return true;
1226 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001227 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001228 return accessibleSensorList;
1229}
1230
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001231sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001232 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001233 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1234 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001235 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001236 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001237
1238 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001239 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1240 // operating in DI mode.
1241 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001242 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1243 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001244 }
1245
Mathias Agopian5307d172012-09-18 17:02:43 -07001246 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001247 pid_t pid = IPCThreadState::self()->getCallingPid();
1248
1249 String8 connPackageName =
1250 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1251 String16 connOpPackageName =
1252 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001253 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001254 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001255 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001256 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001257 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001258 // Add the associated file descriptor to the Looper for polling whenever there is data to
1259 // be injected.
1260 result->updateLooperRegistration(mLooper);
1261 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001262 return result;
1263}
1264
Aravind Akella841a5922015-06-29 12:37:48 -07001265int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001266 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001267 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001268}
1269
Peng Xue36e3472016-11-03 11:57:10 -07001270sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1271 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1272 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001273 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001274
Michael Groover5e1f60b2018-12-04 22:34:29 -08001275 // No new direct connections are allowed when sensor privacy is enabled
1276 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1277 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1278 return nullptr;
1279 }
1280
Peng Xue36e3472016-11-03 11:57:10 -07001281 struct sensors_direct_mem_t mem = {
1282 .type = type,
1283 .format = format,
1284 .size = size,
1285 .handle = resource,
1286 };
1287 uid_t uid = IPCThreadState::self()->getCallingUid();
1288
1289 if (mem.handle == nullptr) {
1290 ALOGE("Failed to clone resource handle");
1291 return nullptr;
1292 }
1293
1294 // check format
1295 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1296 ALOGE("Direct channel format %d is unsupported!", format);
1297 return nullptr;
1298 }
1299
1300 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001301 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1302 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001303 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001304 return nullptr;
1305 }
1306 }
1307
1308 // check specific to memory type
1309 switch(type) {
1310 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001311 if (resource->numFds < 1) {
1312 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1313 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1314 return nullptr;
1315 }
Peng Xue36e3472016-11-03 11:57:10 -07001316 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001317 if (!ashmem_valid(fd)) {
1318 ALOGE("Supplied Ashmem memory region is invalid");
1319 return nullptr;
1320 }
1321
Peng Xue36e3472016-11-03 11:57:10 -07001322 int size2 = ashmem_get_size_region(fd);
1323 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001324 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001325 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1326 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001327 return nullptr;
1328 }
1329 break;
1330 }
1331 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001332 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001333 break;
1334 default:
1335 ALOGE("Unknown direct connection memory type %d", type);
1336 return nullptr;
1337 }
1338
1339 native_handle_t *clone = native_handle_clone(resource);
1340 if (!clone) {
1341 return nullptr;
1342 }
1343
Brian Duddie967ce172019-06-10 11:08:27 -07001344 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001345 SensorDevice& dev(SensorDevice::getInstance());
1346 int channelHandle = dev.registerDirectChannel(&mem);
1347
1348 if (channelHandle <= 0) {
1349 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1350 } else {
1351 mem.handle = clone;
1352 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1353 }
1354
1355 if (conn == nullptr) {
1356 native_handle_close(clone);
1357 native_handle_delete(clone);
1358 } else {
1359 // add to list of direct connections
1360 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001361 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001362 }
1363 return conn;
1364}
1365
Peng Xudd5c5cb2017-03-16 17:39:43 -07001366int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001367 int32_t handle, int32_t type,
1368 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001369 Mutex::Autolock _l(mLock);
1370
Alexey Polyudov88711e82017-05-23 19:54:04 -07001371 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001372 return PERMISSION_DENIED;
1373 }
1374
1375 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001376 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001377 size_t expectSize = INT32_MAX;
1378 switch (type) {
1379 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1380 isFloat = true;
1381 expectSize = 3;
1382 break;
1383 case AINFO_LOCAL_GRAVITY:
1384 isFloat = true;
1385 expectSize = 1;
1386 break;
1387 case AINFO_DOCK_STATE:
1388 case AINFO_HIGH_PERFORMANCE_MODE:
1389 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1390 isFloat = false;
1391 expectSize = 1;
1392 break;
1393 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001394 // CUSTOM events must only contain float data; it may have variable size
1395 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1396 ints.size() ||
1397 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1398 handle < 0) {
1399 return BAD_VALUE;
1400 }
1401 isFloat = true;
1402 isCustom = true;
1403 expectSize = floats.size();
1404 break;
1405 }
1406
1407 if (!isCustom && handle != -1) {
1408 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001409 }
1410
1411 // three events: first one is begin tag, last one is end tag, the one in the middle
1412 // is the payload.
1413 sensors_event_t event[3];
1414 int64_t timestamp = elapsedRealtimeNano();
1415 for (sensors_event_t* i = event; i < event + 3; i++) {
1416 *i = (sensors_event_t) {
1417 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001418 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001419 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1420 .timestamp = timestamp++,
1421 .additional_info = (additional_info_event_t) {
1422 .serial = 0
1423 }
1424 };
1425 }
1426
1427 event[0].additional_info.type = AINFO_BEGIN;
1428 event[1].additional_info.type = type;
1429 event[2].additional_info.type = AINFO_END;
1430
1431 if (isFloat) {
1432 if (floats.size() != expectSize) {
1433 return BAD_VALUE;
1434 }
1435 for (size_t i = 0; i < expectSize; ++i) {
1436 event[1].additional_info.data_float[i] = floats[i];
1437 }
1438 } else {
1439 if (ints.size() != expectSize) {
1440 return BAD_VALUE;
1441 }
1442 for (size_t i = 0; i < expectSize; ++i) {
1443 event[1].additional_info.data_int32[i] = ints[i];
1444 }
1445 }
1446
1447 SensorDevice& dev(SensorDevice::getInstance());
1448 for (sensors_event_t* i = event; i < event + 3; i++) {
1449 int ret = dev.injectSensorData(i);
1450 if (ret != NO_ERROR) {
1451 return ret;
1452 }
1453 }
1454 return NO_ERROR;
1455}
1456
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001457status_t SensorService::resetToNormalMode() {
1458 Mutex::Autolock _l(mLock);
1459 return resetToNormalModeLocked();
1460}
1461
1462status_t SensorService::resetToNormalModeLocked() {
1463 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001464 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301465 if (err == NO_ERROR) {
1466 mCurrentOperatingMode = NORMAL;
1467 dev.enableAllSensors();
1468 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001469 return err;
1470}
1471
Peng Xu47e96012016-03-28 17:55:56 -07001472void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001473 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001474 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001475 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001476 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001477 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001478 int handle = mActiveSensors.keyAt(i);
1479 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001480 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001481 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1482 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001483 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001484 } else {
1485 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001486 }
Aravind Akella8a969552014-09-28 17:52:41 -07001487 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001488 }
1489 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001490 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001491 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001492 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001493 c, i, handle);
1494
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001495 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001496 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001497 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001498 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001499 delete rec;
1500 size--;
1501 } else {
1502 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001503 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001504 }
Aravind Akella8a969552014-09-28 17:52:41 -07001505 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001506 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001507 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001508 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001509 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001510 }
Peng Xu4f707f82016-09-26 11:28:32 -07001511
Brian Stack793f4642019-04-18 17:21:34 -07001512 {
1513 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1514 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1515 if (iter != sPackageTargetVersion.end()) {
1516 sPackageTargetVersion.erase(iter);
1517 }
1518 }
1519
Peng Xu4f707f82016-09-26 11:28:32 -07001520 SensorDevice& dev(SensorDevice::getInstance());
1521 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001522}
1523
Peng Xue36e3472016-11-03 11:57:10 -07001524void SensorService::cleanupConnection(SensorDirectConnection* c) {
1525 Mutex::Autolock _l(mLock);
1526
1527 SensorDevice& dev(SensorDevice::getInstance());
1528 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001529 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001530}
1531
Peng Xu755c4512016-04-07 23:15:14 -07001532sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001533 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001534}
1535
Mathias Agopianfc328812010-07-14 23:41:37 -07001536status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001537 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001538 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001539 if (mInitCheck != NO_ERROR)
1540 return mInitCheck;
1541
Peng Xu755c4512016-04-07 23:15:14 -07001542 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1543 if (sensor == nullptr ||
1544 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001545 return BAD_VALUE;
1546 }
1547
Brian Duddie967ce172019-06-10 11:08:27 -07001548 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001549 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001550 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001551 return INVALID_OPERATION;
1552 }
1553
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001554 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001555 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001556 rec = new SensorRecord(connection);
1557 mActiveSensors.add(handle, rec);
1558 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001559 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001560 }
Brian Stack26029ee2019-04-22 17:25:49 -07001561
1562 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1563 // the recent event as stale to ensure that the previous event is not sent to a client. This
1564 // ensures on-change events that were generated during a previous sensor activation are not
1565 // erroneously sent to newly connected clients, especially if a second client registers for
1566 // an on-change sensor before the first client receives the updated event. Once an updated
1567 // event is received, the recent events will be marked as current, and any new clients will
1568 // immediately receive the most recent event.
1569 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1570 auto logger = mRecentEvent.find(handle);
1571 if (logger != mRecentEvent.end()) {
1572 logger->second->setLastEventStale();
1573 }
1574 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001575 } else {
1576 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001577 // this sensor is already activated, but we are adding a connection that uses it.
1578 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001579 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001580 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001581 // NOTE: The wake_up flag of this event may get set to
1582 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001583
1584 auto logger = mRecentEvent.find(handle);
1585 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001586 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001587 // Verify that the last sensor event was generated from the current activation
1588 // of the sensor. If not, it is possible for an on-change sensor to receive a
1589 // sensor event that is stale if two clients re-activate the sensor
1590 // simultaneously.
1591 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001592 event.sensor = handle;
1593 if (event.version == sizeof(sensors_event_t)) {
1594 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1595 setWakeLockAcquiredLocked(true);
1596 }
Yi Kong8f313e32018-07-17 14:13:29 -07001597 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001598 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001599 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001600 }
1601 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001602 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001603 }
1604 }
1605 }
1606 }
1607
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -07001608 if (connection->addSensor(handle, samplingPeriodNs, maxBatchReportLatencyNs, reservedFlags)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001609 BatteryService::enableSensor(connection->getUid(), handle);
1610 // the sensor was added (which means it wasn't already there)
1611 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001612 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001613 } else {
1614 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1615 handle, connection.get());
1616 }
1617
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301618 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001619 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301620 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1621 samplingPeriodNs = maxDelayNs;
1622 }
1623
Aravind Akella724d91d2013-06-27 12:04:23 -07001624 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1625 if (samplingPeriodNs < minDelayNs) {
1626 samplingPeriodNs = minDelayNs;
1627 }
1628
Aravind Akella6c2664a2014-08-13 12:24:50 -07001629 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1630 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001631 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1632
Aravind Akella4949c502015-02-11 15:54:35 -08001633 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001634 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001635
Peng Xu20483c42015-10-26 15:14:43 -07001636 // Call flush() before calling activate() on the sensor. Wait for a first
1637 // flush complete event before sending events on this connection. Ignore
1638 // one-shot sensors which don't support flush(). Ignore on-change sensors
1639 // to maintain the on-change logic (any on-change events except the initial
1640 // one should be trigger by a change in value). Also if this sensor isn't
1641 // already active, don't call flush().
1642 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001643 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001644 rec->getNumConnections() > 1) {
1645 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001646 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001647 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001648 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001649 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001650 } else {
1651 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001652 }
1653 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001654
1655 if (err == NO_ERROR) {
1656 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1657 err = sensor->activate(connection.get(), true);
1658 }
1659
Aravind Akella8a969552014-09-28 17:52:41 -07001660 if (err == NO_ERROR) {
1661 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001662
Brian Stack240d1d62019-05-17 09:49:39 -07001663 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1664 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001665 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1666 }
1667
Peng Xu51224682017-03-10 16:57:27 -08001668 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1669 SensorRegistrationInfo(handle, connection->getPackageName(),
1670 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001671 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001672 }
1673
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001674 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001675 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001676 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001677 }
1678 return err;
1679}
1680
Peng Xu47e96012016-03-28 17:55:56 -07001681status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001682 if (mInitCheck != NO_ERROR)
1683 return mInitCheck;
1684
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001685 Mutex::Autolock _l(mLock);
1686 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001687 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001688 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1689 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001690
1691 }
1692 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001693 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1694 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001695 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001696 }
1697 return err;
1698}
1699
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001700status_t SensorService::cleanupWithoutDisable(
1701 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001702 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001703 return cleanupWithoutDisableLocked(connection, handle);
1704}
1705
1706status_t SensorService::cleanupWithoutDisableLocked(
1707 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001708 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001709 if (rec) {
1710 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001711 if (connection->removeSensor(handle)) {
1712 BatteryService::disableSensor(connection->getUid(), handle);
1713 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001714 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001715 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001716 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001717 }
1718 // see if this sensor becomes inactive
1719 if (rec->removeConnection(connection)) {
1720 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001721 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001722 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001723 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001724 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001725 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001726 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001727}
1728
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001729status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001730 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001731 if (mInitCheck != NO_ERROR)
1732 return mInitCheck;
1733
Peng Xu755c4512016-04-07 23:15:14 -07001734 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1735 if (sensor == nullptr ||
1736 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001737 return BAD_VALUE;
1738 }
1739
Mathias Agopian1cd70002010-07-21 15:59:50 -07001740 if (ns < 0)
1741 return BAD_VALUE;
1742
Mathias Agopian62569ec2011-11-07 21:21:47 -08001743 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1744 if (ns < minDelayNs) {
1745 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001746 }
1747
Mathias Agopianf001c922010-11-11 17:58:51 -08001748 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001749}
1750
Svetoslavb412f6e2015-04-29 16:50:41 -07001751status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1752 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001753 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001754 SensorDevice& dev(SensorDevice::getInstance());
1755 const int halVersion = dev.getHalDeviceVersion();
1756 status_t err(NO_ERROR);
1757 Mutex::Autolock _l(mLock);
Arthur Ishiguro6eb75be2020-04-01 11:58:43 -07001758
1759 size_t numSensors = 0;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001760 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07001761 for (int handle : connection->getActiveSensorHandles()) {
Peng Xu755c4512016-04-07 23:15:14 -07001762 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1763 if (sensor == nullptr) {
1764 continue;
1765 }
Arthur Ishiguro6eb75be2020-04-01 11:58:43 -07001766 numSensors++;
1767
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001768 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1769 ALOGE("flush called on a one-shot sensor");
1770 err = INVALID_OPERATION;
1771 continue;
1772 }
Arthur Ishiguro6eb75be2020-04-01 11:58:43 -07001773
Aravind Akella8493b792014-09-08 15:45:47 -07001774 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001775 // For older devices just increment pending flush count which will send a trivial
1776 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001777 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001778 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001779 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1780 err = INVALID_OPERATION;
1781 continue;
1782 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001783 status_t err_flush = sensor->flush(connection.get(), handle);
1784 if (err_flush == NO_ERROR) {
1785 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001786 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001787 }
1788 err = (err_flush != NO_ERROR) ? err_flush : err;
1789 }
Aravind Akella70018042014-04-07 22:52:37 +00001790 }
Arthur Ishiguro6eb75be2020-04-01 11:58:43 -07001791
1792 return (numSensors == 0) ? INVALID_OPERATION : err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001793}
Aravind Akella70018042014-04-07 22:52:37 +00001794
Svetoslavb412f6e2015-04-29 16:50:41 -07001795bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1796 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001797 // Check if a permission is required for this sensor
1798 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001799 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001800 }
1801
Brian Stack793f4642019-04-18 17:21:34 -07001802 const int32_t opCode = sensor.getRequiredAppOp();
1803 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1804 IPCThreadState::self()->getCallingUid(), opPackageName);
Brian Stack6a700f92019-05-08 17:02:53 -07001805 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
Brian Stack793f4642019-04-18 17:21:34 -07001806
Brian Stack793f4642019-04-18 17:21:34 -07001807 bool canAccess = false;
Brian Stack6a700f92019-05-08 17:02:53 -07001808 if (hasPermissionForSensor(sensor)) {
1809 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1810 if (opCode < 0 || appOpAllowed) {
Brian Stack793f4642019-04-18 17:21:34 -07001811 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001812 }
1813 } else if (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1814 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR) {
1815 int targetSdkVersion = getTargetSdkVersion(opPackageName);
1816 // Allow access to the sensor if the application targets pre-Q, which is before the
1817 // requirement to hold the AR permission to access Step Counter and Step Detector events
1818 // was introduced, and the user hasn't revoked the app op.
1819 //
1820 // Verifying the app op is required to ensure that the user hasn't revoked the necessary
1821 // permissions to access the Step Detector and Step Counter when the application targets
1822 // pre-Q. Without this check, if the user revokes the pre-Q install-time GMS Core AR
1823 // permission, the app would still be able to receive Step Counter and Step Detector events.
1824 if (appOpAllowed &&
1825 targetSdkVersion > 0 &&
1826 targetSdkVersion <= __ANDROID_API_P__) {
1827 canAccess = true;
Brian Stack793f4642019-04-18 17:21:34 -07001828 }
1829 }
1830
1831 if (canAccess) {
1832 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1833 } else {
1834 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1835 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1836 }
1837
1838 return canAccess;
1839}
1840
1841bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001842 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001843 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001844
1845 // Runtime permissions can't use the cache as they may change.
1846 if (sensor.isRequiredPermissionRuntime()) {
1847 hasPermission = checkPermission(String16(requiredPermission),
1848 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001849 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001850 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1851 }
Brian Stack793f4642019-04-18 17:21:34 -07001852 return hasPermission;
1853}
Svetoslavb412f6e2015-04-29 16:50:41 -07001854
Brian Stack793f4642019-04-18 17:21:34 -07001855int SensorService::getTargetSdkVersion(const String16& opPackageName) {
1856 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1857 int targetSdkVersion = -1;
1858 auto entry = sPackageTargetVersion.find(opPackageName);
1859 if (entry != sPackageTargetVersion.end()) {
1860 targetSdkVersion = entry->second;
1861 } else {
1862 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1863 if (binder != nullptr) {
1864 sp<content::pm::IPackageManagerNative> packageManager =
1865 interface_cast<content::pm::IPackageManagerNative>(binder);
1866 if (packageManager != nullptr) {
1867 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1868 opPackageName, &targetSdkVersion);
1869 if (!status.isOk()) {
1870 targetSdkVersion = -1;
1871 }
1872 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001873 }
Brian Stack793f4642019-04-18 17:21:34 -07001874 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001875 }
Brian Stack793f4642019-04-18 17:21:34 -07001876 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001877}
1878
Aravind Akella9a844cf2014-02-11 18:58:52 -08001879void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001880 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1881 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001882}
1883
Brian Duddie967ce172019-06-10 11:08:27 -07001884void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001885 if (!mWakeLockAcquired) {
1886 return;
1887 }
1888 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001889 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1890 if (connection->needsWakeLock()) {
1891 releaseLock = false;
1892 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001893 }
1894 }
1895 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001896 setWakeLockAcquiredLocked(false);
1897 }
1898}
1899
1900void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1901 Mutex::Autolock _l(mLock);
1902 connection->writeToSocketFromCache();
1903 if (connection->needsWakeLock()) {
1904 setWakeLockAcquiredLocked(true);
1905 }
1906}
1907
Aravind Akella4949c502015-02-11 15:54:35 -08001908bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001909 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001910}
1911
Brian Stack5180e462019-03-08 17:15:19 -08001912bool SensorService::isOperationPermitted(const String16& opPackageName) {
Peng Xue36e3472016-11-03 11:57:10 -07001913 Mutex::Autolock _l(mLock);
Brian Stack5180e462019-03-08 17:15:19 -08001914 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001915 String8 package(opPackageName);
Brian Stack5180e462019-03-08 17:15:19 -08001916 return isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001917 }
Brian Stack5180e462019-03-08 17:15:19 -08001918 return true;
Peng Xue36e3472016-11-03 11:57:10 -07001919}
1920
Svet Ganove752a5c2018-01-15 17:14:20 -08001921void SensorService::UidPolicy::registerSelf() {
1922 ActivityManager am;
1923 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1924 | ActivityManager::UID_OBSERVER_IDLE
1925 | ActivityManager::UID_OBSERVER_ACTIVE,
1926 ActivityManager::PROCESS_STATE_UNKNOWN,
1927 String16("android"));
1928}
1929
1930void SensorService::UidPolicy::unregisterSelf() {
1931 ActivityManager am;
1932 am.unregisterUidObserver(this);
1933}
1934
1935void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1936 onUidIdle(uid, disabled);
1937}
1938
1939void SensorService::UidPolicy::onUidActive(uid_t uid) {
1940 {
1941 Mutex::Autolock _l(mUidLock);
1942 mActiveUids.insert(uid);
1943 }
1944 sp<SensorService> service = mService.promote();
1945 if (service != nullptr) {
1946 service->setSensorAccess(uid, true);
1947 }
1948}
1949
1950void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1951 bool deleted = false;
1952 {
1953 Mutex::Autolock _l(mUidLock);
1954 if (mActiveUids.erase(uid) > 0) {
1955 deleted = true;
1956 }
1957 }
1958 if (deleted) {
1959 sp<SensorService> service = mService.promote();
1960 if (service != nullptr) {
1961 service->setSensorAccess(uid, false);
1962 }
1963 }
1964}
1965
1966void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1967 updateOverrideUid(uid, active, true);
1968}
1969
1970void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1971 updateOverrideUid(uid, false, false);
1972}
1973
1974void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1975 bool wasActive = false;
1976 bool isActive = false;
1977 {
1978 Mutex::Autolock _l(mUidLock);
1979 wasActive = isUidActiveLocked(uid);
1980 mOverrideUids.erase(uid);
1981 if (insert) {
1982 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1983 }
1984 isActive = isUidActiveLocked(uid);
1985 }
1986 if (wasActive != isActive) {
1987 sp<SensorService> service = mService.promote();
1988 if (service != nullptr) {
1989 service->setSensorAccess(uid, isActive);
1990 }
1991 }
1992}
1993
1994bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1995 // Non-app UIDs are considered always active
1996 if (uid < FIRST_APPLICATION_UID) {
1997 return true;
1998 }
1999 Mutex::Autolock _l(mUidLock);
2000 return isUidActiveLocked(uid);
2001}
2002
2003bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
2004 // Non-app UIDs are considered always active
2005 if (uid < FIRST_APPLICATION_UID) {
2006 return true;
2007 }
2008 auto it = mOverrideUids.find(uid);
2009 if (it != mOverrideUids.end()) {
2010 return it->second;
2011 }
2012 return mActiveUids.find(uid) != mActiveUids.end();
2013}
2014
Michael Groover5e1f60b2018-12-04 22:34:29 -08002015void SensorService::SensorPrivacyPolicy::registerSelf() {
2016 SensorPrivacyManager spm;
2017 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2018 spm.addSensorPrivacyListener(this);
2019}
2020
2021void SensorService::SensorPrivacyPolicy::unregisterSelf() {
2022 SensorPrivacyManager spm;
2023 spm.removeSensorPrivacyListener(this);
2024}
2025
2026bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2027 return mSensorPrivacyEnabled;
2028}
2029
2030binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2031 mSensorPrivacyEnabled = enabled;
2032 sp<SensorService> service = mService.promote();
2033 if (service != nullptr) {
2034 if (enabled) {
2035 service->disableAllSensors();
2036 } else {
2037 service->enableAllSensors();
2038 }
2039 }
2040 return binder::Status::ok();
2041}
Brian Duddie967ce172019-06-10 11:08:27 -07002042
2043SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2044 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2045 : mConnectionHolder(holder), mAutolock(mutex) {}
2046
2047template<typename ConnectionType>
2048const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2049 const SortedVector<wp<ConnectionType>>& connectionList,
2050 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2051 referenceHolder->emplace_back();
2052 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2053 for (const wp<ConnectionType>& weakConnection : connectionList){
2054 sp<ConnectionType> connection = weakConnection.promote();
2055 if (connection != nullptr) {
2056 connections.push_back(std::move(connection));
2057 }
2058 }
2059 return connections;
2060}
2061
2062const std::vector<sp<SensorService::SensorEventConnection>>&
2063 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2064 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2065 &mReferencedActiveConnections);
2066}
2067
2068const std::vector<sp<SensorService::SensorDirectConnection>>&
2069 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2070 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2071 &mReferencedDirectConnections);
2072}
2073
2074void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2075 const sp<SensorService::SensorEventConnection>& connection) {
2076 if (mActiveConnections.indexOf(connection) < 0) {
2077 mActiveConnections.add(connection);
2078 }
2079}
2080
2081void SensorService::SensorConnectionHolder::removeEventConnection(
2082 const wp<SensorService::SensorEventConnection>& connection) {
2083 mActiveConnections.remove(connection);
2084}
2085
2086void SensorService::SensorConnectionHolder::addDirectConnection(
2087 const sp<SensorService::SensorDirectConnection>& connection) {
2088 mDirectConnections.add(connection);
2089}
2090
2091void SensorService::SensorConnectionHolder::removeDirectConnection(
2092 const wp<SensorService::SensorDirectConnection>& connection) {
2093 mDirectConnections.remove(connection);
2094}
2095
2096SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2097 return ConnectionSafeAutolock(*this, mutex);
2098}
2099
2100} // namespace android