blob: 9ed6fc291194cca1a5023fe6e5ead7879e714578 [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();
305
306 mLock.unlock();
307 for (const sp<SensorEventConnection>& conn : connections) {
Brian Duddie967ce172019-06-10 11:08:27 -0700308 if (conn->getUid() == uid) {
309 conn->setSensorAccess(hasAccess);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700310 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700311 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700312}
313
Peng Xu0cc8f802016-04-05 23:46:03 -0700314const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
315 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800316 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700317 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700318 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700319 return s->getSensor();
320 } else {
321 return mSensors.getNonSensor();
322 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800323}
324
Peng Xu6a2d3a02015-12-21 12:00:23 -0800325const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700326 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800327}
328
Peng Xu6a2d3a02015-12-21 12:00:23 -0800329bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700330 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800331
332 const auto i = mRecentEvent.find(handle);
333 if (i != mRecentEvent.end()) {
334 delete i->second;
335 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800336 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700337 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800338}
339
Peng Xu0cc8f802016-04-05 23:46:03 -0700340const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
341 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700342}
343
Peng Xu47e96012016-03-28 17:55:56 -0700344SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800345 for (auto && entry : mRecentEvent) {
346 delete entry.second;
347 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800348 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800349 mSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700350}
351
352status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700353 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700354 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800355 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700356 IPCThreadState::self()->getCallingPid(),
357 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700358 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700359 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700360 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800361 return INVALID_OPERATION;
362 }
Brian Duddie967ce172019-06-10 11:08:27 -0700363 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800364 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700365 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700366 // If already in restricted mode. Ignore.
367 if (mCurrentOperatingMode == RESTRICTED) {
368 return status_t(NO_ERROR);
369 }
370 // If in any mode other than normal, ignore.
371 if (mCurrentOperatingMode != NORMAL) {
372 return INVALID_OPERATION;
373 }
Peng Xue36e3472016-11-03 11:57:10 -0700374
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700375 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800376 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700377 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700378 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700379 return status_t(NO_ERROR);
380 } else if (args.size() == 1 && args[0] == String16("enable")) {
381 // If currently in restricted mode, reset back to NORMAL mode else ignore.
382 if (mCurrentOperatingMode == RESTRICTED) {
383 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800384 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700385 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700386 }
Aravind Akella841a5922015-06-29 12:37:48 -0700387 if (mCurrentOperatingMode == DATA_INJECTION) {
388 resetToNormalModeLocked();
389 }
390 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700391 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700392 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
393 if (mCurrentOperatingMode == NORMAL) {
394 dev.disableAllSensors();
395 status_t err = dev.setMode(DATA_INJECTION);
396 if (err == NO_ERROR) {
397 mCurrentOperatingMode = DATA_INJECTION;
398 } else {
399 // Re-enable sensors.
400 dev.enableAllSensors();
401 }
402 mWhiteListedPackage.setTo(String8(args[1]));
403 return NO_ERROR;
404 } else if (mCurrentOperatingMode == DATA_INJECTION) {
405 // Already in DATA_INJECTION mode. Treat this as a no_op.
406 return NO_ERROR;
407 } else {
408 // Transition to data injection mode supported only from NORMAL mode.
409 return INVALID_OPERATION;
410 }
Mike Ma24743862020-01-29 00:36:55 -0800411 } else if (args.size() == 1 && args[0] == String16("--proto")) {
412 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700413 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700414 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700415 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700416 } else {
417 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700418 //
Brian Stack51498e62018-10-03 10:52:21 -0700419 timespec curTime;
420 clock_gettime(CLOCK_REALTIME, &curTime);
421 struct tm* timeinfo = localtime(&(curTime.tv_sec));
422 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
423 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800424 result.append("Sensor Device:\n");
425 result.append(SensorDevice::getInstance().dump().c_str());
426
427 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700428 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700429
Peng Xu6a2d3a02015-12-21 12:00:23 -0800430 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700431 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700432
Peng Xu0cc8f802016-04-05 23:46:03 -0700433 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800434 for (auto&& i : mRecentEvent) {
435 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700436 if (!i.second->isEmpty()) {
437 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
438 i.second->setFormat("normal");
439 } else {
440 i.second->setFormat("mask_data");
441 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800442 // if there is events and sensor does not need special permission.
443 result.appendFormat("%s: ", s->getSensor().getName().string());
444 result.append(i.second->dump().c_str());
445 }
446 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700447
Aravind Akella444f2672015-05-07 12:40:52 -0700448 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700449 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700450 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
451 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700452 if (dev.isSensorActive(handle)) {
453 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
454 getSensorName(handle).string(),
455 handle,
456 mActiveSensors.valueAt(i)->getNumConnections());
457 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700458 }
459
Andreas Gamped4036b62015-07-28 13:49:04 -0700460 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700461 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700462 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
463 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700464 result.appendFormat("Mode :");
465 switch(mCurrentOperatingMode) {
466 case NORMAL:
467 result.appendFormat(" NORMAL\n");
468 break;
469 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700470 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700471 break;
472 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700473 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700474 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800475 result.appendFormat("Sensor Privacy: %s\n",
476 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700477
Brian Duddie967ce172019-06-10 11:08:27 -0700478 const auto& activeConnections = connLock.getActiveConnections();
479 result.appendFormat("%zd active connections\n", activeConnections.size());
480 for (size_t i=0 ; i < activeConnections.size() ; i++) {
481 result.appendFormat("Connection Number: %zu \n", i);
482 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700483 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700484
Brian Duddie967ce172019-06-10 11:08:27 -0700485 const auto& directConnections = connLock.getDirectConnections();
486 result.appendFormat("%zd direct connections\n", directConnections.size());
487 for (size_t i = 0 ; i < directConnections.size() ; i++) {
488 result.appendFormat("Direct connection %zu:\n", i);
489 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700490 }
491
Aravind Akella18d6d512015-06-18 14:18:28 -0700492 result.appendFormat("Previous Registrations:\n");
493 // Log in the reverse chronological order.
494 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
495 SENSOR_REGISTRATIONS_BUF_SIZE;
496 const int startIndex = currentIndex;
497 do {
498 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
499 if (SensorRegistrationInfo::isSentinel(reg_info)) {
500 // Ignore sentinel, proceed to next item.
501 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
502 SENSOR_REGISTRATIONS_BUF_SIZE;
503 continue;
504 }
Peng Xu51224682017-03-10 16:57:27 -0800505 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700506 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
507 SENSOR_REGISTRATIONS_BUF_SIZE;
508 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700509 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700510 }
511 write(fd, result.string(), result.size());
512 return NO_ERROR;
513}
514
Mike Ma24743862020-01-29 00:36:55 -0800515/**
516 * Dump debugging information as android.service.SensorServiceProto protobuf message using
517 * ProtoOutputStream.
518 *
519 * See proto definition and some notes about ProtoOutputStream in
520 * frameworks/base/core/proto/android/service/sensor_service.proto
521 */
522status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
523 using namespace service::SensorServiceProto;
524 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800525 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
526 if (!mSensors.hasAnySensor()) {
527 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
528 }
Mike Ma24743862020-01-29 00:36:55 -0800529 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
530
531 timespec curTime;
532 clock_gettime(CLOCK_REALTIME, &curTime);
533 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
534
535 // Write SensorDeviceProto
536 uint64_t token = proto.start(SENSOR_DEVICE);
537 SensorDevice::getInstance().dump(&proto);
538 proto.end(token);
539
540 // Write SensorListProto
541 token = proto.start(SENSORS);
542 mSensors.dump(&proto);
543 proto.end(token);
544
545 // Write SensorFusionProto
546 token = proto.start(FUSION_STATE);
547 SensorFusion::getInstance().dump(&proto);
548 proto.end(token);
549
550 // Write SensorEventsProto
551 token = proto.start(SENSOR_EVENTS);
552 for (auto&& i : mRecentEvent) {
553 sp<SensorInterface> s = mSensors.getInterface(i.first);
554 if (!i.second->isEmpty()) {
555 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
556 "normal" : "mask_data");
557 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
558 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
559 std::string(s->getSensor().getName().string()));
560 i.second->dump(&proto);
561 proto.end(mToken);
562 }
563 }
564 proto.end(token);
565
566 // Write ActiveSensorProto
567 SensorDevice& dev = SensorDevice::getInstance();
568 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
569 int handle = mActiveSensors.keyAt(i);
570 if (dev.isSensorActive(handle)) {
571 token = proto.start(ACTIVE_SENSORS);
572 proto.write(service::ActiveSensorProto::NAME,
573 std::string(getSensorName(handle).string()));
574 proto.write(service::ActiveSensorProto::HANDLE, handle);
575 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
576 int(mActiveSensors.valueAt(i)->getNumConnections()));
577 proto.end(token);
578 }
579 }
580
581 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
582 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
583 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
584
585 switch(mCurrentOperatingMode) {
586 case NORMAL:
587 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
588 break;
589 case RESTRICTED:
590 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
591 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
592 break;
593 case DATA_INJECTION:
594 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
595 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
596 break;
597 default:
598 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
599 }
600 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
601
602 // Write repeated SensorEventConnectionProto
603 const auto& activeConnections = connLock->getActiveConnections();
604 for (size_t i = 0; i < activeConnections.size(); i++) {
605 token = proto.start(ACTIVE_CONNECTIONS);
606 activeConnections[i]->dump(&proto);
607 proto.end(token);
608 }
609
610 // Write repeated SensorDirectConnectionProto
611 const auto& directConnections = connLock->getDirectConnections();
612 for (size_t i = 0 ; i < directConnections.size() ; i++) {
613 token = proto.start(DIRECT_CONNECTIONS);
614 directConnections[i]->dump(&proto);
615 proto.end(token);
616 }
617
618 // Write repeated SensorRegistrationInfoProto
619 const int startIndex = mNextSensorRegIndex;
620 int curr = startIndex;
621 do {
622 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
623 if (SensorRegistrationInfo::isSentinel(reg_info)) {
624 // Ignore sentinel, proceed to next item.
625 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
626 continue;
627 }
628 token = proto.start(PREVIOUS_REGISTRATIONS);
629 reg_info.dump(&proto);
630 proto.end(token);
631 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
632 } while (startIndex != curr);
633
634 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
635}
636
Michael Groover5e1f60b2018-12-04 22:34:29 -0800637void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700638 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
639 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800640}
641
Brian Duddie967ce172019-06-10 11:08:27 -0700642void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800643 SensorDevice& dev(SensorDevice::getInstance());
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700644 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
645 connection->updateSensorSubscriptions();
646 }
Brian Duddie967ce172019-06-10 11:08:27 -0700647 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
Arthur Ishiguroc8ad44b2020-04-13 08:04:47 -0700648 connection->stopAll(true /* backupRecord */);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800649 }
650 dev.disableAllSensors();
651 // Clear all pending flush connections for all active sensors. If one of the active
652 // connections has called flush() and the underlying sensor has been disabled before a
653 // flush complete event is returned, we need to remove the connection from this queue.
654 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
655 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
656 }
657}
658
659void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700660 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
661 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800662}
663
Brian Duddie967ce172019-06-10 11:08:27 -0700664void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800665 // sensors should only be enabled if the operating state is not restricted and sensor
666 // privacy is not enabled.
667 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
668 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
669 mCurrentOperatingMode,
670 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
671 return;
672 }
673 SensorDevice& dev(SensorDevice::getInstance());
674 dev.enableAllSensors();
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700675 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
676 connection->updateSensorSubscriptions();
677 }
Brian Duddie967ce172019-06-10 11:08:27 -0700678 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
Arthur Ishiguroc8ad44b2020-04-13 08:04:47 -0700679 connection->recoverAll();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800680 }
681}
682
Brian Duddie967ce172019-06-10 11:08:27 -0700683
Svet Ganove752a5c2018-01-15 17:14:20 -0800684// NOTE: This is a remote API - make sure all args are validated
685status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
686 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
687 return PERMISSION_DENIED;
688 }
689 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
690 return BAD_VALUE;
691 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700692 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800693 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700694 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800695 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700696 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800697 return handleGetUidState(args, out, err);
698 } else if (args.size() == 1 && args[0] == String16("help")) {
699 printHelp(out);
700 return NO_ERROR;
701 }
702 printHelp(err);
703 return BAD_VALUE;
704}
705
Tanmay Patild33a1822019-04-11 18:38:55 -0700706static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800707 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700708 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800709 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700710 ALOGE("Unknown package: '%s'", String8(packageName).string());
711 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800712 return BAD_VALUE;
713 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700714
715 if (userId < 0) {
716 ALOGE("Invalid user: %d", userId);
717 dprintf(err, "Invalid user: %d\n", userId);
718 return BAD_VALUE;
719 }
720
721 uid = multiuser_get_uid(userId, uid);
722 return NO_ERROR;
723}
724
725status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
726 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
727 if (!(args.size() == 3 || args.size() == 5)) {
728 printHelp(err);
729 return BAD_VALUE;
730 }
731
Svet Ganove752a5c2018-01-15 17:14:20 -0800732 bool active = false;
733 if (args[2] == String16("active")) {
734 active = true;
735 } else if ((args[2] != String16("idle"))) {
736 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
737 return BAD_VALUE;
738 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700739
740 int userId = 0;
741 if (args.size() == 5 && args[3] == String16("--user")) {
742 userId = atoi(String8(args[4]));
743 }
744
745 uid_t uid;
746 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
747 return BAD_VALUE;
748 }
749
Svet Ganove752a5c2018-01-15 17:14:20 -0800750 mUidPolicy->addOverrideUid(uid, active);
751 return NO_ERROR;
752}
753
754status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700755 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
756 if (!(args.size() == 2 || args.size() == 4)) {
757 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800758 return BAD_VALUE;
759 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700760
761 int userId = 0;
762 if (args.size() == 4 && args[2] == String16("--user")) {
763 userId = atoi(String8(args[3]));
764 }
765
766 uid_t uid;
767 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
768 return BAD_VALUE;
769 }
770
Svet Ganove752a5c2018-01-15 17:14:20 -0800771 mUidPolicy->removeOverrideUid(uid);
772 return NO_ERROR;
773}
774
775status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700776 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
777 if (!(args.size() == 2 || args.size() == 4)) {
778 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800779 return BAD_VALUE;
780 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700781
782 int userId = 0;
783 if (args.size() == 4 && args[2] == String16("--user")) {
784 userId = atoi(String8(args[3]));
785 }
786
787 uid_t uid;
788 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
789 return BAD_VALUE;
790 }
791
Svet Ganove752a5c2018-01-15 17:14:20 -0800792 if (mUidPolicy->isUidActive(uid)) {
793 return dprintf(out, "active\n");
794 } else {
795 return dprintf(out, "idle\n");
796 }
797}
798
799status_t SensorService::printHelp(int out) {
800 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700801 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
802 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
803 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800804 " help print this message\n");
805}
806
Peng Xu0cc8f802016-04-05 23:46:03 -0700807//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800808void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700809 sensors_event_t const* buffer, const int count) {
810 for (int i=0 ; i<count ; i++) {
811 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700812 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
813 handle = buffer[i].meta_data.sensor;
814 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700815 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700816 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700817 // If this buffer has an event from a one_shot sensor and this connection is registered
818 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700819 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700820 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
821 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800822 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700823 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700824
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700825 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700826 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700827}
828
Peng Xu47e96012016-03-28 17:55:56 -0700829bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000830 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700831
Peng Xueb4d6282015-12-10 18:02:41 -0800832 // each virtual sensor could generate an event per "real" event, that's why we need to size
833 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
834 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700835 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700836 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700837 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700838
Mathias Agopianf001c922010-11-11 17:58:51 -0800839 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700840
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700841 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700842 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700843 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
844 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700845 if(count == DEAD_OBJECT && device.isReconnecting()) {
846 device.reconnect();
847 continue;
848 } else {
849 ALOGE("sensor poll failed (%s)", strerror(-count));
850 break;
851 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700852 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700853
854 // Reset sensors_event_t.flags to zero for all events in the buffer.
855 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700856 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700857 }
Brian Duddie967ce172019-06-10 11:08:27 -0700858 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700859
Aravind Akella9a844cf2014-02-11 18:58:52 -0800860 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
861 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
862 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
863 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
864 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700865 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700866 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700867 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700868 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700869 }
870 }
871
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700872 if (wakeEvents > 0) {
873 if (!mWakeLockAcquired) {
874 setWakeLockAcquiredLocked(true);
875 }
876 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800877 }
Aravind Akella8493b792014-09-08 15:45:47 -0700878 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800879
Mathias Agopianf001c922010-11-11 17:58:51 -0800880 // handle virtual sensors
881 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700882 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700883 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800884 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700885 SensorFusion& fusion(SensorFusion::getInstance());
886 if (fusion.isEnabled()) {
887 for (size_t i=0 ; i<size_t(count) ; i++) {
888 fusion.process(event[i]);
889 }
890 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700891 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700892 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700893 if (count + k >= minBufferSize) {
894 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700895 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700896 count, k, minBufferSize);
897 break;
898 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800899 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700900 sp<SensorInterface> si = mSensors.getInterface(handle);
901 if (si == nullptr) {
902 ALOGE("handle %d is not an valid virtual sensor", handle);
903 continue;
904 }
905
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700906 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700907 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800908 k++;
909 }
910 }
911 }
912 if (k) {
913 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700914 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800915 count += k;
916 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700917 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700918 }
919 }
920 }
921
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700922 // handle backward compatibility for RotationVector sensor
923 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
924 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700925 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700926 // All the 4 components of the quaternion should be available
927 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700928 mSensorEventBuffer[i].data[4] = -1;
929 }
930 }
931 }
932
Brian Duddie967ce172019-06-10 11:08:27 -0700933 // Cache the list of active connections, since we use it in multiple places below but won't
934 // modify it here
935 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
936
Aravind Akella8493b792014-09-08 15:45:47 -0700937 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700938 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
939 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
940 // SensorEventConnection mapped to the corresponding flush_complete_event in
941 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700942 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700943 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
944 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
945 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700946 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700947 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
948 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700949 }
950 }
Peng Xu2576cb62016-01-20 00:22:09 -0800951
952 // handle dynamic sensor meta events, process registration and unregistration of dynamic
953 // sensor based on content of event.
954 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
955 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
956 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
957 const sensor_t& dynamicSensor =
958 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
959 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
960 handle, dynamicSensor.type, dynamicSensor.name);
961
Peng Xu0cc8f802016-04-05 23:46:03 -0700962 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800963 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700964 sensor_t s = dynamicSensor;
965 // make sure the dynamic sensor flag is set
966 s.flags |= DYNAMIC_SENSOR_MASK;
967 // force the handle to be consistent
968 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800969
970 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800971
Peng Xu0cc8f802016-04-05 23:46:03 -0700972 // This will release hold on dynamic sensor meta, so it should be called
973 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700974 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800975 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700976 } else {
977 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
978 }
Peng Xu2576cb62016-01-20 00:22:09 -0800979 } else {
980 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
981 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
982
983 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800984 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800985 ALOGE("Dynamic sensor release error.");
986 }
987
Brian Duddie967ce172019-06-10 11:08:27 -0700988 for (const sp<SensorEventConnection>& connection : activeConnections) {
989 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -0800990 }
991 }
992 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700993 }
994
Aravind Akella9a844cf2014-02-11 18:58:52 -0800995 // Send our events to clients. Check the state of wake lock for each client and release the
996 // lock if none of the clients need it.
997 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -0700998 for (const sp<SensorEventConnection>& connection : activeConnections) {
999 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1000 mMapFlushEventsToConnections);
1001 needsWakeLock |= connection->needsWakeLock();
1002 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
1003 // Early check for one-shot sensors.
1004 if (connection->hasOneShotSensors()) {
1005 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -08001006 }
1007 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001008
Aravind Akella9a844cf2014-02-11 18:58:52 -08001009 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001010 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001011 }
Aravind Akella8493b792014-09-08 15:45:47 -07001012 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001013
Steve Block3c20fbe2012-01-05 23:22:43 +00001014 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001015 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001016 return false;
1017}
1018
Aravind Akella56ae4262014-07-10 16:01:10 -07001019sp<Looper> SensorService::getLooper() const {
1020 return mLooper;
1021}
1022
Aravind Akellab4373ac2014-10-29 17:55:20 -07001023void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001024 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1025 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1026 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001027 }
Brian Duddie967ce172019-06-10 11:08:27 -07001028 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001029}
1030
1031void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1032 if (acquire) {
1033 if (!mWakeLockAcquired) {
1034 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1035 mWakeLockAcquired = true;
1036 }
1037 mLooper->wake();
1038 } else {
1039 if (mWakeLockAcquired) {
1040 release_wake_lock(WAKE_LOCK_NAME);
1041 mWakeLockAcquired = false;
1042 }
1043 }
1044}
1045
Aravind Akellab4373ac2014-10-29 17:55:20 -07001046bool SensorService::isWakeLockAcquired() {
1047 Mutex::Autolock _l(mLock);
1048 return mWakeLockAcquired;
1049}
1050
Aravind Akella56ae4262014-07-10 16:01:10 -07001051bool SensorService::SensorEventAckReceiver::threadLoop() {
1052 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001053 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001054 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001055 bool wakeLockAcquired = mService->isWakeLockAcquired();
1056 int timeout = -1;
1057 if (wakeLockAcquired) timeout = 5000;
1058 int ret = looper->pollOnce(timeout);
1059 if (ret == ALOOPER_POLL_TIMEOUT) {
1060 mService->resetAllWakeLockRefCounts();
1061 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001062 } while(!Thread::exitPending());
1063 return false;
1064}
1065
Aravind Akella9a844cf2014-02-11 18:58:52 -08001066void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001067 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001068 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001069 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1070 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001071 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001072 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001073 }
Peng Xu2576cb62016-01-20 00:22:09 -08001074
Peng Xu6a2d3a02015-12-21 12:00:23 -08001075 auto logger = mRecentEvent.find(buffer[i].sensor);
1076 if (logger != mRecentEvent.end()) {
1077 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001078 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001079 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001080}
1081
Peng Xu47e96012016-03-28 17:55:56 -07001082void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001083 struct compar {
1084 static int cmp(void const* lhs, void const* rhs) {
1085 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1086 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001087 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001088 }
1089 };
1090 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1091}
1092
Mathias Agopian5d270722010-07-19 15:20:39 -07001093String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001094 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001095}
1096
Aravind Akellab4099e72013-10-15 15:43:10 -07001097bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001098 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1099 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001100}
1101
Aravind Akella9a844cf2014-02-11 18:58:52 -08001102bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001103 int handle = event.sensor;
1104 if (event.type == SENSOR_TYPE_META_DATA) {
1105 handle = event.meta_data.sensor;
1106 }
Peng Xu755c4512016-04-07 23:15:14 -07001107 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1108 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001109}
1110
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001111int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1112 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1113 // UUID is not supported for this device.
1114 return 0;
1115 }
1116 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1117 // This sensor can be uniquely identified in the system by
1118 // the combination of its type and name.
1119 return -1;
1120 }
1121
1122 // We have a dynamic sensor.
1123
1124 if (!sHmacGlobalKeyIsValid) {
1125 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1126 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1127 return 0;
1128 }
1129
1130 // We want each app author/publisher to get a different ID, so that the
1131 // same dynamic sensor cannot be tracked across apps by multiple
1132 // authors/publishers. So we use both our UUID and our User ID.
1133 // Note potential confusion:
1134 // UUID => Universally Unique Identifier.
1135 // UID => User Identifier.
1136 // We refrain from using "uid" except as needed by API to try to
1137 // keep this distinction clear.
1138
1139 auto appUserId = IPCThreadState::self()->getCallingUid();
1140 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1141 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1142 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1143
1144 // Now we use our key on our UUID/app combo to get the hash.
1145 uint8_t hash[EVP_MAX_MD_SIZE];
1146 unsigned int hashLen;
1147 if (HMAC(EVP_sha256(),
1148 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1149 uuidAndApp, sizeof(uuidAndApp),
1150 hash, &hashLen) == nullptr) {
1151 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1152 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1153 return 0;
1154 }
1155
1156 int32_t id = 0;
1157 if (hashLen < sizeof(id)) {
1158 // We never expect this case, but out of paranoia, we handle it.
1159 // Our 'id' length is already quite small, we don't want the
1160 // effective length of it to be even smaller.
1161 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1162 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1163 return 0;
1164 }
1165
1166 // This is almost certainly less than all of 'hash', but it's as secure
1167 // as we can be with our current 'id' length.
1168 memcpy(&id, hash, sizeof(id));
1169
1170 // Note at the beginning of the function that we return the values of
1171 // 0 and -1 to represent special cases. As a result, we can't return
1172 // those as dynamic sensor IDs. If we happened to hash to one of those
1173 // values, we change 'id' so we report as a dynamic sensor, and not as
1174 // one of those special cases.
1175 if (id == -1) {
1176 id = -2;
1177 } else if (id == 0) {
1178 id = 1;
1179 }
1180 return id;
1181}
1182
1183void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1184 for (auto &sensor : sensorList) {
1185 int32_t id = getIdFromUuid(sensor.getUuid());
1186 sensor.setId(id);
1187 }
1188}
1189
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001190Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001191 char value[PROPERTY_VALUE_MAX];
1192 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001193 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001194 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001195 Vector<Sensor> accessibleSensorList;
1196 for (size_t i = 0; i < initialSensorList.size(); i++) {
1197 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001198 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001199 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001200 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001201 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001202}
1203
Peng Xu47e96012016-03-28 17:55:56 -07001204Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001205 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001206 mSensors.forEachSensor(
1207 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001208 if (sensor.isDynamicSensor()) {
1209 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1210 accessibleSensorList.add(sensor);
1211 } else {
1212 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1213 sensor.getName().string(),
1214 sensor.getRequiredPermission().string(),
1215 sensor.getRequiredAppOp());
1216 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001217 }
1218 return true;
1219 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001220 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001221 return accessibleSensorList;
1222}
1223
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001224sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001225 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001226 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1227 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001228 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001229 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001230
1231 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001232 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1233 // operating in DI mode.
1234 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001235 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1236 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001237 }
1238
Mathias Agopian5307d172012-09-18 17:02:43 -07001239 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001240 pid_t pid = IPCThreadState::self()->getCallingPid();
1241
1242 String8 connPackageName =
1243 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1244 String16 connOpPackageName =
1245 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001246 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001247 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001248 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001249 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001250 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001251 // Add the associated file descriptor to the Looper for polling whenever there is data to
1252 // be injected.
1253 result->updateLooperRegistration(mLooper);
1254 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001255 return result;
1256}
1257
Aravind Akella841a5922015-06-29 12:37:48 -07001258int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001259 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001260 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001261}
1262
Peng Xue36e3472016-11-03 11:57:10 -07001263sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1264 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1265 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001266 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001267
Michael Groover5e1f60b2018-12-04 22:34:29 -08001268 // No new direct connections are allowed when sensor privacy is enabled
1269 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1270 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1271 return nullptr;
1272 }
1273
Peng Xue36e3472016-11-03 11:57:10 -07001274 struct sensors_direct_mem_t mem = {
1275 .type = type,
1276 .format = format,
1277 .size = size,
1278 .handle = resource,
1279 };
1280 uid_t uid = IPCThreadState::self()->getCallingUid();
1281
1282 if (mem.handle == nullptr) {
1283 ALOGE("Failed to clone resource handle");
1284 return nullptr;
1285 }
1286
1287 // check format
1288 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1289 ALOGE("Direct channel format %d is unsupported!", format);
1290 return nullptr;
1291 }
1292
1293 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001294 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1295 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001296 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001297 return nullptr;
1298 }
1299 }
1300
1301 // check specific to memory type
1302 switch(type) {
1303 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001304 if (resource->numFds < 1) {
1305 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1306 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1307 return nullptr;
1308 }
Peng Xue36e3472016-11-03 11:57:10 -07001309 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001310 if (!ashmem_valid(fd)) {
1311 ALOGE("Supplied Ashmem memory region is invalid");
1312 return nullptr;
1313 }
1314
Peng Xue36e3472016-11-03 11:57:10 -07001315 int size2 = ashmem_get_size_region(fd);
1316 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001317 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001318 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1319 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001320 return nullptr;
1321 }
1322 break;
1323 }
1324 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001325 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001326 break;
1327 default:
1328 ALOGE("Unknown direct connection memory type %d", type);
1329 return nullptr;
1330 }
1331
1332 native_handle_t *clone = native_handle_clone(resource);
1333 if (!clone) {
1334 return nullptr;
1335 }
1336
Brian Duddie967ce172019-06-10 11:08:27 -07001337 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001338 SensorDevice& dev(SensorDevice::getInstance());
1339 int channelHandle = dev.registerDirectChannel(&mem);
1340
1341 if (channelHandle <= 0) {
1342 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1343 } else {
1344 mem.handle = clone;
1345 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1346 }
1347
1348 if (conn == nullptr) {
1349 native_handle_close(clone);
1350 native_handle_delete(clone);
1351 } else {
1352 // add to list of direct connections
1353 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001354 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001355 }
1356 return conn;
1357}
1358
Peng Xudd5c5cb2017-03-16 17:39:43 -07001359int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001360 int32_t handle, int32_t type,
1361 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001362 Mutex::Autolock _l(mLock);
1363
Alexey Polyudov88711e82017-05-23 19:54:04 -07001364 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001365 return PERMISSION_DENIED;
1366 }
1367
1368 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001369 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001370 size_t expectSize = INT32_MAX;
1371 switch (type) {
1372 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1373 isFloat = true;
1374 expectSize = 3;
1375 break;
1376 case AINFO_LOCAL_GRAVITY:
1377 isFloat = true;
1378 expectSize = 1;
1379 break;
1380 case AINFO_DOCK_STATE:
1381 case AINFO_HIGH_PERFORMANCE_MODE:
1382 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1383 isFloat = false;
1384 expectSize = 1;
1385 break;
1386 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001387 // CUSTOM events must only contain float data; it may have variable size
1388 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1389 ints.size() ||
1390 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1391 handle < 0) {
1392 return BAD_VALUE;
1393 }
1394 isFloat = true;
1395 isCustom = true;
1396 expectSize = floats.size();
1397 break;
1398 }
1399
1400 if (!isCustom && handle != -1) {
1401 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001402 }
1403
1404 // three events: first one is begin tag, last one is end tag, the one in the middle
1405 // is the payload.
1406 sensors_event_t event[3];
1407 int64_t timestamp = elapsedRealtimeNano();
1408 for (sensors_event_t* i = event; i < event + 3; i++) {
1409 *i = (sensors_event_t) {
1410 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001411 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001412 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1413 .timestamp = timestamp++,
1414 .additional_info = (additional_info_event_t) {
1415 .serial = 0
1416 }
1417 };
1418 }
1419
1420 event[0].additional_info.type = AINFO_BEGIN;
1421 event[1].additional_info.type = type;
1422 event[2].additional_info.type = AINFO_END;
1423
1424 if (isFloat) {
1425 if (floats.size() != expectSize) {
1426 return BAD_VALUE;
1427 }
1428 for (size_t i = 0; i < expectSize; ++i) {
1429 event[1].additional_info.data_float[i] = floats[i];
1430 }
1431 } else {
1432 if (ints.size() != expectSize) {
1433 return BAD_VALUE;
1434 }
1435 for (size_t i = 0; i < expectSize; ++i) {
1436 event[1].additional_info.data_int32[i] = ints[i];
1437 }
1438 }
1439
1440 SensorDevice& dev(SensorDevice::getInstance());
1441 for (sensors_event_t* i = event; i < event + 3; i++) {
1442 int ret = dev.injectSensorData(i);
1443 if (ret != NO_ERROR) {
1444 return ret;
1445 }
1446 }
1447 return NO_ERROR;
1448}
1449
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001450status_t SensorService::resetToNormalMode() {
1451 Mutex::Autolock _l(mLock);
1452 return resetToNormalModeLocked();
1453}
1454
1455status_t SensorService::resetToNormalModeLocked() {
1456 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001457 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301458 if (err == NO_ERROR) {
1459 mCurrentOperatingMode = NORMAL;
1460 dev.enableAllSensors();
1461 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001462 return err;
1463}
1464
Peng Xu47e96012016-03-28 17:55:56 -07001465void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001466 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001467 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001468 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001469 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001470 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001471 int handle = mActiveSensors.keyAt(i);
1472 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001473 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001474 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1475 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001476 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001477 } else {
1478 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001479 }
Aravind Akella8a969552014-09-28 17:52:41 -07001480 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001481 }
1482 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001483 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001484 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001485 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001486 c, i, handle);
1487
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001488 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001489 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001490 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001491 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001492 delete rec;
1493 size--;
1494 } else {
1495 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001496 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001497 }
Aravind Akella8a969552014-09-28 17:52:41 -07001498 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001499 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001500 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001501 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001502 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001503 }
Peng Xu4f707f82016-09-26 11:28:32 -07001504
Brian Stack793f4642019-04-18 17:21:34 -07001505 {
1506 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1507 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1508 if (iter != sPackageTargetVersion.end()) {
1509 sPackageTargetVersion.erase(iter);
1510 }
1511 }
1512
Peng Xu4f707f82016-09-26 11:28:32 -07001513 SensorDevice& dev(SensorDevice::getInstance());
1514 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001515}
1516
Peng Xue36e3472016-11-03 11:57:10 -07001517void SensorService::cleanupConnection(SensorDirectConnection* c) {
1518 Mutex::Autolock _l(mLock);
1519
1520 SensorDevice& dev(SensorDevice::getInstance());
1521 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001522 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001523}
1524
Peng Xu755c4512016-04-07 23:15:14 -07001525sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001526 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001527}
1528
Mathias Agopianfc328812010-07-14 23:41:37 -07001529status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001530 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001531 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001532 if (mInitCheck != NO_ERROR)
1533 return mInitCheck;
1534
Peng Xu755c4512016-04-07 23:15:14 -07001535 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1536 if (sensor == nullptr ||
1537 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001538 return BAD_VALUE;
1539 }
1540
Brian Duddie967ce172019-06-10 11:08:27 -07001541 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001542 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001543 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001544 return INVALID_OPERATION;
1545 }
1546
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001547 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001548 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001549 rec = new SensorRecord(connection);
1550 mActiveSensors.add(handle, rec);
1551 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001552 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001553 }
Brian Stack26029ee2019-04-22 17:25:49 -07001554
1555 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1556 // the recent event as stale to ensure that the previous event is not sent to a client. This
1557 // ensures on-change events that were generated during a previous sensor activation are not
1558 // erroneously sent to newly connected clients, especially if a second client registers for
1559 // an on-change sensor before the first client receives the updated event. Once an updated
1560 // event is received, the recent events will be marked as current, and any new clients will
1561 // immediately receive the most recent event.
1562 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1563 auto logger = mRecentEvent.find(handle);
1564 if (logger != mRecentEvent.end()) {
1565 logger->second->setLastEventStale();
1566 }
1567 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001568 } else {
1569 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001570 // this sensor is already activated, but we are adding a connection that uses it.
1571 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001572 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001573 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001574 // NOTE: The wake_up flag of this event may get set to
1575 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001576
1577 auto logger = mRecentEvent.find(handle);
1578 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001579 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001580 // Verify that the last sensor event was generated from the current activation
1581 // of the sensor. If not, it is possible for an on-change sensor to receive a
1582 // sensor event that is stale if two clients re-activate the sensor
1583 // simultaneously.
1584 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001585 event.sensor = handle;
1586 if (event.version == sizeof(sensors_event_t)) {
1587 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1588 setWakeLockAcquiredLocked(true);
1589 }
Yi Kong8f313e32018-07-17 14:13:29 -07001590 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001591 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001592 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001593 }
1594 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001595 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001596 }
1597 }
1598 }
1599 }
1600
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -07001601 if (connection->addSensor(handle, samplingPeriodNs, maxBatchReportLatencyNs, reservedFlags)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001602 BatteryService::enableSensor(connection->getUid(), handle);
1603 // the sensor was added (which means it wasn't already there)
1604 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001605 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001606 } else {
1607 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1608 handle, connection.get());
1609 }
1610
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301611 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001612 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301613 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1614 samplingPeriodNs = maxDelayNs;
1615 }
1616
Aravind Akella724d91d2013-06-27 12:04:23 -07001617 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1618 if (samplingPeriodNs < minDelayNs) {
1619 samplingPeriodNs = minDelayNs;
1620 }
1621
Aravind Akella6c2664a2014-08-13 12:24:50 -07001622 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1623 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001624 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1625
Aravind Akella4949c502015-02-11 15:54:35 -08001626 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001627 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001628
Peng Xu20483c42015-10-26 15:14:43 -07001629 // Call flush() before calling activate() on the sensor. Wait for a first
1630 // flush complete event before sending events on this connection. Ignore
1631 // one-shot sensors which don't support flush(). Ignore on-change sensors
1632 // to maintain the on-change logic (any on-change events except the initial
1633 // one should be trigger by a change in value). Also if this sensor isn't
1634 // already active, don't call flush().
1635 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001636 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001637 rec->getNumConnections() > 1) {
1638 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001639 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001640 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001641 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001642 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001643 } else {
1644 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001645 }
1646 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001647
1648 if (err == NO_ERROR) {
1649 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1650 err = sensor->activate(connection.get(), true);
1651 }
1652
Aravind Akella8a969552014-09-28 17:52:41 -07001653 if (err == NO_ERROR) {
1654 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001655
Brian Stack240d1d62019-05-17 09:49:39 -07001656 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1657 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001658 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1659 }
1660
Peng Xu51224682017-03-10 16:57:27 -08001661 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1662 SensorRegistrationInfo(handle, connection->getPackageName(),
1663 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001664 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001665 }
1666
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001667 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001668 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001669 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001670 }
1671 return err;
1672}
1673
Peng Xu47e96012016-03-28 17:55:56 -07001674status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001675 if (mInitCheck != NO_ERROR)
1676 return mInitCheck;
1677
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001678 Mutex::Autolock _l(mLock);
1679 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001680 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001681 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1682 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001683
1684 }
1685 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001686 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1687 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001688 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001689 }
1690 return err;
1691}
1692
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001693status_t SensorService::cleanupWithoutDisable(
1694 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001695 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001696 return cleanupWithoutDisableLocked(connection, handle);
1697}
1698
1699status_t SensorService::cleanupWithoutDisableLocked(
1700 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001701 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001702 if (rec) {
1703 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001704 if (connection->removeSensor(handle)) {
1705 BatteryService::disableSensor(connection->getUid(), handle);
1706 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001707 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001708 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001709 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001710 }
1711 // see if this sensor becomes inactive
1712 if (rec->removeConnection(connection)) {
1713 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001714 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001715 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001716 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001717 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001718 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001719 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001720}
1721
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001722status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001723 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001724 if (mInitCheck != NO_ERROR)
1725 return mInitCheck;
1726
Peng Xu755c4512016-04-07 23:15:14 -07001727 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1728 if (sensor == nullptr ||
1729 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001730 return BAD_VALUE;
1731 }
1732
Mathias Agopian1cd70002010-07-21 15:59:50 -07001733 if (ns < 0)
1734 return BAD_VALUE;
1735
Mathias Agopian62569ec2011-11-07 21:21:47 -08001736 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1737 if (ns < minDelayNs) {
1738 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001739 }
1740
Mathias Agopianf001c922010-11-11 17:58:51 -08001741 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001742}
1743
Svetoslavb412f6e2015-04-29 16:50:41 -07001744status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1745 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001746 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001747 SensorDevice& dev(SensorDevice::getInstance());
1748 const int halVersion = dev.getHalDeviceVersion();
1749 status_t err(NO_ERROR);
1750 Mutex::Autolock _l(mLock);
1751 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07001752 for (int handle : connection->getActiveSensorHandles()) {
Peng Xu755c4512016-04-07 23:15:14 -07001753 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1754 if (sensor == nullptr) {
1755 continue;
1756 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001757 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1758 ALOGE("flush called on a one-shot sensor");
1759 err = INVALID_OPERATION;
1760 continue;
1761 }
Aravind Akella8493b792014-09-08 15:45:47 -07001762 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001763 // For older devices just increment pending flush count which will send a trivial
1764 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001765 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001766 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001767 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1768 err = INVALID_OPERATION;
1769 continue;
1770 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001771 status_t err_flush = sensor->flush(connection.get(), handle);
1772 if (err_flush == NO_ERROR) {
1773 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001774 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001775 }
1776 err = (err_flush != NO_ERROR) ? err_flush : err;
1777 }
Aravind Akella70018042014-04-07 22:52:37 +00001778 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07001779 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001780}
Aravind Akella70018042014-04-07 22:52:37 +00001781
Svetoslavb412f6e2015-04-29 16:50:41 -07001782bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1783 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001784 // Check if a permission is required for this sensor
1785 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001786 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001787 }
1788
Brian Stack793f4642019-04-18 17:21:34 -07001789 const int32_t opCode = sensor.getRequiredAppOp();
1790 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1791 IPCThreadState::self()->getCallingUid(), opPackageName);
Brian Stack6a700f92019-05-08 17:02:53 -07001792 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
Brian Stack793f4642019-04-18 17:21:34 -07001793
Brian Stack793f4642019-04-18 17:21:34 -07001794 bool canAccess = false;
Brian Stack6a700f92019-05-08 17:02:53 -07001795 if (hasPermissionForSensor(sensor)) {
1796 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1797 if (opCode < 0 || appOpAllowed) {
Brian Stack793f4642019-04-18 17:21:34 -07001798 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001799 }
1800 } else if (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1801 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR) {
1802 int targetSdkVersion = getTargetSdkVersion(opPackageName);
1803 // Allow access to the sensor if the application targets pre-Q, which is before the
1804 // requirement to hold the AR permission to access Step Counter and Step Detector events
1805 // was introduced, and the user hasn't revoked the app op.
1806 //
1807 // Verifying the app op is required to ensure that the user hasn't revoked the necessary
1808 // permissions to access the Step Detector and Step Counter when the application targets
1809 // pre-Q. Without this check, if the user revokes the pre-Q install-time GMS Core AR
1810 // permission, the app would still be able to receive Step Counter and Step Detector events.
1811 if (appOpAllowed &&
1812 targetSdkVersion > 0 &&
1813 targetSdkVersion <= __ANDROID_API_P__) {
1814 canAccess = true;
Brian Stack793f4642019-04-18 17:21:34 -07001815 }
1816 }
1817
1818 if (canAccess) {
1819 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1820 } else {
1821 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1822 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1823 }
1824
1825 return canAccess;
1826}
1827
1828bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001829 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001830 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001831
1832 // Runtime permissions can't use the cache as they may change.
1833 if (sensor.isRequiredPermissionRuntime()) {
1834 hasPermission = checkPermission(String16(requiredPermission),
1835 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001836 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001837 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1838 }
Brian Stack793f4642019-04-18 17:21:34 -07001839 return hasPermission;
1840}
Svetoslavb412f6e2015-04-29 16:50:41 -07001841
Brian Stack793f4642019-04-18 17:21:34 -07001842int SensorService::getTargetSdkVersion(const String16& opPackageName) {
1843 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1844 int targetSdkVersion = -1;
1845 auto entry = sPackageTargetVersion.find(opPackageName);
1846 if (entry != sPackageTargetVersion.end()) {
1847 targetSdkVersion = entry->second;
1848 } else {
1849 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1850 if (binder != nullptr) {
1851 sp<content::pm::IPackageManagerNative> packageManager =
1852 interface_cast<content::pm::IPackageManagerNative>(binder);
1853 if (packageManager != nullptr) {
1854 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1855 opPackageName, &targetSdkVersion);
1856 if (!status.isOk()) {
1857 targetSdkVersion = -1;
1858 }
1859 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001860 }
Brian Stack793f4642019-04-18 17:21:34 -07001861 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001862 }
Brian Stack793f4642019-04-18 17:21:34 -07001863 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001864}
1865
Aravind Akella9a844cf2014-02-11 18:58:52 -08001866void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001867 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1868 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001869}
1870
Brian Duddie967ce172019-06-10 11:08:27 -07001871void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001872 if (!mWakeLockAcquired) {
1873 return;
1874 }
1875 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001876 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1877 if (connection->needsWakeLock()) {
1878 releaseLock = false;
1879 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001880 }
1881 }
1882 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001883 setWakeLockAcquiredLocked(false);
1884 }
1885}
1886
1887void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1888 Mutex::Autolock _l(mLock);
1889 connection->writeToSocketFromCache();
1890 if (connection->needsWakeLock()) {
1891 setWakeLockAcquiredLocked(true);
1892 }
1893}
1894
Aravind Akella4949c502015-02-11 15:54:35 -08001895bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001896 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001897}
1898
Brian Stack5180e462019-03-08 17:15:19 -08001899bool SensorService::isOperationPermitted(const String16& opPackageName) {
Peng Xue36e3472016-11-03 11:57:10 -07001900 Mutex::Autolock _l(mLock);
Brian Stack5180e462019-03-08 17:15:19 -08001901 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001902 String8 package(opPackageName);
Brian Stack5180e462019-03-08 17:15:19 -08001903 return isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001904 }
Brian Stack5180e462019-03-08 17:15:19 -08001905 return true;
Peng Xue36e3472016-11-03 11:57:10 -07001906}
1907
Svet Ganove752a5c2018-01-15 17:14:20 -08001908void SensorService::UidPolicy::registerSelf() {
1909 ActivityManager am;
1910 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1911 | ActivityManager::UID_OBSERVER_IDLE
1912 | ActivityManager::UID_OBSERVER_ACTIVE,
1913 ActivityManager::PROCESS_STATE_UNKNOWN,
1914 String16("android"));
1915}
1916
1917void SensorService::UidPolicy::unregisterSelf() {
1918 ActivityManager am;
1919 am.unregisterUidObserver(this);
1920}
1921
1922void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1923 onUidIdle(uid, disabled);
1924}
1925
1926void SensorService::UidPolicy::onUidActive(uid_t uid) {
1927 {
1928 Mutex::Autolock _l(mUidLock);
1929 mActiveUids.insert(uid);
1930 }
1931 sp<SensorService> service = mService.promote();
1932 if (service != nullptr) {
1933 service->setSensorAccess(uid, true);
1934 }
1935}
1936
1937void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1938 bool deleted = false;
1939 {
1940 Mutex::Autolock _l(mUidLock);
1941 if (mActiveUids.erase(uid) > 0) {
1942 deleted = true;
1943 }
1944 }
1945 if (deleted) {
1946 sp<SensorService> service = mService.promote();
1947 if (service != nullptr) {
1948 service->setSensorAccess(uid, false);
1949 }
1950 }
1951}
1952
1953void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1954 updateOverrideUid(uid, active, true);
1955}
1956
1957void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1958 updateOverrideUid(uid, false, false);
1959}
1960
1961void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1962 bool wasActive = false;
1963 bool isActive = false;
1964 {
1965 Mutex::Autolock _l(mUidLock);
1966 wasActive = isUidActiveLocked(uid);
1967 mOverrideUids.erase(uid);
1968 if (insert) {
1969 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1970 }
1971 isActive = isUidActiveLocked(uid);
1972 }
1973 if (wasActive != isActive) {
1974 sp<SensorService> service = mService.promote();
1975 if (service != nullptr) {
1976 service->setSensorAccess(uid, isActive);
1977 }
1978 }
1979}
1980
1981bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1982 // Non-app UIDs are considered always active
1983 if (uid < FIRST_APPLICATION_UID) {
1984 return true;
1985 }
1986 Mutex::Autolock _l(mUidLock);
1987 return isUidActiveLocked(uid);
1988}
1989
1990bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1991 // Non-app UIDs are considered always active
1992 if (uid < FIRST_APPLICATION_UID) {
1993 return true;
1994 }
1995 auto it = mOverrideUids.find(uid);
1996 if (it != mOverrideUids.end()) {
1997 return it->second;
1998 }
1999 return mActiveUids.find(uid) != mActiveUids.end();
2000}
2001
Michael Groover5e1f60b2018-12-04 22:34:29 -08002002void SensorService::SensorPrivacyPolicy::registerSelf() {
2003 SensorPrivacyManager spm;
2004 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2005 spm.addSensorPrivacyListener(this);
2006}
2007
2008void SensorService::SensorPrivacyPolicy::unregisterSelf() {
2009 SensorPrivacyManager spm;
2010 spm.removeSensorPrivacyListener(this);
2011}
2012
2013bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2014 return mSensorPrivacyEnabled;
2015}
2016
2017binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2018 mSensorPrivacyEnabled = enabled;
2019 sp<SensorService> service = mService.promote();
2020 if (service != nullptr) {
2021 if (enabled) {
2022 service->disableAllSensors();
2023 } else {
2024 service->enableAllSensors();
2025 }
2026 }
2027 return binder::Status::ok();
2028}
Brian Duddie967ce172019-06-10 11:08:27 -07002029
2030SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2031 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2032 : mConnectionHolder(holder), mAutolock(mutex) {}
2033
2034template<typename ConnectionType>
2035const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2036 const SortedVector<wp<ConnectionType>>& connectionList,
2037 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2038 referenceHolder->emplace_back();
2039 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2040 for (const wp<ConnectionType>& weakConnection : connectionList){
2041 sp<ConnectionType> connection = weakConnection.promote();
2042 if (connection != nullptr) {
2043 connections.push_back(std::move(connection));
2044 }
2045 }
2046 return connections;
2047}
2048
2049const std::vector<sp<SensorService::SensorEventConnection>>&
2050 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2051 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2052 &mReferencedActiveConnections);
2053}
2054
2055const std::vector<sp<SensorService::SensorDirectConnection>>&
2056 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2057 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2058 &mReferencedDirectConnections);
2059}
2060
2061void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2062 const sp<SensorService::SensorEventConnection>& connection) {
2063 if (mActiveConnections.indexOf(connection) < 0) {
2064 mActiveConnections.add(connection);
2065 }
2066}
2067
2068void SensorService::SensorConnectionHolder::removeEventConnection(
2069 const wp<SensorService::SensorEventConnection>& connection) {
2070 mActiveConnections.remove(connection);
2071}
2072
2073void SensorService::SensorConnectionHolder::addDirectConnection(
2074 const sp<SensorService::SensorDirectConnection>& connection) {
2075 mDirectConnections.add(connection);
2076}
2077
2078void SensorService::SensorConnectionHolder::removeDirectConnection(
2079 const wp<SensorService::SensorDirectConnection>& connection) {
2080 mDirectConnections.remove(connection);
2081}
2082
2083SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2084 return ConnectionSafeAutolock(*this, mutex);
2085}
2086
2087} // namespace android