• 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 
SensorManager(const String16 & opPackageName)95 SensorManager::SensorManager(const String16& opPackageName)
96     : mSensorList(nullptr), mOpPackageName(opPackageName), mDirectConnectionHandle(1) {
97     Mutex::Autolock _l(mLock);
98     assertStateLocked();
99 }
100 
~SensorManager()101 SensorManager::~SensorManager() {
102     free(mSensorList);
103 }
104 
waitForSensorService(sp<ISensorServer> * server)105 status_t SensorManager::waitForSensorService(sp<ISensorServer> *server) {
106     // try for 300 seconds (60*5(getService() tries for 5 seconds)) before giving up ...
107     sp<ISensorServer> s;
108     const String16 name("sensorservice");
109     for (int i = 0; i < 60; i++) {
110         status_t err = getService(name, &s);
111         switch (err) {
112             case NAME_NOT_FOUND:
113                 sleep(1);
114                 continue;
115             case NO_ERROR:
116                 if (server != nullptr) {
117                     *server = s;
118                 }
119                 return NO_ERROR;
120             default:
121                 return err;
122         }
123     }
124     return TIMED_OUT;
125 }
126 
sensorManagerDied()127 void SensorManager::sensorManagerDied() {
128     Mutex::Autolock _l(mLock);
129     mSensorServer.clear();
130     free(mSensorList);
131     mSensorList = nullptr;
132     mSensors.clear();
133 }
134 
assertStateLocked()135 status_t SensorManager::assertStateLocked() {
136     bool initSensorManager = false;
137     if (mSensorServer == nullptr) {
138         initSensorManager = true;
139     } else {
140         // Ping binder to check if sensorservice is alive.
141         status_t err = IInterface::asBinder(mSensorServer)->pingBinder();
142         if (err != NO_ERROR) {
143             initSensorManager = true;
144         }
145     }
146     if (initSensorManager) {
147         waitForSensorService(&mSensorServer);
148         LOG_ALWAYS_FATAL_IF(mSensorServer == nullptr, "getService(SensorService) NULL");
149 
150         class DeathObserver : public IBinder::DeathRecipient {
151             SensorManager& mSensorManager;
152             virtual void binderDied(const wp<IBinder>& who) {
153                 ALOGW("sensorservice died [%p]", static_cast<void*>(who.unsafe_get()));
154                 mSensorManager.sensorManagerDied();
155             }
156         public:
157             explicit DeathObserver(SensorManager& mgr) : mSensorManager(mgr) { }
158         };
159 
160         mDeathObserver = new DeathObserver(*const_cast<SensorManager *>(this));
161         IInterface::asBinder(mSensorServer)->linkToDeath(mDeathObserver);
162 
163         mSensors = mSensorServer->getSensorList(mOpPackageName);
164         size_t count = mSensors.size();
165         mSensorList =
166                 static_cast<Sensor const**>(malloc(count * sizeof(Sensor*)));
167         LOG_ALWAYS_FATAL_IF(mSensorList == nullptr, "mSensorList NULL");
168 
169         for (size_t i=0 ; i<count ; i++) {
170             mSensorList[i] = mSensors.array() + i;
171         }
172     }
173 
174     return NO_ERROR;
175 }
176 
getSensorList(Sensor const * const ** list)177 ssize_t SensorManager::getSensorList(Sensor const* const** list) {
178     Mutex::Autolock _l(mLock);
179     status_t err = assertStateLocked();
180     if (err < 0) {
181         return static_cast<ssize_t>(err);
182     }
183     *list = mSensorList;
184     return static_cast<ssize_t>(mSensors.size());
185 }
186 
getDynamicSensorList(Vector<Sensor> & dynamicSensors)187 ssize_t SensorManager::getDynamicSensorList(Vector<Sensor> & dynamicSensors) {
188     Mutex::Autolock _l(mLock);
189     status_t err = assertStateLocked();
190     if (err < 0) {
191         return static_cast<ssize_t>(err);
192     }
193 
194     dynamicSensors = mSensorServer->getDynamicSensorList(mOpPackageName);
195     size_t count = dynamicSensors.size();
196 
197     return static_cast<ssize_t>(count);
198 }
199 
getDefaultSensor(int type)200 Sensor const* SensorManager::getDefaultSensor(int type)
201 {
202     Mutex::Autolock _l(mLock);
203     if (assertStateLocked() == NO_ERROR) {
204         bool wakeUpSensor = false;
205         // For the following sensor types, return a wake-up sensor. These types are by default
206         // defined as wake-up sensors. For the rest of the sensor types defined in sensors.h return
207         // a non_wake-up version.
208         if (type == SENSOR_TYPE_PROXIMITY || type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
209             type == SENSOR_TYPE_TILT_DETECTOR || type == SENSOR_TYPE_WAKE_GESTURE ||
210             type == SENSOR_TYPE_GLANCE_GESTURE || type == SENSOR_TYPE_PICK_UP_GESTURE ||
211             type == SENSOR_TYPE_WRIST_TILT_GESTURE ||
212             type == SENSOR_TYPE_LOW_LATENCY_OFFBODY_DETECT || type == SENSOR_TYPE_HINGE_ANGLE) {
213             wakeUpSensor = true;
214         }
215         // For now we just return the first sensor of that type we find.
216         // in the future it will make sense to let the SensorService make
217         // that decision.
218         for (size_t i=0 ; i<mSensors.size() ; i++) {
219             if (mSensorList[i]->getType() == type &&
220                 mSensorList[i]->isWakeUpSensor() == wakeUpSensor) {
221                 return mSensorList[i];
222             }
223         }
224     }
225     return nullptr;
226 }
227 
createEventQueue(String8 packageName,int mode,String16 attributionTag)228 sp<SensorEventQueue> SensorManager::createEventQueue(
229     String8 packageName, int mode, String16 attributionTag) {
230     sp<SensorEventQueue> queue;
231 
232     Mutex::Autolock _l(mLock);
233     while (assertStateLocked() == NO_ERROR) {
234         sp<ISensorEventConnection> connection = mSensorServer->createSensorEventConnection(
235             packageName, mode, mOpPackageName, attributionTag);
236         if (connection == nullptr) {
237             // SensorService just died or the app doesn't have required permissions.
238             ALOGE("createEventQueue: connection is NULL.");
239             return nullptr;
240         }
241         queue = new SensorEventQueue(connection);
242         break;
243     }
244     return queue;
245 }
246 
isDataInjectionEnabled()247 bool SensorManager::isDataInjectionEnabled() {
248     Mutex::Autolock _l(mLock);
249     if (assertStateLocked() == NO_ERROR) {
250         return mSensorServer->isDataInjectionEnabled();
251     }
252     return false;
253 }
254 
createDirectChannel(size_t size,int channelType,const native_handle_t * resourceHandle)255 int SensorManager::createDirectChannel(
256         size_t size, int channelType, const native_handle_t *resourceHandle) {
257     Mutex::Autolock _l(mLock);
258     if (assertStateLocked() != NO_ERROR) {
259         return NO_INIT;
260     }
261 
262     if (channelType != SENSOR_DIRECT_MEM_TYPE_ASHMEM
263             && channelType != SENSOR_DIRECT_MEM_TYPE_GRALLOC) {
264         ALOGE("Bad channel shared memory type %d", channelType);
265         return BAD_VALUE;
266     }
267 
268     sp<ISensorEventConnection> conn =
269               mSensorServer->createSensorDirectConnection(mOpPackageName,
270                   static_cast<uint32_t>(size),
271                   static_cast<int32_t>(channelType),
272                   SENSOR_DIRECT_FMT_SENSORS_EVENT, resourceHandle);
273     if (conn == nullptr) {
274         return NO_MEMORY;
275     }
276 
277     int nativeHandle = mDirectConnectionHandle++;
278     mDirectConnection.emplace(nativeHandle, conn);
279     return nativeHandle;
280 }
281 
destroyDirectChannel(int channelNativeHandle)282 void SensorManager::destroyDirectChannel(int channelNativeHandle) {
283     Mutex::Autolock _l(mLock);
284     if (assertStateLocked() == NO_ERROR) {
285         mDirectConnection.erase(channelNativeHandle);
286     }
287 }
288 
configureDirectChannel(int channelNativeHandle,int sensorHandle,int rateLevel)289 int SensorManager::configureDirectChannel(int channelNativeHandle, int sensorHandle, int rateLevel) {
290     Mutex::Autolock _l(mLock);
291     if (assertStateLocked() != NO_ERROR) {
292         return NO_INIT;
293     }
294 
295     auto i = mDirectConnection.find(channelNativeHandle);
296     if (i == mDirectConnection.end()) {
297         ALOGE("Cannot find the handle in client direct connection table");
298         return BAD_VALUE;
299     }
300 
301     int ret;
302     ret = i->second->configureChannel(sensorHandle, rateLevel);
303     ALOGE_IF(ret < 0, "SensorManager::configureChannel (%d, %d) returns %d",
304             static_cast<int>(sensorHandle), static_cast<int>(rateLevel),
305             static_cast<int>(ret));
306     return ret;
307 }
308 
setOperationParameter(int handle,int type,const Vector<float> & floats,const Vector<int32_t> & ints)309 int SensorManager::setOperationParameter(
310         int handle, int type,
311         const Vector<float> &floats, const Vector<int32_t> &ints) {
312     Mutex::Autolock _l(mLock);
313     if (assertStateLocked() != NO_ERROR) {
314         return NO_INIT;
315     }
316     return mSensorServer->setOperationParameter(handle, type, floats, ints);
317 }
318 
319 // ----------------------------------------------------------------------------
320 }; // namespace android
321