• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 is 0, mSensorList will be non-null. This is old
180         // existing behavior and callers expect this.
181         mSensorList =
182                 static_cast<Sensor const**>(malloc(count * sizeof(Sensor*)));
183         LOG_ALWAYS_FATAL_IF(mSensorList == nullptr, "mSensorList NULL");
184 
185         for (size_t i=0 ; i<count ; i++) {
186             mSensorList[i] = mSensors.array() + i;
187         }
188     }
189 
190     return NO_ERROR;
191 }
192 
getSensorList(Sensor const * const ** list)193 ssize_t SensorManager::getSensorList(Sensor const* const** list) {
194     Mutex::Autolock _l(mLock);
195     status_t err = assertStateLocked();
196     if (err < 0) {
197         return static_cast<ssize_t>(err);
198     }
199     *list = mSensorList;
200     return static_cast<ssize_t>(mSensors.size());
201 }
202 
getDynamicSensorList(Vector<Sensor> & dynamicSensors)203 ssize_t SensorManager::getDynamicSensorList(Vector<Sensor> & dynamicSensors) {
204     Mutex::Autolock _l(mLock);
205     status_t err = assertStateLocked();
206     if (err < 0) {
207         return static_cast<ssize_t>(err);
208     }
209 
210     dynamicSensors = mSensorServer->getDynamicSensorList(mOpPackageName);
211     size_t count = dynamicSensors.size();
212 
213     return static_cast<ssize_t>(count);
214 }
215 
getRuntimeSensorList(int deviceId,Vector<Sensor> & runtimeSensors)216 ssize_t SensorManager::getRuntimeSensorList(int deviceId, Vector<Sensor>& runtimeSensors) {
217     Mutex::Autolock _l(mLock);
218     status_t err = assertStateLocked();
219     if (err < 0) {
220         return static_cast<ssize_t>(err);
221     }
222 
223     runtimeSensors = mSensorServer->getRuntimeSensorList(mOpPackageName, deviceId);
224     size_t count = runtimeSensors.size();
225 
226     return static_cast<ssize_t>(count);
227 }
228 
getDynamicSensorList(Sensor const * const ** list)229 ssize_t SensorManager::getDynamicSensorList(Sensor const* const** list) {
230     Mutex::Autolock _l(mLock);
231     status_t err = assertStateLocked();
232     if (err < 0) {
233         return static_cast<ssize_t>(err);
234     }
235 
236     free(mDynamicSensorList);
237     mDynamicSensorList = nullptr;
238     mDynamicSensors = mSensorServer->getDynamicSensorList(mOpPackageName);
239     size_t dynamicCount = mDynamicSensors.size();
240     if (dynamicCount > 0) {
241         mDynamicSensorList = static_cast<Sensor const**>(
242                 malloc(dynamicCount * sizeof(Sensor*)));
243         if (mDynamicSensorList == nullptr) {
244           ALOGE("Failed to allocate dynamic sensor list for %zu sensors.",
245                 dynamicCount);
246           return static_cast<ssize_t>(NO_MEMORY);
247         }
248 
249         for (size_t i = 0; i < dynamicCount; i++) {
250             mDynamicSensorList[i] = mDynamicSensors.array() + i;
251         }
252     }
253 
254     *list = mDynamicSensorList;
255     return static_cast<ssize_t>(mDynamicSensors.size());
256 }
257 
getDefaultSensor(int type)258 Sensor const* SensorManager::getDefaultSensor(int type)
259 {
260     Mutex::Autolock _l(mLock);
261     if (assertStateLocked() == NO_ERROR) {
262         bool wakeUpSensor = false;
263         // For the following sensor types, return a wake-up sensor. These types are by default
264         // defined as wake-up sensors. For the rest of the sensor types defined in sensors.h return
265         // a non_wake-up version.
266         if (type == SENSOR_TYPE_PROXIMITY || type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
267             type == SENSOR_TYPE_TILT_DETECTOR || type == SENSOR_TYPE_WAKE_GESTURE ||
268             type == SENSOR_TYPE_GLANCE_GESTURE || type == SENSOR_TYPE_PICK_UP_GESTURE ||
269             type == SENSOR_TYPE_WRIST_TILT_GESTURE ||
270             type == SENSOR_TYPE_LOW_LATENCY_OFFBODY_DETECT || type == SENSOR_TYPE_HINGE_ANGLE) {
271             wakeUpSensor = true;
272         }
273         // For now we just return the first sensor of that type we find.
274         // in the future it will make sense to let the SensorService make
275         // that decision.
276         for (size_t i=0 ; i<mSensors.size() ; i++) {
277             if (mSensorList[i]->getType() == type &&
278                 mSensorList[i]->isWakeUpSensor() == wakeUpSensor) {
279                 return mSensorList[i];
280             }
281         }
282     }
283     return nullptr;
284 }
285 
createEventQueue(String8 packageName,int mode,String16 attributionTag)286 sp<SensorEventQueue> SensorManager::createEventQueue(
287     String8 packageName, int mode, String16 attributionTag) {
288     sp<SensorEventQueue> queue;
289 
290     Mutex::Autolock _l(mLock);
291     while (assertStateLocked() == NO_ERROR) {
292         sp<ISensorEventConnection> connection = mSensorServer->createSensorEventConnection(
293             packageName, mode, mOpPackageName, attributionTag);
294         if (connection == nullptr) {
295             // SensorService just died or the app doesn't have required permissions.
296             ALOGE("createEventQueue: connection is NULL.");
297             return nullptr;
298         }
299         queue = new SensorEventQueue(connection);
300         break;
301     }
302     return queue;
303 }
304 
isDataInjectionEnabled()305 bool SensorManager::isDataInjectionEnabled() {
306     Mutex::Autolock _l(mLock);
307     if (assertStateLocked() == NO_ERROR) {
308         return mSensorServer->isDataInjectionEnabled();
309     }
310     return false;
311 }
312 
createDirectChannel(size_t size,int channelType,const native_handle_t * resourceHandle)313 int SensorManager::createDirectChannel(
314         size_t size, int channelType, const native_handle_t *resourceHandle) {
315     static constexpr int DEFAULT_DEVICE_ID = 0;
316     return createDirectChannel(DEFAULT_DEVICE_ID, size, channelType, resourceHandle);
317 }
318 
createDirectChannel(int deviceId,size_t size,int channelType,const native_handle_t * resourceHandle)319 int SensorManager::createDirectChannel(
320         int deviceId, size_t size, int channelType, const native_handle_t *resourceHandle) {
321     Mutex::Autolock _l(mLock);
322     if (assertStateLocked() != NO_ERROR) {
323         return NO_INIT;
324     }
325 
326     if (channelType != SENSOR_DIRECT_MEM_TYPE_ASHMEM
327             && channelType != SENSOR_DIRECT_MEM_TYPE_GRALLOC) {
328         ALOGE("Bad channel shared memory type %d", channelType);
329         return BAD_VALUE;
330     }
331 
332     sp<ISensorEventConnection> conn =
333               mSensorServer->createSensorDirectConnection(mOpPackageName, deviceId,
334                   static_cast<uint32_t>(size),
335                   static_cast<int32_t>(channelType),
336                   SENSOR_DIRECT_FMT_SENSORS_EVENT, resourceHandle);
337     if (conn == nullptr) {
338         return NO_MEMORY;
339     }
340 
341     int nativeHandle = mDirectConnectionHandle++;
342     mDirectConnection.emplace(nativeHandle, conn);
343     return nativeHandle;
344 }
345 
destroyDirectChannel(int channelNativeHandle)346 void SensorManager::destroyDirectChannel(int channelNativeHandle) {
347     Mutex::Autolock _l(mLock);
348     if (assertStateLocked() == NO_ERROR) {
349         mDirectConnection.erase(channelNativeHandle);
350     }
351 }
352 
configureDirectChannel(int channelNativeHandle,int sensorHandle,int rateLevel)353 int SensorManager::configureDirectChannel(int channelNativeHandle, int sensorHandle, int rateLevel) {
354     Mutex::Autolock _l(mLock);
355     if (assertStateLocked() != NO_ERROR) {
356         return NO_INIT;
357     }
358 
359     auto i = mDirectConnection.find(channelNativeHandle);
360     if (i == mDirectConnection.end()) {
361         ALOGE("Cannot find the handle in client direct connection table");
362         return BAD_VALUE;
363     }
364 
365     int ret;
366     ret = i->second->configureChannel(sensorHandle, rateLevel);
367     ALOGE_IF(ret < 0, "SensorManager::configureChannel (%d, %d) returns %d",
368             static_cast<int>(sensorHandle), static_cast<int>(rateLevel),
369             static_cast<int>(ret));
370     return ret;
371 }
372 
setOperationParameter(int handle,int type,const Vector<float> & floats,const Vector<int32_t> & ints)373 int SensorManager::setOperationParameter(
374         int handle, int type,
375         const Vector<float> &floats, const Vector<int32_t> &ints) {
376     Mutex::Autolock _l(mLock);
377     if (assertStateLocked() != NO_ERROR) {
378         return NO_INIT;
379     }
380     return mSensorServer->setOperationParameter(handle, type, floats, ints);
381 }
382 
383 // ----------------------------------------------------------------------------
384 }; // namespace android
385