ServiceManagement.cpp revision 9a22d1db4dca94f205e25105a3d822dd179d3b53
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
105struct PassthroughServiceManager : IServiceManager {
106    Return<sp<IBase>> get(const hidl_string& fqName,
107                     const hidl_string& name) override {
108        FQName iface(fqName);
109
110        if (!iface.isValid() ||
111            !iface.isFullyQualified() ||
112            iface.isIdentifier()) {
113            LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
114            return nullptr;
115        }
116
117        const int dlMode = RTLD_LAZY;
118        void *handle = nullptr;
119
120        std::string library;
121
122        // TODO: lookup in VINTF instead
123        // TODO(b/34135607): Remove HAL_LIBRARY_PATH_SYSTEM
124
125        for (const std::string &path : {
126            HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, HAL_LIBRARY_PATH_SYSTEM
127        }) {
128            const std::string prefix = iface.getPackageAndVersion().string() + "-impl";
129
130            std::vector<std::string> libs = search(path, prefix, ".so");
131
132            if (libs.size() > 1) {
133                LOG(WARNING) << "Multiple libraries found: " << StringHelper::JoinStrings(libs, ", ");
134            }
135
136            for (const std::string &lib : libs) {
137                handle = dlopen((path + lib).c_str(), dlMode);
138                if (handle != nullptr) {
139                    library = lib;
140                    goto beginLookup;
141                }
142            }
143        }
144
145        if (handle == nullptr) {
146            return nullptr;
147        }
148beginLookup:
149
150        const std::string sym = "HIDL_FETCH_" + iface.name();
151
152        IBase* (*generator)(const char* name);
153        *(void **)(&generator) = dlsym(handle, sym.c_str());
154        if(!generator) {
155            LOG(ERROR) << "Passthrough lookup opened " << library
156                       << " but could not find symbol " << sym;
157            return nullptr;
158        }
159        return (*generator)(name);
160    }
161
162    Return<bool> add(const hidl_vec<hidl_string>& /* interfaceChain */,
163                     const hidl_string& /* name */,
164                     const sp<IBase>& /* service */) override {
165        LOG(FATAL) << "Cannot register services with passthrough service manager.";
166        return false;
167    }
168
169    Return<void> list(list_cb /* _hidl_cb */) override {
170        // TODO: add this functionality
171        LOG(FATAL) << "Cannot list services with passthrough service manager.";
172        return Void();
173    }
174    Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
175                                 listByInterface_cb /* _hidl_cb */) override {
176        // TODO: add this functionality
177        LOG(FATAL) << "Cannot list services with passthrough service manager.";
178        return Void();
179    }
180
181    Return<bool> registerForNotifications(const hidl_string& /* fqName */,
182                                          const hidl_string& /* name */,
183                                          const sp<IServiceNotification>& /* callback */) override {
184        // This makes no sense.
185        LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
186        return false;
187    }
188
189    Return<void> debugDump(debugDump_cb _cb) override {
190        std::vector<InstanceDebugInfo> vec;
191        for (const std::string &path : {
192            HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, HAL_LIBRARY_PATH_SYSTEM
193        }) {
194            std::vector<std::string> libs = search(path, "", ".so");
195            for (const std::string &lib : libs) {
196                std::string matchedName;
197                if (matchPackageName(lib, &matchedName)) {
198                    vec.push_back({
199                        .interfaceName = matchedName,
200                        .instanceName = "",
201                        .refCount = 0,
202                    });
203                }
204            }
205        }
206        _cb(vec);
207        return Void();
208    }
209
210};
211
212sp<IServiceManager> getPassthroughServiceManager() {
213    static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
214    return manager;
215}
216
217namespace details {
218
219struct Waiter : IServiceNotification {
220    Return<void> onRegistration(const hidl_string& /* fqName */,
221                                const hidl_string& /* name */,
222                                bool /* preexisting */) override {
223        std::unique_lock<std::mutex> lock(mMutex);
224        if (mRegistered) {
225            return Void();
226        }
227        mRegistered = true;
228        lock.unlock();
229
230        mCondition.notify_one();
231        return Void();
232    }
233
234    void wait() {
235        std::unique_lock<std::mutex> lock(mMutex);
236        mCondition.wait(lock, [this]{
237            return mRegistered;
238        });
239    }
240
241private:
242    std::mutex mMutex;
243    std::condition_variable mCondition;
244    bool mRegistered = false;
245};
246
247void waitForHwService(
248        const std::string &interface, const std::string &instanceName) {
249    const sp<IServiceManager> manager = defaultServiceManager();
250
251    if (manager == nullptr) {
252        LOG(ERROR) << "Could not get default service manager.";
253        return;
254    }
255
256    sp<Waiter> waiter = new Waiter();
257    Return<bool> ret = manager->registerForNotifications(interface, instanceName, waiter);
258
259    if (!ret.isOk()) {
260        LOG(ERROR) << "Transport error, " << ret.description()
261            << ", during notification registration for "
262            << interface << "/" << instanceName << ".";
263        return;
264    }
265
266    if (!ret) {
267        LOG(ERROR) << "Could not register for notifications for "
268            << interface << "/" << instanceName << ".";
269        return;
270    }
271
272    waiter->wait();
273}
274
275}; // namespace details
276
277}; // namespace hardware
278}; // namespace android
279