blob: a5dafd59a2611d2fc821a43fc8308dd7f2e86e24 [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
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700302void SensorService::onUidStateChanged(uid_t uid, UidState state) {
303 SensorDevice& dev(SensorDevice::getInstance());
304
Brian Duddie967ce172019-06-10 11:08:27 -0700305 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700306 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
Brian Duddie967ce172019-06-10 11:08:27 -0700307 if (conn->getUid() == uid) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700308 dev.setUidStateForConnection(conn.get(), state);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700309 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700310 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700311}
312
Peng Xu0cc8f802016-04-05 23:46:03 -0700313const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
314 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800315 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700316 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700317 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700318 return s->getSensor();
319 } else {
320 return mSensors.getNonSensor();
321 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800322}
323
Peng Xu6a2d3a02015-12-21 12:00:23 -0800324const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700325 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800326}
327
Peng Xu6a2d3a02015-12-21 12:00:23 -0800328bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700329 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800330
331 const auto i = mRecentEvent.find(handle);
332 if (i != mRecentEvent.end()) {
333 delete i->second;
334 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800335 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700336 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800337}
338
Peng Xu0cc8f802016-04-05 23:46:03 -0700339const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
340 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700341}
342
Peng Xu47e96012016-03-28 17:55:56 -0700343SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800344 for (auto && entry : mRecentEvent) {
345 delete entry.second;
346 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800347 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800348 mSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700349}
350
351status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700352 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700353 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800354 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700355 IPCThreadState::self()->getCallingPid(),
356 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700357 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700358 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700359 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800360 return INVALID_OPERATION;
361 }
Brian Duddie967ce172019-06-10 11:08:27 -0700362 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800363 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700364 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700365 // If already in restricted mode. Ignore.
366 if (mCurrentOperatingMode == RESTRICTED) {
367 return status_t(NO_ERROR);
368 }
369 // If in any mode other than normal, ignore.
370 if (mCurrentOperatingMode != NORMAL) {
371 return INVALID_OPERATION;
372 }
Peng Xue36e3472016-11-03 11:57:10 -0700373
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700374 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800375 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700376 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700377 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700378 return status_t(NO_ERROR);
379 } else if (args.size() == 1 && args[0] == String16("enable")) {
380 // If currently in restricted mode, reset back to NORMAL mode else ignore.
381 if (mCurrentOperatingMode == RESTRICTED) {
382 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800383 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700384 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700385 }
Aravind Akella841a5922015-06-29 12:37:48 -0700386 if (mCurrentOperatingMode == DATA_INJECTION) {
387 resetToNormalModeLocked();
388 }
389 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700390 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700391 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
392 if (mCurrentOperatingMode == NORMAL) {
393 dev.disableAllSensors();
394 status_t err = dev.setMode(DATA_INJECTION);
395 if (err == NO_ERROR) {
396 mCurrentOperatingMode = DATA_INJECTION;
397 } else {
398 // Re-enable sensors.
399 dev.enableAllSensors();
400 }
401 mWhiteListedPackage.setTo(String8(args[1]));
402 return NO_ERROR;
403 } else if (mCurrentOperatingMode == DATA_INJECTION) {
404 // Already in DATA_INJECTION mode. Treat this as a no_op.
405 return NO_ERROR;
406 } else {
407 // Transition to data injection mode supported only from NORMAL mode.
408 return INVALID_OPERATION;
409 }
Mike Ma24743862020-01-29 00:36:55 -0800410 } else if (args.size() == 1 && args[0] == String16("--proto")) {
411 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700412 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700413 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700414 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700415 } else {
416 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700417 //
Brian Stack51498e62018-10-03 10:52:21 -0700418 timespec curTime;
419 clock_gettime(CLOCK_REALTIME, &curTime);
420 struct tm* timeinfo = localtime(&(curTime.tv_sec));
421 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
422 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800423 result.append("Sensor Device:\n");
424 result.append(SensorDevice::getInstance().dump().c_str());
425
426 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700427 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700428
Peng Xu6a2d3a02015-12-21 12:00:23 -0800429 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700430 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700431
Peng Xu0cc8f802016-04-05 23:46:03 -0700432 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800433 for (auto&& i : mRecentEvent) {
434 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700435 if (!i.second->isEmpty()) {
436 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
437 i.second->setFormat("normal");
438 } else {
439 i.second->setFormat("mask_data");
440 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800441 // if there is events and sensor does not need special permission.
442 result.appendFormat("%s: ", s->getSensor().getName().string());
443 result.append(i.second->dump().c_str());
444 }
445 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700446
Aravind Akella444f2672015-05-07 12:40:52 -0700447 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700448 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700449 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
450 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700451 if (dev.isSensorActive(handle)) {
452 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
453 getSensorName(handle).string(),
454 handle,
455 mActiveSensors.valueAt(i)->getNumConnections());
456 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700457 }
458
Andreas Gamped4036b62015-07-28 13:49:04 -0700459 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700460 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700461 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
462 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700463 result.appendFormat("Mode :");
464 switch(mCurrentOperatingMode) {
465 case NORMAL:
466 result.appendFormat(" NORMAL\n");
467 break;
468 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700469 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700470 break;
471 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700472 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700473 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800474 result.appendFormat("Sensor Privacy: %s\n",
475 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700476
Brian Duddie967ce172019-06-10 11:08:27 -0700477 const auto& activeConnections = connLock.getActiveConnections();
478 result.appendFormat("%zd active connections\n", activeConnections.size());
479 for (size_t i=0 ; i < activeConnections.size() ; i++) {
480 result.appendFormat("Connection Number: %zu \n", i);
481 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700482 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700483
Brian Duddie967ce172019-06-10 11:08:27 -0700484 const auto& directConnections = connLock.getDirectConnections();
485 result.appendFormat("%zd direct connections\n", directConnections.size());
486 for (size_t i = 0 ; i < directConnections.size() ; i++) {
487 result.appendFormat("Direct connection %zu:\n", i);
488 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700489 }
490
Aravind Akella18d6d512015-06-18 14:18:28 -0700491 result.appendFormat("Previous Registrations:\n");
492 // Log in the reverse chronological order.
493 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
494 SENSOR_REGISTRATIONS_BUF_SIZE;
495 const int startIndex = currentIndex;
496 do {
497 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
498 if (SensorRegistrationInfo::isSentinel(reg_info)) {
499 // Ignore sentinel, proceed to next item.
500 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
501 SENSOR_REGISTRATIONS_BUF_SIZE;
502 continue;
503 }
Peng Xu51224682017-03-10 16:57:27 -0800504 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700505 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
506 SENSOR_REGISTRATIONS_BUF_SIZE;
507 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700508 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700509 }
510 write(fd, result.string(), result.size());
511 return NO_ERROR;
512}
513
Mike Ma24743862020-01-29 00:36:55 -0800514/**
515 * Dump debugging information as android.service.SensorServiceProto protobuf message using
516 * ProtoOutputStream.
517 *
518 * See proto definition and some notes about ProtoOutputStream in
519 * frameworks/base/core/proto/android/service/sensor_service.proto
520 */
521status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
522 using namespace service::SensorServiceProto;
523 util::ProtoOutputStream proto;
Mike Ma285aac12020-02-07 12:29:46 -0800524 proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
525 if (!mSensors.hasAnySensor()) {
526 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
527 }
Mike Ma24743862020-01-29 00:36:55 -0800528 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
529
530 timespec curTime;
531 clock_gettime(CLOCK_REALTIME, &curTime);
532 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
533
534 // Write SensorDeviceProto
535 uint64_t token = proto.start(SENSOR_DEVICE);
536 SensorDevice::getInstance().dump(&proto);
537 proto.end(token);
538
539 // Write SensorListProto
540 token = proto.start(SENSORS);
541 mSensors.dump(&proto);
542 proto.end(token);
543
544 // Write SensorFusionProto
545 token = proto.start(FUSION_STATE);
546 SensorFusion::getInstance().dump(&proto);
547 proto.end(token);
548
549 // Write SensorEventsProto
550 token = proto.start(SENSOR_EVENTS);
551 for (auto&& i : mRecentEvent) {
552 sp<SensorInterface> s = mSensors.getInterface(i.first);
553 if (!i.second->isEmpty()) {
554 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
555 "normal" : "mask_data");
556 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
557 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
558 std::string(s->getSensor().getName().string()));
559 i.second->dump(&proto);
560 proto.end(mToken);
561 }
562 }
563 proto.end(token);
564
565 // Write ActiveSensorProto
566 SensorDevice& dev = SensorDevice::getInstance();
567 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
568 int handle = mActiveSensors.keyAt(i);
569 if (dev.isSensorActive(handle)) {
570 token = proto.start(ACTIVE_SENSORS);
571 proto.write(service::ActiveSensorProto::NAME,
572 std::string(getSensorName(handle).string()));
573 proto.write(service::ActiveSensorProto::HANDLE, handle);
574 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
575 int(mActiveSensors.valueAt(i)->getNumConnections()));
576 proto.end(token);
577 }
578 }
579
580 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
581 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
582 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
583
584 switch(mCurrentOperatingMode) {
585 case NORMAL:
586 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
587 break;
588 case RESTRICTED:
589 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
590 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
591 break;
592 case DATA_INJECTION:
593 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
594 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
595 break;
596 default:
597 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
598 }
599 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
600
601 // Write repeated SensorEventConnectionProto
602 const auto& activeConnections = connLock->getActiveConnections();
603 for (size_t i = 0; i < activeConnections.size(); i++) {
604 token = proto.start(ACTIVE_CONNECTIONS);
605 activeConnections[i]->dump(&proto);
606 proto.end(token);
607 }
608
609 // Write repeated SensorDirectConnectionProto
610 const auto& directConnections = connLock->getDirectConnections();
611 for (size_t i = 0 ; i < directConnections.size() ; i++) {
612 token = proto.start(DIRECT_CONNECTIONS);
613 directConnections[i]->dump(&proto);
614 proto.end(token);
615 }
616
617 // Write repeated SensorRegistrationInfoProto
618 const int startIndex = mNextSensorRegIndex;
619 int curr = startIndex;
620 do {
621 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
622 if (SensorRegistrationInfo::isSentinel(reg_info)) {
623 // Ignore sentinel, proceed to next item.
624 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
625 continue;
626 }
627 token = proto.start(PREVIOUS_REGISTRATIONS);
628 reg_info.dump(&proto);
629 proto.end(token);
630 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
631 } while (startIndex != curr);
632
633 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
634}
635
Michael Groover5e1f60b2018-12-04 22:34:29 -0800636void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700637 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
638 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800639}
640
Brian Duddie967ce172019-06-10 11:08:27 -0700641void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800642 SensorDevice& dev(SensorDevice::getInstance());
Brian Duddie967ce172019-06-10 11:08:27 -0700643 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
Arthur Ishiguroc8ad44b2020-04-13 08:04:47 -0700644 connection->stopAll(true /* backupRecord */);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800645 }
646 dev.disableAllSensors();
647 // Clear all pending flush connections for all active sensors. If one of the active
648 // connections has called flush() and the underlying sensor has been disabled before a
649 // flush complete event is returned, we need to remove the connection from this queue.
650 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
651 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
652 }
653}
654
655void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700656 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
657 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800658}
659
Brian Duddie967ce172019-06-10 11:08:27 -0700660void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800661 // sensors should only be enabled if the operating state is not restricted and sensor
662 // privacy is not enabled.
663 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
664 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
665 mCurrentOperatingMode,
666 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
667 return;
668 }
669 SensorDevice& dev(SensorDevice::getInstance());
670 dev.enableAllSensors();
Brian Duddie967ce172019-06-10 11:08:27 -0700671 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
Arthur Ishiguroc8ad44b2020-04-13 08:04:47 -0700672 connection->recoverAll();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800673 }
674}
675
Brian Duddie967ce172019-06-10 11:08:27 -0700676
Svet Ganove752a5c2018-01-15 17:14:20 -0800677// NOTE: This is a remote API - make sure all args are validated
678status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
679 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
680 return PERMISSION_DENIED;
681 }
682 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
683 return BAD_VALUE;
684 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700685 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800686 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700687 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800688 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700689 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800690 return handleGetUidState(args, out, err);
691 } else if (args.size() == 1 && args[0] == String16("help")) {
692 printHelp(out);
693 return NO_ERROR;
694 }
695 printHelp(err);
696 return BAD_VALUE;
697}
698
Tanmay Patild33a1822019-04-11 18:38:55 -0700699static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800700 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700701 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800702 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700703 ALOGE("Unknown package: '%s'", String8(packageName).string());
704 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800705 return BAD_VALUE;
706 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700707
708 if (userId < 0) {
709 ALOGE("Invalid user: %d", userId);
710 dprintf(err, "Invalid user: %d\n", userId);
711 return BAD_VALUE;
712 }
713
714 uid = multiuser_get_uid(userId, uid);
715 return NO_ERROR;
716}
717
718status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
719 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
720 if (!(args.size() == 3 || args.size() == 5)) {
721 printHelp(err);
722 return BAD_VALUE;
723 }
724
Svet Ganove752a5c2018-01-15 17:14:20 -0800725 bool active = false;
726 if (args[2] == String16("active")) {
727 active = true;
728 } else if ((args[2] != String16("idle"))) {
729 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
730 return BAD_VALUE;
731 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700732
733 int userId = 0;
734 if (args.size() == 5 && args[3] == String16("--user")) {
735 userId = atoi(String8(args[4]));
736 }
737
738 uid_t uid;
739 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
740 return BAD_VALUE;
741 }
742
Svet Ganove752a5c2018-01-15 17:14:20 -0800743 mUidPolicy->addOverrideUid(uid, active);
744 return NO_ERROR;
745}
746
747status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700748 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
749 if (!(args.size() == 2 || args.size() == 4)) {
750 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800751 return BAD_VALUE;
752 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700753
754 int userId = 0;
755 if (args.size() == 4 && args[2] == String16("--user")) {
756 userId = atoi(String8(args[3]));
757 }
758
759 uid_t uid;
760 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
761 return BAD_VALUE;
762 }
763
Svet Ganove752a5c2018-01-15 17:14:20 -0800764 mUidPolicy->removeOverrideUid(uid);
765 return NO_ERROR;
766}
767
768status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700769 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
770 if (!(args.size() == 2 || args.size() == 4)) {
771 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800772 return BAD_VALUE;
773 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700774
775 int userId = 0;
776 if (args.size() == 4 && args[2] == String16("--user")) {
777 userId = atoi(String8(args[3]));
778 }
779
780 uid_t uid;
781 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
782 return BAD_VALUE;
783 }
784
Svet Ganove752a5c2018-01-15 17:14:20 -0800785 if (mUidPolicy->isUidActive(uid)) {
786 return dprintf(out, "active\n");
787 } else {
788 return dprintf(out, "idle\n");
789 }
790}
791
792status_t SensorService::printHelp(int out) {
793 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700794 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
795 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
796 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800797 " help print this message\n");
798}
799
Peng Xu0cc8f802016-04-05 23:46:03 -0700800//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800801void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700802 sensors_event_t const* buffer, const int count) {
803 for (int i=0 ; i<count ; i++) {
804 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700805 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
806 handle = buffer[i].meta_data.sensor;
807 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700808 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700809 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700810 // If this buffer has an event from a one_shot sensor and this connection is registered
811 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700812 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700813 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
814 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800815 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700816 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700817
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700818 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700819 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700820}
821
Peng Xu47e96012016-03-28 17:55:56 -0700822bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000823 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700824
Peng Xueb4d6282015-12-10 18:02:41 -0800825 // each virtual sensor could generate an event per "real" event, that's why we need to size
826 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
827 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700828 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700829 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700830 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700831
Mathias Agopianf001c922010-11-11 17:58:51 -0800832 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700833
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700834 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700835 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700836 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
837 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700838 if(count == DEAD_OBJECT && device.isReconnecting()) {
839 device.reconnect();
840 continue;
841 } else {
842 ALOGE("sensor poll failed (%s)", strerror(-count));
843 break;
844 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700845 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700846
847 // Reset sensors_event_t.flags to zero for all events in the buffer.
848 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700849 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700850 }
Brian Duddie967ce172019-06-10 11:08:27 -0700851 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700852
Aravind Akella9a844cf2014-02-11 18:58:52 -0800853 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
854 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
855 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
856 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
857 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700858 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700859 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700860 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700861 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700862 }
863 }
864
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700865 if (wakeEvents > 0) {
866 if (!mWakeLockAcquired) {
867 setWakeLockAcquiredLocked(true);
868 }
869 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800870 }
Aravind Akella8493b792014-09-08 15:45:47 -0700871 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800872
Mathias Agopianf001c922010-11-11 17:58:51 -0800873 // handle virtual sensors
874 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700875 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700876 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800877 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700878 SensorFusion& fusion(SensorFusion::getInstance());
879 if (fusion.isEnabled()) {
880 for (size_t i=0 ; i<size_t(count) ; i++) {
881 fusion.process(event[i]);
882 }
883 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700884 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700885 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700886 if (count + k >= minBufferSize) {
887 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700888 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700889 count, k, minBufferSize);
890 break;
891 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800892 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700893 sp<SensorInterface> si = mSensors.getInterface(handle);
894 if (si == nullptr) {
895 ALOGE("handle %d is not an valid virtual sensor", handle);
896 continue;
897 }
898
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700899 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700900 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800901 k++;
902 }
903 }
904 }
905 if (k) {
906 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700907 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800908 count += k;
909 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700910 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700911 }
912 }
913 }
914
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700915 // handle backward compatibility for RotationVector sensor
916 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
917 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700918 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700919 // All the 4 components of the quaternion should be available
920 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700921 mSensorEventBuffer[i].data[4] = -1;
922 }
923 }
924 }
925
Brian Duddie967ce172019-06-10 11:08:27 -0700926 // Cache the list of active connections, since we use it in multiple places below but won't
927 // modify it here
928 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
929
Aravind Akella8493b792014-09-08 15:45:47 -0700930 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700931 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
932 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
933 // SensorEventConnection mapped to the corresponding flush_complete_event in
934 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700935 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700936 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
937 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
938 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700939 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700940 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
941 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700942 }
943 }
Peng Xu2576cb62016-01-20 00:22:09 -0800944
945 // handle dynamic sensor meta events, process registration and unregistration of dynamic
946 // sensor based on content of event.
947 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
948 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
949 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
950 const sensor_t& dynamicSensor =
951 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
952 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
953 handle, dynamicSensor.type, dynamicSensor.name);
954
Peng Xu0cc8f802016-04-05 23:46:03 -0700955 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800956 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700957 sensor_t s = dynamicSensor;
958 // make sure the dynamic sensor flag is set
959 s.flags |= DYNAMIC_SENSOR_MASK;
960 // force the handle to be consistent
961 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800962
963 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800964
Peng Xu0cc8f802016-04-05 23:46:03 -0700965 // This will release hold on dynamic sensor meta, so it should be called
966 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700967 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800968 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700969 } else {
970 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
971 }
Peng Xu2576cb62016-01-20 00:22:09 -0800972 } else {
973 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
974 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
975
976 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800977 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800978 ALOGE("Dynamic sensor release error.");
979 }
980
Brian Duddie967ce172019-06-10 11:08:27 -0700981 for (const sp<SensorEventConnection>& connection : activeConnections) {
982 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -0800983 }
984 }
985 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700986 }
987
Aravind Akella9a844cf2014-02-11 18:58:52 -0800988 // Send our events to clients. Check the state of wake lock for each client and release the
989 // lock if none of the clients need it.
990 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -0700991 for (const sp<SensorEventConnection>& connection : activeConnections) {
992 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
993 mMapFlushEventsToConnections);
994 needsWakeLock |= connection->needsWakeLock();
995 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
996 // Early check for one-shot sensors.
997 if (connection->hasOneShotSensors()) {
998 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -0800999 }
1000 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001001
Aravind Akella9a844cf2014-02-11 18:58:52 -08001002 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001003 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001004 }
Aravind Akella8493b792014-09-08 15:45:47 -07001005 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001006
Steve Block3c20fbe2012-01-05 23:22:43 +00001007 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001008 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001009 return false;
1010}
1011
Aravind Akella56ae4262014-07-10 16:01:10 -07001012sp<Looper> SensorService::getLooper() const {
1013 return mLooper;
1014}
1015
Aravind Akellab4373ac2014-10-29 17:55:20 -07001016void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001017 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1018 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1019 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001020 }
Brian Duddie967ce172019-06-10 11:08:27 -07001021 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001022}
1023
1024void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1025 if (acquire) {
1026 if (!mWakeLockAcquired) {
1027 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1028 mWakeLockAcquired = true;
1029 }
1030 mLooper->wake();
1031 } else {
1032 if (mWakeLockAcquired) {
1033 release_wake_lock(WAKE_LOCK_NAME);
1034 mWakeLockAcquired = false;
1035 }
1036 }
1037}
1038
Aravind Akellab4373ac2014-10-29 17:55:20 -07001039bool SensorService::isWakeLockAcquired() {
1040 Mutex::Autolock _l(mLock);
1041 return mWakeLockAcquired;
1042}
1043
Aravind Akella56ae4262014-07-10 16:01:10 -07001044bool SensorService::SensorEventAckReceiver::threadLoop() {
1045 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001046 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001047 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001048 bool wakeLockAcquired = mService->isWakeLockAcquired();
1049 int timeout = -1;
1050 if (wakeLockAcquired) timeout = 5000;
1051 int ret = looper->pollOnce(timeout);
1052 if (ret == ALOOPER_POLL_TIMEOUT) {
1053 mService->resetAllWakeLockRefCounts();
1054 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001055 } while(!Thread::exitPending());
1056 return false;
1057}
1058
Aravind Akella9a844cf2014-02-11 18:58:52 -08001059void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001060 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001061 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001062 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1063 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001064 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001065 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001066 }
Peng Xu2576cb62016-01-20 00:22:09 -08001067
Peng Xu6a2d3a02015-12-21 12:00:23 -08001068 auto logger = mRecentEvent.find(buffer[i].sensor);
1069 if (logger != mRecentEvent.end()) {
1070 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001071 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001072 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001073}
1074
Peng Xu47e96012016-03-28 17:55:56 -07001075void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001076 struct compar {
1077 static int cmp(void const* lhs, void const* rhs) {
1078 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1079 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001080 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001081 }
1082 };
1083 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1084}
1085
Mathias Agopian5d270722010-07-19 15:20:39 -07001086String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001087 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001088}
1089
Aravind Akellab4099e72013-10-15 15:43:10 -07001090bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001091 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1092 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001093}
1094
Aravind Akella9a844cf2014-02-11 18:58:52 -08001095bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001096 int handle = event.sensor;
1097 if (event.type == SENSOR_TYPE_META_DATA) {
1098 handle = event.meta_data.sensor;
1099 }
Peng Xu755c4512016-04-07 23:15:14 -07001100 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1101 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001102}
1103
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001104int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1105 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1106 // UUID is not supported for this device.
1107 return 0;
1108 }
1109 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1110 // This sensor can be uniquely identified in the system by
1111 // the combination of its type and name.
1112 return -1;
1113 }
1114
1115 // We have a dynamic sensor.
1116
1117 if (!sHmacGlobalKeyIsValid) {
1118 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1119 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1120 return 0;
1121 }
1122
1123 // We want each app author/publisher to get a different ID, so that the
1124 // same dynamic sensor cannot be tracked across apps by multiple
1125 // authors/publishers. So we use both our UUID and our User ID.
1126 // Note potential confusion:
1127 // UUID => Universally Unique Identifier.
1128 // UID => User Identifier.
1129 // We refrain from using "uid" except as needed by API to try to
1130 // keep this distinction clear.
1131
1132 auto appUserId = IPCThreadState::self()->getCallingUid();
1133 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1134 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1135 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1136
1137 // Now we use our key on our UUID/app combo to get the hash.
1138 uint8_t hash[EVP_MAX_MD_SIZE];
1139 unsigned int hashLen;
1140 if (HMAC(EVP_sha256(),
1141 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1142 uuidAndApp, sizeof(uuidAndApp),
1143 hash, &hashLen) == nullptr) {
1144 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1145 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1146 return 0;
1147 }
1148
1149 int32_t id = 0;
1150 if (hashLen < sizeof(id)) {
1151 // We never expect this case, but out of paranoia, we handle it.
1152 // Our 'id' length is already quite small, we don't want the
1153 // effective length of it to be even smaller.
1154 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1155 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1156 return 0;
1157 }
1158
1159 // This is almost certainly less than all of 'hash', but it's as secure
1160 // as we can be with our current 'id' length.
1161 memcpy(&id, hash, sizeof(id));
1162
1163 // Note at the beginning of the function that we return the values of
1164 // 0 and -1 to represent special cases. As a result, we can't return
1165 // those as dynamic sensor IDs. If we happened to hash to one of those
1166 // values, we change 'id' so we report as a dynamic sensor, and not as
1167 // one of those special cases.
1168 if (id == -1) {
1169 id = -2;
1170 } else if (id == 0) {
1171 id = 1;
1172 }
1173 return id;
1174}
1175
1176void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1177 for (auto &sensor : sensorList) {
1178 int32_t id = getIdFromUuid(sensor.getUuid());
1179 sensor.setId(id);
1180 }
1181}
1182
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001183Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001184 char value[PROPERTY_VALUE_MAX];
1185 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001186 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001187 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001188 Vector<Sensor> accessibleSensorList;
1189 for (size_t i = 0; i < initialSensorList.size(); i++) {
1190 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001191 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001192 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001193 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001194 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001195}
1196
Peng Xu47e96012016-03-28 17:55:56 -07001197Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001198 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001199 mSensors.forEachSensor(
1200 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001201 if (sensor.isDynamicSensor()) {
1202 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1203 accessibleSensorList.add(sensor);
1204 } else {
1205 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1206 sensor.getName().string(),
1207 sensor.getRequiredPermission().string(),
1208 sensor.getRequiredAppOp());
1209 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001210 }
1211 return true;
1212 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001213 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001214 return accessibleSensorList;
1215}
1216
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001217sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001218 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001219 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1220 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001221 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001222 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001223
1224 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001225 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1226 // operating in DI mode.
1227 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001228 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1229 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001230 }
1231
Mathias Agopian5307d172012-09-18 17:02:43 -07001232 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001233 pid_t pid = IPCThreadState::self()->getCallingPid();
1234
1235 String8 connPackageName =
1236 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1237 String16 connOpPackageName =
1238 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1239 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001240 requestedMode == DATA_INJECTION, connOpPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001241 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001242 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001243 // Add the associated file descriptor to the Looper for polling whenever there is data to
1244 // be injected.
1245 result->updateLooperRegistration(mLooper);
1246 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001247 return result;
1248}
1249
Aravind Akella841a5922015-06-29 12:37:48 -07001250int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001251 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001252 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001253}
1254
Peng Xue36e3472016-11-03 11:57:10 -07001255sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1256 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1257 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001258 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001259
Michael Groover5e1f60b2018-12-04 22:34:29 -08001260 // No new direct connections are allowed when sensor privacy is enabled
1261 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1262 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1263 return nullptr;
1264 }
1265
Peng Xue36e3472016-11-03 11:57:10 -07001266 struct sensors_direct_mem_t mem = {
1267 .type = type,
1268 .format = format,
1269 .size = size,
1270 .handle = resource,
1271 };
1272 uid_t uid = IPCThreadState::self()->getCallingUid();
1273
1274 if (mem.handle == nullptr) {
1275 ALOGE("Failed to clone resource handle");
1276 return nullptr;
1277 }
1278
1279 // check format
1280 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1281 ALOGE("Direct channel format %d is unsupported!", format);
1282 return nullptr;
1283 }
1284
1285 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001286 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1287 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001288 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001289 return nullptr;
1290 }
1291 }
1292
1293 // check specific to memory type
1294 switch(type) {
1295 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001296 if (resource->numFds < 1) {
1297 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1298 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1299 return nullptr;
1300 }
Peng Xue36e3472016-11-03 11:57:10 -07001301 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001302 if (!ashmem_valid(fd)) {
1303 ALOGE("Supplied Ashmem memory region is invalid");
1304 return nullptr;
1305 }
1306
Peng Xue36e3472016-11-03 11:57:10 -07001307 int size2 = ashmem_get_size_region(fd);
1308 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001309 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001310 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1311 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001312 return nullptr;
1313 }
1314 break;
1315 }
1316 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001317 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001318 break;
1319 default:
1320 ALOGE("Unknown direct connection memory type %d", type);
1321 return nullptr;
1322 }
1323
1324 native_handle_t *clone = native_handle_clone(resource);
1325 if (!clone) {
1326 return nullptr;
1327 }
1328
Brian Duddie967ce172019-06-10 11:08:27 -07001329 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001330 SensorDevice& dev(SensorDevice::getInstance());
1331 int channelHandle = dev.registerDirectChannel(&mem);
1332
1333 if (channelHandle <= 0) {
1334 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1335 } else {
1336 mem.handle = clone;
1337 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1338 }
1339
1340 if (conn == nullptr) {
1341 native_handle_close(clone);
1342 native_handle_delete(clone);
1343 } else {
1344 // add to list of direct connections
1345 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001346 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001347 }
1348 return conn;
1349}
1350
Peng Xudd5c5cb2017-03-16 17:39:43 -07001351int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001352 int32_t handle, int32_t type,
1353 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001354 Mutex::Autolock _l(mLock);
1355
Alexey Polyudov88711e82017-05-23 19:54:04 -07001356 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001357 return PERMISSION_DENIED;
1358 }
1359
1360 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001361 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001362 size_t expectSize = INT32_MAX;
1363 switch (type) {
1364 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1365 isFloat = true;
1366 expectSize = 3;
1367 break;
1368 case AINFO_LOCAL_GRAVITY:
1369 isFloat = true;
1370 expectSize = 1;
1371 break;
1372 case AINFO_DOCK_STATE:
1373 case AINFO_HIGH_PERFORMANCE_MODE:
1374 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1375 isFloat = false;
1376 expectSize = 1;
1377 break;
1378 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001379 // CUSTOM events must only contain float data; it may have variable size
1380 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1381 ints.size() ||
1382 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1383 handle < 0) {
1384 return BAD_VALUE;
1385 }
1386 isFloat = true;
1387 isCustom = true;
1388 expectSize = floats.size();
1389 break;
1390 }
1391
1392 if (!isCustom && handle != -1) {
1393 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001394 }
1395
1396 // three events: first one is begin tag, last one is end tag, the one in the middle
1397 // is the payload.
1398 sensors_event_t event[3];
1399 int64_t timestamp = elapsedRealtimeNano();
1400 for (sensors_event_t* i = event; i < event + 3; i++) {
1401 *i = (sensors_event_t) {
1402 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001403 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001404 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1405 .timestamp = timestamp++,
1406 .additional_info = (additional_info_event_t) {
1407 .serial = 0
1408 }
1409 };
1410 }
1411
1412 event[0].additional_info.type = AINFO_BEGIN;
1413 event[1].additional_info.type = type;
1414 event[2].additional_info.type = AINFO_END;
1415
1416 if (isFloat) {
1417 if (floats.size() != expectSize) {
1418 return BAD_VALUE;
1419 }
1420 for (size_t i = 0; i < expectSize; ++i) {
1421 event[1].additional_info.data_float[i] = floats[i];
1422 }
1423 } else {
1424 if (ints.size() != expectSize) {
1425 return BAD_VALUE;
1426 }
1427 for (size_t i = 0; i < expectSize; ++i) {
1428 event[1].additional_info.data_int32[i] = ints[i];
1429 }
1430 }
1431
1432 SensorDevice& dev(SensorDevice::getInstance());
1433 for (sensors_event_t* i = event; i < event + 3; i++) {
1434 int ret = dev.injectSensorData(i);
1435 if (ret != NO_ERROR) {
1436 return ret;
1437 }
1438 }
1439 return NO_ERROR;
1440}
1441
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001442status_t SensorService::resetToNormalMode() {
1443 Mutex::Autolock _l(mLock);
1444 return resetToNormalModeLocked();
1445}
1446
1447status_t SensorService::resetToNormalModeLocked() {
1448 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001449 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301450 if (err == NO_ERROR) {
1451 mCurrentOperatingMode = NORMAL;
1452 dev.enableAllSensors();
1453 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001454 return err;
1455}
1456
Peng Xu47e96012016-03-28 17:55:56 -07001457void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001458 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001459 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001460 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001461 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001462 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001463 int handle = mActiveSensors.keyAt(i);
1464 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001465 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001466 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1467 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001468 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001469 } else {
1470 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001471 }
Aravind Akella8a969552014-09-28 17:52:41 -07001472 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001473 }
1474 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001475 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001476 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001477 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001478 c, i, handle);
1479
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001480 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001481 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001482 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001483 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001484 delete rec;
1485 size--;
1486 } else {
1487 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001488 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001489 }
Aravind Akella8a969552014-09-28 17:52:41 -07001490 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001491 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001492 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001493 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001494 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001495 }
Peng Xu4f707f82016-09-26 11:28:32 -07001496
Brian Stack793f4642019-04-18 17:21:34 -07001497 {
1498 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1499 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1500 if (iter != sPackageTargetVersion.end()) {
1501 sPackageTargetVersion.erase(iter);
1502 }
1503 }
1504
Peng Xu4f707f82016-09-26 11:28:32 -07001505 SensorDevice& dev(SensorDevice::getInstance());
1506 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001507}
1508
Peng Xue36e3472016-11-03 11:57:10 -07001509void SensorService::cleanupConnection(SensorDirectConnection* c) {
1510 Mutex::Autolock _l(mLock);
1511
1512 SensorDevice& dev(SensorDevice::getInstance());
1513 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001514 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001515}
1516
Peng Xu755c4512016-04-07 23:15:14 -07001517sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001518 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001519}
1520
Mathias Agopianfc328812010-07-14 23:41:37 -07001521status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001522 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001523 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001524 if (mInitCheck != NO_ERROR)
1525 return mInitCheck;
1526
Peng Xu755c4512016-04-07 23:15:14 -07001527 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1528 if (sensor == nullptr ||
1529 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001530 return BAD_VALUE;
1531 }
1532
Brian Duddie967ce172019-06-10 11:08:27 -07001533 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001534 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001535 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001536 return INVALID_OPERATION;
1537 }
1538
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001539 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001540 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001541 rec = new SensorRecord(connection);
1542 mActiveSensors.add(handle, rec);
1543 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001544 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001545 }
Brian Stack26029ee2019-04-22 17:25:49 -07001546
1547 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1548 // the recent event as stale to ensure that the previous event is not sent to a client. This
1549 // ensures on-change events that were generated during a previous sensor activation are not
1550 // erroneously sent to newly connected clients, especially if a second client registers for
1551 // an on-change sensor before the first client receives the updated event. Once an updated
1552 // event is received, the recent events will be marked as current, and any new clients will
1553 // immediately receive the most recent event.
1554 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1555 auto logger = mRecentEvent.find(handle);
1556 if (logger != mRecentEvent.end()) {
1557 logger->second->setLastEventStale();
1558 }
1559 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001560 } else {
1561 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001562 // this sensor is already activated, but we are adding a connection that uses it.
1563 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001564 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001565 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001566 // NOTE: The wake_up flag of this event may get set to
1567 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001568
1569 auto logger = mRecentEvent.find(handle);
1570 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001571 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001572 // Verify that the last sensor event was generated from the current activation
1573 // of the sensor. If not, it is possible for an on-change sensor to receive a
1574 // sensor event that is stale if two clients re-activate the sensor
1575 // simultaneously.
1576 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001577 event.sensor = handle;
1578 if (event.version == sizeof(sensors_event_t)) {
1579 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1580 setWakeLockAcquiredLocked(true);
1581 }
Yi Kong8f313e32018-07-17 14:13:29 -07001582 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001583 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001584 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001585 }
1586 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001587 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001588 }
1589 }
1590 }
1591 }
1592
Arthur Ishiguro062b27b2020-04-13 08:04:49 -07001593 if (connection->addSensor(handle)) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001594 BatteryService::enableSensor(connection->getUid(), handle);
1595 // the sensor was added (which means it wasn't already there)
1596 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001597 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001598 } else {
1599 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1600 handle, connection.get());
1601 }
1602
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301603 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001604 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301605 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1606 samplingPeriodNs = maxDelayNs;
1607 }
1608
Aravind Akella724d91d2013-06-27 12:04:23 -07001609 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1610 if (samplingPeriodNs < minDelayNs) {
1611 samplingPeriodNs = minDelayNs;
1612 }
1613
Aravind Akella6c2664a2014-08-13 12:24:50 -07001614 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1615 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001616 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1617
Aravind Akella4949c502015-02-11 15:54:35 -08001618 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001619 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001620
Peng Xu20483c42015-10-26 15:14:43 -07001621 // Call flush() before calling activate() on the sensor. Wait for a first
1622 // flush complete event before sending events on this connection. Ignore
1623 // one-shot sensors which don't support flush(). Ignore on-change sensors
1624 // to maintain the on-change logic (any on-change events except the initial
1625 // one should be trigger by a change in value). Also if this sensor isn't
1626 // already active, don't call flush().
1627 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001628 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001629 rec->getNumConnections() > 1) {
1630 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001631 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001632 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001633 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001634 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001635 } else {
1636 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001637 }
1638 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001639
1640 if (err == NO_ERROR) {
1641 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1642 err = sensor->activate(connection.get(), true);
1643 }
1644
Aravind Akella8a969552014-09-28 17:52:41 -07001645 if (err == NO_ERROR) {
1646 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001647
Brian Stack240d1d62019-05-17 09:49:39 -07001648 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1649 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001650 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1651 }
1652
Peng Xu51224682017-03-10 16:57:27 -08001653 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1654 SensorRegistrationInfo(handle, connection->getPackageName(),
1655 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001656 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001657 }
1658
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001659 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001660 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001661 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001662 }
1663 return err;
1664}
1665
Peng Xu47e96012016-03-28 17:55:56 -07001666status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001667 if (mInitCheck != NO_ERROR)
1668 return mInitCheck;
1669
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001670 Mutex::Autolock _l(mLock);
1671 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001672 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001673 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1674 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001675
1676 }
1677 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001678 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1679 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001680 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001681 }
1682 return err;
1683}
1684
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001685status_t SensorService::cleanupWithoutDisable(
1686 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001687 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001688 return cleanupWithoutDisableLocked(connection, handle);
1689}
1690
1691status_t SensorService::cleanupWithoutDisableLocked(
1692 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001693 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001694 if (rec) {
1695 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001696 if (connection->removeSensor(handle)) {
1697 BatteryService::disableSensor(connection->getUid(), handle);
1698 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001699 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001700 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001701 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001702 }
1703 // see if this sensor becomes inactive
1704 if (rec->removeConnection(connection)) {
1705 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001706 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001707 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001708 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001709 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001710 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001711 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001712}
1713
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001714status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001715 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001716 if (mInitCheck != NO_ERROR)
1717 return mInitCheck;
1718
Peng Xu755c4512016-04-07 23:15:14 -07001719 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1720 if (sensor == nullptr ||
1721 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001722 return BAD_VALUE;
1723 }
1724
Mathias Agopian1cd70002010-07-21 15:59:50 -07001725 if (ns < 0)
1726 return BAD_VALUE;
1727
Mathias Agopian62569ec2011-11-07 21:21:47 -08001728 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1729 if (ns < minDelayNs) {
1730 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001731 }
1732
Mathias Agopianf001c922010-11-11 17:58:51 -08001733 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001734}
1735
Svetoslavb412f6e2015-04-29 16:50:41 -07001736status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1737 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001738 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001739 SensorDevice& dev(SensorDevice::getInstance());
1740 const int halVersion = dev.getHalDeviceVersion();
1741 status_t err(NO_ERROR);
1742 Mutex::Autolock _l(mLock);
1743 // Loop through all sensors for this connection and call flush on each of them.
Arthur Ishiguroad46c782020-03-26 11:24:43 -07001744 for (int handle : connection->getActiveSensorHandles()) {
Peng Xu755c4512016-04-07 23:15:14 -07001745 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1746 if (sensor == nullptr) {
1747 continue;
1748 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001749 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1750 ALOGE("flush called on a one-shot sensor");
1751 err = INVALID_OPERATION;
1752 continue;
1753 }
Aravind Akella8493b792014-09-08 15:45:47 -07001754 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001755 // For older devices just increment pending flush count which will send a trivial
1756 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001757 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001758 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001759 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1760 err = INVALID_OPERATION;
1761 continue;
1762 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001763 status_t err_flush = sensor->flush(connection.get(), handle);
1764 if (err_flush == NO_ERROR) {
1765 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001766 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001767 }
1768 err = (err_flush != NO_ERROR) ? err_flush : err;
1769 }
Aravind Akella70018042014-04-07 22:52:37 +00001770 }
Arthur Ishigurofb64fca2020-04-14 11:28:11 -07001771 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001772}
Aravind Akella70018042014-04-07 22:52:37 +00001773
Svetoslavb412f6e2015-04-29 16:50:41 -07001774bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1775 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001776 // Check if a permission is required for this sensor
1777 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001778 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001779 }
1780
Brian Stack793f4642019-04-18 17:21:34 -07001781 const int32_t opCode = sensor.getRequiredAppOp();
1782 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1783 IPCThreadState::self()->getCallingUid(), opPackageName);
Brian Stack6a700f92019-05-08 17:02:53 -07001784 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
Brian Stack793f4642019-04-18 17:21:34 -07001785
Brian Stack793f4642019-04-18 17:21:34 -07001786 bool canAccess = false;
Brian Stack6a700f92019-05-08 17:02:53 -07001787 if (hasPermissionForSensor(sensor)) {
1788 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1789 if (opCode < 0 || appOpAllowed) {
Brian Stack793f4642019-04-18 17:21:34 -07001790 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001791 }
1792 } else if (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1793 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR) {
1794 int targetSdkVersion = getTargetSdkVersion(opPackageName);
1795 // Allow access to the sensor if the application targets pre-Q, which is before the
1796 // requirement to hold the AR permission to access Step Counter and Step Detector events
1797 // was introduced, and the user hasn't revoked the app op.
1798 //
1799 // Verifying the app op is required to ensure that the user hasn't revoked the necessary
1800 // permissions to access the Step Detector and Step Counter when the application targets
1801 // pre-Q. Without this check, if the user revokes the pre-Q install-time GMS Core AR
1802 // permission, the app would still be able to receive Step Counter and Step Detector events.
1803 if (appOpAllowed &&
1804 targetSdkVersion > 0 &&
1805 targetSdkVersion <= __ANDROID_API_P__) {
1806 canAccess = true;
Brian Stack793f4642019-04-18 17:21:34 -07001807 }
1808 }
1809
1810 if (canAccess) {
1811 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1812 } else {
1813 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1814 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1815 }
1816
1817 return canAccess;
1818}
1819
1820bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001821 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001822 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001823
1824 // Runtime permissions can't use the cache as they may change.
1825 if (sensor.isRequiredPermissionRuntime()) {
1826 hasPermission = checkPermission(String16(requiredPermission),
1827 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001828 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001829 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1830 }
Brian Stack793f4642019-04-18 17:21:34 -07001831 return hasPermission;
1832}
Svetoslavb412f6e2015-04-29 16:50:41 -07001833
Brian Stack793f4642019-04-18 17:21:34 -07001834int SensorService::getTargetSdkVersion(const String16& opPackageName) {
1835 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1836 int targetSdkVersion = -1;
1837 auto entry = sPackageTargetVersion.find(opPackageName);
1838 if (entry != sPackageTargetVersion.end()) {
1839 targetSdkVersion = entry->second;
1840 } else {
1841 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1842 if (binder != nullptr) {
1843 sp<content::pm::IPackageManagerNative> packageManager =
1844 interface_cast<content::pm::IPackageManagerNative>(binder);
1845 if (packageManager != nullptr) {
1846 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1847 opPackageName, &targetSdkVersion);
1848 if (!status.isOk()) {
1849 targetSdkVersion = -1;
1850 }
1851 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001852 }
Brian Stack793f4642019-04-18 17:21:34 -07001853 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001854 }
Brian Stack793f4642019-04-18 17:21:34 -07001855 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001856}
1857
Aravind Akella9a844cf2014-02-11 18:58:52 -08001858void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001859 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1860 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001861}
1862
Brian Duddie967ce172019-06-10 11:08:27 -07001863void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001864 if (!mWakeLockAcquired) {
1865 return;
1866 }
1867 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001868 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1869 if (connection->needsWakeLock()) {
1870 releaseLock = false;
1871 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001872 }
1873 }
1874 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001875 setWakeLockAcquiredLocked(false);
1876 }
1877}
1878
1879void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1880 Mutex::Autolock _l(mLock);
1881 connection->writeToSocketFromCache();
1882 if (connection->needsWakeLock()) {
1883 setWakeLockAcquiredLocked(true);
1884 }
1885}
1886
Aravind Akella4949c502015-02-11 15:54:35 -08001887bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001888 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001889}
1890
Brian Stack5180e462019-03-08 17:15:19 -08001891bool SensorService::isOperationPermitted(const String16& opPackageName) {
Peng Xue36e3472016-11-03 11:57:10 -07001892 Mutex::Autolock _l(mLock);
Brian Stack5180e462019-03-08 17:15:19 -08001893 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001894 String8 package(opPackageName);
Brian Stack5180e462019-03-08 17:15:19 -08001895 return isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001896 }
Brian Stack5180e462019-03-08 17:15:19 -08001897 return true;
Peng Xue36e3472016-11-03 11:57:10 -07001898}
1899
Svet Ganove752a5c2018-01-15 17:14:20 -08001900void SensorService::UidPolicy::registerSelf() {
1901 ActivityManager am;
1902 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1903 | ActivityManager::UID_OBSERVER_IDLE
1904 | ActivityManager::UID_OBSERVER_ACTIVE,
1905 ActivityManager::PROCESS_STATE_UNKNOWN,
1906 String16("android"));
1907}
1908
1909void SensorService::UidPolicy::unregisterSelf() {
1910 ActivityManager am;
1911 am.unregisterUidObserver(this);
1912}
1913
1914void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1915 onUidIdle(uid, disabled);
1916}
1917
1918void SensorService::UidPolicy::onUidActive(uid_t uid) {
1919 {
1920 Mutex::Autolock _l(mUidLock);
1921 mActiveUids.insert(uid);
1922 }
1923 sp<SensorService> service = mService.promote();
1924 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001925 service->onUidStateChanged(uid, UID_STATE_ACTIVE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001926 }
1927}
1928
1929void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1930 bool deleted = false;
1931 {
1932 Mutex::Autolock _l(mUidLock);
1933 if (mActiveUids.erase(uid) > 0) {
1934 deleted = true;
1935 }
1936 }
1937 if (deleted) {
1938 sp<SensorService> service = mService.promote();
1939 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001940 service->onUidStateChanged(uid, UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001941 }
1942 }
1943}
1944
1945void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1946 updateOverrideUid(uid, active, true);
1947}
1948
1949void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1950 updateOverrideUid(uid, false, false);
1951}
1952
1953void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1954 bool wasActive = false;
1955 bool isActive = false;
1956 {
1957 Mutex::Autolock _l(mUidLock);
1958 wasActive = isUidActiveLocked(uid);
1959 mOverrideUids.erase(uid);
1960 if (insert) {
1961 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1962 }
1963 isActive = isUidActiveLocked(uid);
1964 }
1965 if (wasActive != isActive) {
1966 sp<SensorService> service = mService.promote();
1967 if (service != nullptr) {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001968 service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
Svet Ganove752a5c2018-01-15 17:14:20 -08001969 }
1970 }
1971}
1972
1973bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1974 // Non-app UIDs are considered always active
1975 if (uid < FIRST_APPLICATION_UID) {
1976 return true;
1977 }
1978 Mutex::Autolock _l(mUidLock);
1979 return isUidActiveLocked(uid);
1980}
1981
1982bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1983 // Non-app UIDs are considered always active
1984 if (uid < FIRST_APPLICATION_UID) {
1985 return true;
1986 }
1987 auto it = mOverrideUids.find(uid);
1988 if (it != mOverrideUids.end()) {
1989 return it->second;
1990 }
1991 return mActiveUids.find(uid) != mActiveUids.end();
1992}
1993
Arthur Ishiguro539c27c2020-04-13 09:47:59 -07001994bool SensorService::isUidActive(uid_t uid) {
1995 return mUidPolicy->isUidActive(uid);
1996}
1997
Michael Groover5e1f60b2018-12-04 22:34:29 -08001998void SensorService::SensorPrivacyPolicy::registerSelf() {
1999 SensorPrivacyManager spm;
2000 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2001 spm.addSensorPrivacyListener(this);
2002}
2003
2004void SensorService::SensorPrivacyPolicy::unregisterSelf() {
2005 SensorPrivacyManager spm;
2006 spm.removeSensorPrivacyListener(this);
2007}
2008
2009bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2010 return mSensorPrivacyEnabled;
2011}
2012
2013binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2014 mSensorPrivacyEnabled = enabled;
2015 sp<SensorService> service = mService.promote();
2016 if (service != nullptr) {
2017 if (enabled) {
2018 service->disableAllSensors();
2019 } else {
2020 service->enableAllSensors();
2021 }
2022 }
2023 return binder::Status::ok();
2024}
Brian Duddie967ce172019-06-10 11:08:27 -07002025
2026SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2027 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2028 : mConnectionHolder(holder), mAutolock(mutex) {}
2029
2030template<typename ConnectionType>
2031const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2032 const SortedVector<wp<ConnectionType>>& connectionList,
2033 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2034 referenceHolder->emplace_back();
2035 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2036 for (const wp<ConnectionType>& weakConnection : connectionList){
2037 sp<ConnectionType> connection = weakConnection.promote();
2038 if (connection != nullptr) {
2039 connections.push_back(std::move(connection));
2040 }
2041 }
2042 return connections;
2043}
2044
2045const std::vector<sp<SensorService::SensorEventConnection>>&
2046 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2047 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2048 &mReferencedActiveConnections);
2049}
2050
2051const std::vector<sp<SensorService::SensorDirectConnection>>&
2052 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2053 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2054 &mReferencedDirectConnections);
2055}
2056
2057void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2058 const sp<SensorService::SensorEventConnection>& connection) {
2059 if (mActiveConnections.indexOf(connection) < 0) {
2060 mActiveConnections.add(connection);
2061 }
2062}
2063
2064void SensorService::SensorConnectionHolder::removeEventConnection(
2065 const wp<SensorService::SensorEventConnection>& connection) {
2066 mActiveConnections.remove(connection);
2067}
2068
2069void SensorService::SensorConnectionHolder::addDirectConnection(
2070 const sp<SensorService::SensorDirectConnection>& connection) {
2071 mDirectConnections.add(connection);
2072}
2073
2074void SensorService::SensorConnectionHolder::removeDirectConnection(
2075 const wp<SensorService::SensorDirectConnection>& connection) {
2076 mDirectConnections.remove(connection);
2077}
2078
2079SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2080 return ConnectionSafeAutolock(*this, mutex);
2081}
2082
2083} // namespace android