1 /*
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 */
16
17 #define LOG_TAG "Sensors"
18
19 #include <sensor/SensorManager.h>
20
21 #include <stdint.h>
22 #include <sys/types.h>
23
24 #include <cutils/native_handle.h>
25 #include <utils/Errors.h>
26 #include <utils/RefBase.h>
27 #include <utils/Singleton.h>
28
29 #include <binder/IBinder.h>
30 #include <binder/IPermissionController.h>
31 #include <binder/IServiceManager.h>
32
33 #include <sensor/ISensorServer.h>
34 #include <sensor/ISensorEventConnection.h>
35 #include <sensor/Sensor.h>
36 #include <sensor/SensorEventQueue.h>
37
38 // ----------------------------------------------------------------------------
39 namespace android {
40 // ----------------------------------------------------------------------------
41
42 Mutex SensorManager::sLock;
43 std::map<String16, SensorManager*> SensorManager::sPackageInstances;
44
getInstanceForPackage(const String16 & packageName)45 SensorManager& SensorManager::getInstanceForPackage(const String16& packageName) {
46 waitForSensorService(nullptr);
47
48 Mutex::Autolock _l(sLock);
49 SensorManager* sensorManager;
50 auto iterator = sPackageInstances.find(packageName);
51
52 if (iterator != sPackageInstances.end()) {
53 sensorManager = iterator->second;
54 } else {
55 String16 opPackageName = packageName;
56
57 // It is possible that the calling code has no access to the package name.
58 // In this case we will get the packages for the calling UID and pick the
59 // first one for attributing the app op. This will work correctly for
60 // runtime permissions as for legacy apps we will toggle the app op for
61 // all packages in the UID. The caveat is that the operation may be attributed
62 // to the wrong package and stats based on app ops may be slightly off.
63 if (opPackageName.size() <= 0) {
64 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
65 if (binder != nullptr) {
66 const uid_t uid = IPCThreadState::self()->getCallingUid();
67 Vector<String16> packages;
68 interface_cast<IPermissionController>(binder)->getPackagesForUid(uid, packages);
69 if (!packages.isEmpty()) {
70 opPackageName = packages[0];
71 } else {
72 ALOGE("No packages for calling UID");
73 }
74 } else {
75 ALOGE("Cannot get permission service");
76 }
77 }
78
79 sensorManager = new SensorManager(opPackageName);
80
81 // If we had no package name, we looked it up from the UID and the sensor
82 // manager instance we created should also be mapped to the empty package
83 // name, to avoid looking up the packages for a UID and get the same result.
84 if (packageName.size() <= 0) {
85 sPackageInstances.insert(std::make_pair(String16(), sensorManager));
86 }
87
88 // Stash the per package sensor manager.
89 sPackageInstances.insert(std::make_pair(opPackageName, sensorManager));
90 }
91
92 return *sensorManager;
93 }
94
removeInstanceForPackage(const String16 & packageName)95 void SensorManager::removeInstanceForPackage(const String16& packageName) {
96 Mutex::Autolock _l(sLock);
97 auto iterator = sPackageInstances.find(packageName);
98 if (iterator != sPackageInstances.end()) {
99 SensorManager* sensorManager = iterator->second;
100 delete sensorManager;
101 sPackageInstances.erase(iterator);
102 }
103 }
104
SensorManager(const String16 & opPackageName)105 SensorManager::SensorManager(const String16& opPackageName)
106 : mSensorList(nullptr), mOpPackageName(opPackageName), mDirectConnectionHandle(1) {
107 Mutex::Autolock _l(mLock);
108 assertStateLocked();
109 }
110
~SensorManager()111 SensorManager::~SensorManager() {
112 free(mSensorList);
113 free(mDynamicSensorList);
114 }
115
waitForSensorService(sp<ISensorServer> * server)116 status_t SensorManager::waitForSensorService(sp<ISensorServer> *server) {
117 // try for 300 seconds (60*5(getService() tries for 5 seconds)) before giving up ...
118 sp<ISensorServer> s;
119 const String16 name("sensorservice");
120 for (int i = 0; i < 60; i++) {
121 status_t err = getService(name, &s);
122 switch (err) {
123 case NAME_NOT_FOUND:
124 sleep(1);
125 continue;
126 case NO_ERROR:
127 if (server != nullptr) {
128 *server = s;
129 }
130 return NO_ERROR;
131 default:
132 return err;
133 }
134 }
135 return TIMED_OUT;
136 }
137
sensorManagerDied()138 void SensorManager::sensorManagerDied() {
139 Mutex::Autolock _l(mLock);
140 mSensorServer.clear();
141 free(mSensorList);
142 mSensorList = nullptr;
143 mSensors.clear();
144 free(mDynamicSensorList);
145 mDynamicSensorList = nullptr;
146 mDynamicSensors.clear();
147 }
148
assertStateLocked()149 status_t SensorManager::assertStateLocked() {
150 bool initSensorManager = false;
151 if (mSensorServer == nullptr) {
152 initSensorManager = true;
153 } else {
154 // Ping binder to check if sensorservice is alive.
155 status_t err = IInterface::asBinder(mSensorServer)->pingBinder();
156 if (err != NO_ERROR) {
157 initSensorManager = true;
158 }
159 }
160 if (initSensorManager) {
161 waitForSensorService(&mSensorServer);
162 LOG_ALWAYS_FATAL_IF(mSensorServer == nullptr, "getService(SensorService) NULL");
163
164 class DeathObserver : public IBinder::DeathRecipient {
165 SensorManager& mSensorManager;
166 virtual void binderDied(const wp<IBinder>& who) {
167 ALOGW("sensorservice died [%p]", static_cast<void*>(who.unsafe_get()));
168 mSensorManager.sensorManagerDied();
169 }
170 public:
171 explicit DeathObserver(SensorManager& mgr) : mSensorManager(mgr) { }
172 };
173
174 mDeathObserver = new DeathObserver(*const_cast<SensorManager *>(this));
175 IInterface::asBinder(mSensorServer)->linkToDeath(mDeathObserver);
176
177 mSensors = mSensorServer->getSensorList(mOpPackageName);
178 size_t count = mSensors.size();
179 if (count == 0) {
180 ALOGE("Failed to get Sensor list");
181 mSensorServer.clear();
182 return UNKNOWN_ERROR;
183 }
184 mSensorList =
185 static_cast<Sensor const**>(malloc(count * sizeof(Sensor*)));
186 LOG_ALWAYS_FATAL_IF(mSensorList == nullptr, "mSensorList NULL");
187
188 for (size_t i=0 ; i<count ; i++) {
189 mSensorList[i] = mSensors.array() + i;
190 }
191 }
192
193 return NO_ERROR;
194 }
195
getSensorList(Sensor const * const ** list)196 ssize_t SensorManager::getSensorList(Sensor const* const** list) {
197 Mutex::Autolock _l(mLock);
198 status_t err = assertStateLocked();
199 if (err < 0) {
200 return static_cast<ssize_t>(err);
201 }
202 *list = mSensorList;
203 return static_cast<ssize_t>(mSensors.size());
204 }
205
getDynamicSensorList(Vector<Sensor> & dynamicSensors)206 ssize_t SensorManager::getDynamicSensorList(Vector<Sensor> & dynamicSensors) {
207 Mutex::Autolock _l(mLock);
208 status_t err = assertStateLocked();
209 if (err < 0) {
210 return static_cast<ssize_t>(err);
211 }
212
213 dynamicSensors = mSensorServer->getDynamicSensorList(mOpPackageName);
214 size_t count = dynamicSensors.size();
215
216 return static_cast<ssize_t>(count);
217 }
218
getDynamicSensorList(Sensor const * const ** list)219 ssize_t SensorManager::getDynamicSensorList(Sensor const* const** list) {
220 Mutex::Autolock _l(mLock);
221 status_t err = assertStateLocked();
222 if (err < 0) {
223 return static_cast<ssize_t>(err);
224 }
225
226 free(mDynamicSensorList);
227 mDynamicSensorList = nullptr;
228 mDynamicSensors = mSensorServer->getDynamicSensorList(mOpPackageName);
229 size_t dynamicCount = mDynamicSensors.size();
230 if (dynamicCount > 0) {
231 mDynamicSensorList = static_cast<Sensor const**>(
232 malloc(dynamicCount * sizeof(Sensor*)));
233 if (mDynamicSensorList == nullptr) {
234 ALOGE("Failed to allocate dynamic sensor list for %zu sensors.",
235 dynamicCount);
236 return static_cast<ssize_t>(NO_MEMORY);
237 }
238
239 for (size_t i = 0; i < dynamicCount; i++) {
240 mDynamicSensorList[i] = mDynamicSensors.array() + i;
241 }
242 }
243
244 *list = mDynamicSensorList;
245 return static_cast<ssize_t>(mDynamicSensors.size());
246 }
247
getDefaultSensor(int type)248 Sensor const* SensorManager::getDefaultSensor(int type)
249 {
250 Mutex::Autolock _l(mLock);
251 if (assertStateLocked() == NO_ERROR) {
252 bool wakeUpSensor = false;
253 // For the following sensor types, return a wake-up sensor. These types are by default
254 // defined as wake-up sensors. For the rest of the sensor types defined in sensors.h return
255 // a non_wake-up version.
256 if (type == SENSOR_TYPE_PROXIMITY || type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
257 type == SENSOR_TYPE_TILT_DETECTOR || type == SENSOR_TYPE_WAKE_GESTURE ||
258 type == SENSOR_TYPE_GLANCE_GESTURE || type == SENSOR_TYPE_PICK_UP_GESTURE ||
259 type == SENSOR_TYPE_WRIST_TILT_GESTURE ||
260 type == SENSOR_TYPE_LOW_LATENCY_OFFBODY_DETECT || type == SENSOR_TYPE_HINGE_ANGLE) {
261 wakeUpSensor = true;
262 }
263 // For now we just return the first sensor of that type we find.
264 // in the future it will make sense to let the SensorService make
265 // that decision.
266 for (size_t i=0 ; i<mSensors.size() ; i++) {
267 if (mSensorList[i]->getType() == type &&
268 mSensorList[i]->isWakeUpSensor() == wakeUpSensor) {
269 return mSensorList[i];
270 }
271 }
272 }
273 return nullptr;
274 }
275
createEventQueue(String8 packageName,int mode,String16 attributionTag)276 sp<SensorEventQueue> SensorManager::createEventQueue(
277 String8 packageName, int mode, String16 attributionTag) {
278 sp<SensorEventQueue> queue;
279
280 Mutex::Autolock _l(mLock);
281 while (assertStateLocked() == NO_ERROR) {
282 sp<ISensorEventConnection> connection = mSensorServer->createSensorEventConnection(
283 packageName, mode, mOpPackageName, attributionTag);
284 if (connection == nullptr) {
285 // SensorService just died or the app doesn't have required permissions.
286 ALOGE("createEventQueue: connection is NULL.");
287 return nullptr;
288 }
289 queue = new SensorEventQueue(connection);
290 break;
291 }
292 return queue;
293 }
294
isDataInjectionEnabled()295 bool SensorManager::isDataInjectionEnabled() {
296 Mutex::Autolock _l(mLock);
297 if (assertStateLocked() == NO_ERROR) {
298 return mSensorServer->isDataInjectionEnabled();
299 }
300 return false;
301 }
302
createDirectChannel(size_t size,int channelType,const native_handle_t * resourceHandle)303 int SensorManager::createDirectChannel(
304 size_t size, int channelType, const native_handle_t *resourceHandle) {
305 Mutex::Autolock _l(mLock);
306 if (assertStateLocked() != NO_ERROR) {
307 return NO_INIT;
308 }
309
310 if (channelType != SENSOR_DIRECT_MEM_TYPE_ASHMEM
311 && channelType != SENSOR_DIRECT_MEM_TYPE_GRALLOC) {
312 ALOGE("Bad channel shared memory type %d", channelType);
313 return BAD_VALUE;
314 }
315
316 sp<ISensorEventConnection> conn =
317 mSensorServer->createSensorDirectConnection(mOpPackageName,
318 static_cast<uint32_t>(size),
319 static_cast<int32_t>(channelType),
320 SENSOR_DIRECT_FMT_SENSORS_EVENT, resourceHandle);
321 if (conn == nullptr) {
322 return NO_MEMORY;
323 }
324
325 int nativeHandle = mDirectConnectionHandle++;
326 mDirectConnection.emplace(nativeHandle, conn);
327 return nativeHandle;
328 }
329
destroyDirectChannel(int channelNativeHandle)330 void SensorManager::destroyDirectChannel(int channelNativeHandle) {
331 Mutex::Autolock _l(mLock);
332 if (assertStateLocked() == NO_ERROR) {
333 mDirectConnection.erase(channelNativeHandle);
334 }
335 }
336
configureDirectChannel(int channelNativeHandle,int sensorHandle,int rateLevel)337 int SensorManager::configureDirectChannel(int channelNativeHandle, int sensorHandle, int rateLevel) {
338 Mutex::Autolock _l(mLock);
339 if (assertStateLocked() != NO_ERROR) {
340 return NO_INIT;
341 }
342
343 auto i = mDirectConnection.find(channelNativeHandle);
344 if (i == mDirectConnection.end()) {
345 ALOGE("Cannot find the handle in client direct connection table");
346 return BAD_VALUE;
347 }
348
349 int ret;
350 ret = i->second->configureChannel(sensorHandle, rateLevel);
351 ALOGE_IF(ret < 0, "SensorManager::configureChannel (%d, %d) returns %d",
352 static_cast<int>(sensorHandle), static_cast<int>(rateLevel),
353 static_cast<int>(ret));
354 return ret;
355 }
356
setOperationParameter(int handle,int type,const Vector<float> & floats,const Vector<int32_t> & ints)357 int SensorManager::setOperationParameter(
358 int handle, int type,
359 const Vector<float> &floats, const Vector<int32_t> &ints) {
360 Mutex::Autolock _l(mLock);
361 if (assertStateLocked() != NO_ERROR) {
362 return NO_INIT;
363 }
364 return mSensorServer->setOperationParameter(handle, type, floats, ints);
365 }
366
367 // ----------------------------------------------------------------------------
368 }; // namespace android
369