ServiceManagement.cpp revision 7f49f59f349b9d097c6ab533b4a20090d0bc5740
1/*
2 * Copyright (C) 2016 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 "ServiceManagement"
18
19#include <condition_variable>
20#include <dlfcn.h>
21#include <dirent.h>
22#include <unistd.h>
23
24#include <mutex>
25#include <regex>
26
27#include <hidl/HidlBinderSupport.h>
28#include <hidl/ServiceManagement.h>
29#include <hidl/Static.h>
30#include <hidl/Status.h>
31
32#include <android-base/logging.h>
33#include <hidl-util/FQName.h>
34#include <hidl-util/StringHelper.h>
35#include <hwbinder/IPCThreadState.h>
36#include <hwbinder/Parcel.h>
37
38#include <android/hidl/manager/1.0/IServiceManager.h>
39#include <android/hidl/manager/1.0/BpHwServiceManager.h>
40#include <android/hidl/manager/1.0/BnHwServiceManager.h>
41
42#define RE_COMPONENT    "[a-zA-Z_][a-zA-Z_0-9]*"
43#define RE_PATH         RE_COMPONENT "(?:[.]" RE_COMPONENT ")*"
44static const std::regex gLibraryFileNamePattern("(" RE_PATH "@[0-9]+[.][0-9]+)-impl(.*?).so");
45
46using android::hidl::manager::V1_0::IServiceManager;
47using android::hidl::manager::V1_0::IServiceNotification;
48using android::hidl::manager::V1_0::BpHwServiceManager;
49using android::hidl::manager::V1_0::BnHwServiceManager;
50
51namespace android {
52namespace hardware {
53
54sp<IServiceManager> defaultServiceManager() {
55
56    if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
57    if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
58        // HwBinder not available on this device or not accessible to
59        // this process.
60        return nullptr;
61    }
62    {
63        AutoMutex _l(gDefaultServiceManagerLock);
64        while (gDefaultServiceManager == NULL) {
65            gDefaultServiceManager = fromBinder<IServiceManager, BpHwServiceManager, BnHwServiceManager>(
66                ProcessState::self()->getContextObject(NULL));
67            if (gDefaultServiceManager == NULL)
68                sleep(1);
69        }
70    }
71
72    return gDefaultServiceManager;
73}
74
75std::vector<std::string> search(const std::string &path,
76                              const std::string &prefix,
77                              const std::string &suffix) {
78    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
79    if (!dir) return {};
80
81    std::vector<std::string> results{};
82
83    dirent* dp;
84    while ((dp = readdir(dir.get())) != nullptr) {
85        std::string name = dp->d_name;
86
87        if (StringHelper::StartsWith(name, prefix) &&
88                StringHelper::EndsWith(name, suffix)) {
89            results.push_back(name);
90        }
91    }
92
93    return results;
94}
95
96bool matchPackageName(const std::string &lib, std::string *matchedName) {
97    std::smatch match;
98    if (std::regex_match(lib, match, gLibraryFileNamePattern)) {
99        *matchedName = match.str(1) + "::I*";
100        return true;
101    }
102    return false;
103}
104
105static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
106    sp<IServiceManager> binderizedManager = defaultServiceManager();
107    if (binderizedManager == nullptr) {
108        LOG(WARNING) << "Could not registerReference for "
109                     << interfaceName << "/" << instanceName
110                     << ": null binderized manager.";
111        return;
112    }
113    auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName, getpid());
114    if (!ret.isOk()) {
115        LOG(WARNING) << "Could not registerReference for "
116                     << interfaceName << "/" << instanceName
117                     << ": " << ret.description();
118    }
119    LOG(INFO) << "Successfully registerReference for "
120              << interfaceName << "/" << instanceName;
121}
122
123struct PassthroughServiceManager : IServiceManager {
124    Return<sp<IBase>> get(const hidl_string& fqName,
125                     const hidl_string& name) override {
126        FQName iface(fqName);
127
128        if (!iface.isValid() ||
129            !iface.isFullyQualified() ||
130            iface.isIdentifier()) {
131            LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
132            return nullptr;
133        }
134
135        const int dlMode = RTLD_LAZY;
136        void *handle = nullptr;
137
138        std::string library;
139
140        // TODO: lookup in VINTF instead
141        // TODO(b/34135607): Remove HAL_LIBRARY_PATH_SYSTEM
142
143        for (const std::string &path : {
144            HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, HAL_LIBRARY_PATH_SYSTEM
145        }) {
146            const std::string prefix = iface.getPackageAndVersion().string() + "-impl";
147
148            std::vector<std::string> libs = search(path, prefix, ".so");
149
150            if (libs.size() > 1) {
151                LOG(WARNING) << "Multiple libraries found: " << StringHelper::JoinStrings(libs, ", ");
152            }
153
154            for (const std::string &lib : libs) {
155                handle = dlopen((path + lib).c_str(), dlMode);
156                if (handle != nullptr) {
157                    library = lib;
158                    goto beginLookup;
159                }
160            }
161        }
162
163        if (handle == nullptr) {
164            return nullptr;
165        }
166beginLookup:
167
168        const std::string sym = "HIDL_FETCH_" + iface.name();
169
170        IBase* (*generator)(const char* name);
171        *(void **)(&generator) = dlsym(handle, sym.c_str());
172        if(!generator) {
173            LOG(ERROR) << "Passthrough lookup opened " << library
174                       << " but could not find symbol " << sym;
175            return nullptr;
176        }
177
178        registerReference(fqName, name);
179
180        return (*generator)(name);
181    }
182
183    Return<bool> add(const hidl_vec<hidl_string>& /* interfaceChain */,
184                     const hidl_string& /* name */,
185                     const sp<IBase>& /* service */) override {
186        LOG(FATAL) << "Cannot register services with passthrough service manager.";
187        return false;
188    }
189
190    Return<void> list(list_cb _hidl_cb) override {
191        std::vector<hidl_string> vec;
192        for (const std::string &path : {
193            HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, HAL_LIBRARY_PATH_SYSTEM
194        }) {
195            std::vector<std::string> libs = search(path, "", ".so");
196            for (const std::string &lib : libs) {
197                std::string matchedName;
198                if (matchPackageName(lib, &matchedName)) {
199                    vec.push_back(matchedName + "/*");
200                }
201            }
202        }
203        _hidl_cb(vec);
204        return Void();
205    }
206    Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
207                                 listByInterface_cb /* _hidl_cb */) override {
208        // TODO: add this functionality
209        LOG(FATAL) << "Cannot list services with passthrough service manager.";
210        return Void();
211    }
212
213    Return<bool> registerForNotifications(const hidl_string& /* fqName */,
214                                          const hidl_string& /* name */,
215                                          const sp<IServiceNotification>& /* callback */) override {
216        // This makes no sense.
217        LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
218        return false;
219    }
220
221    Return<void> debugDump(debugDump_cb) override {
222        // This makes no sense.
223        LOG(FATAL) << "Cannot call debugDump on passthrough service manager."
224                   << "Call it on defaultServiceManager() instead.";
225        return Void();
226    }
227
228    Return<void> registerPassthroughClient(const hidl_string &, const hidl_string &, int32_t) override {
229        // This makes no sense.
230        LOG(FATAL) << "Cannot call registerPassthroughClient on passthrough service manager. "
231                   << "Call it on defaultServiceManager() instead.";
232        return Void();
233    }
234
235};
236
237sp<IServiceManager> getPassthroughServiceManager() {
238    static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
239    return manager;
240}
241
242namespace details {
243
244struct Waiter : IServiceNotification {
245    Return<void> onRegistration(const hidl_string& /* fqName */,
246                                const hidl_string& /* name */,
247                                bool /* preexisting */) override {
248        std::unique_lock<std::mutex> lock(mMutex);
249        if (mRegistered) {
250            return Void();
251        }
252        mRegistered = true;
253        lock.unlock();
254
255        mCondition.notify_one();
256        return Void();
257    }
258
259    void wait() {
260        std::unique_lock<std::mutex> lock(mMutex);
261        mCondition.wait(lock, [this]{
262            return mRegistered;
263        });
264    }
265
266private:
267    std::mutex mMutex;
268    std::condition_variable mCondition;
269    bool mRegistered = false;
270};
271
272void waitForHwService(
273        const std::string &interface, const std::string &instanceName) {
274    const sp<IServiceManager> manager = defaultServiceManager();
275
276    if (manager == nullptr) {
277        LOG(ERROR) << "Could not get default service manager.";
278        return;
279    }
280
281    sp<Waiter> waiter = new Waiter();
282    Return<bool> ret = manager->registerForNotifications(interface, instanceName, waiter);
283
284    if (!ret.isOk()) {
285        LOG(ERROR) << "Transport error, " << ret.description()
286            << ", during notification registration for "
287            << interface << "/" << instanceName << ".";
288        return;
289    }
290
291    if (!ret) {
292        LOG(ERROR) << "Could not register for notifications for "
293            << interface << "/" << instanceName << ".";
294        return;
295    }
296
297    waiter->wait();
298}
299
300}; // namespace details
301
302}; // namespace hardware
303}; // namespace android
304