1 /*
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "os_account_plugin_manager.h"
17 #include <chrono>
18 #include <dlfcn.h>
19 #include <unistd.h>
20 #include <future>
21 #include <pthread.h>
22 #include <thread>
23
24 namespace OHOS {
25 namespace AccountSA {
26
~OsAccountPluginManager()27 OsAccountPluginManager::~OsAccountPluginManager()
28 {
29 CloseLib();
30 }
31
LoaderLib(const std::string & path,const std::string & libName)32 void OsAccountPluginManager::LoaderLib(const std::string &path, const std::string &libName)
33 {
34 if (IsPluginAvailable()) {
35 ACCOUNT_LOGE("LibHandle_ is not nullptr.");
36 return;
37 }
38 std::lock_guard<std::mutex> lock(libMutex_);
39 std::string soPath = path + libName;
40 libHandle_ = dlopen(soPath.c_str(), RTLD_LAZY);
41 if (libHandle_ == nullptr) {
42 ACCOUNT_LOGE("Call dlopen failed, error=%{public}s.", dlerror());
43 return;
44 }
45 for (size_t i = 0; i < funcSymbolList_.size(); i++) {
46 std::string methodName = funcSymbolList_[i];
47 if (methodName.empty()) {
48 ACCOUNT_LOGE("Call check methodName empty.");
49 dlclose(libHandle_);
50 libHandle_ = nullptr;
51 methodMap_.clear();
52 return;
53 }
54 dlerror();
55 void *func = dlsym(libHandle_, methodName.c_str());
56 if (func == nullptr) {
57 ACCOUNT_LOGE("Call check failed, method=%{public}s error=%{public}s.", methodName.c_str(), dlerror());
58 dlclose(libHandle_);
59 libHandle_ = nullptr;
60 methodMap_.clear();
61 return;
62 }
63 methodMap_.emplace(methodName, func);
64 }
65 ACCOUNT_LOGI("Load library success.");
66 }
67
CloseLib()68 void OsAccountPluginManager::CloseLib()
69 {
70 std::lock_guard<std::mutex> lock(libMutex_);
71 if (libHandle_ == nullptr) {
72 ACCOUNT_LOGE("LibHandle_ is nullptr.");
73 return;
74 }
75 dlclose(libHandle_);
76 libHandle_ = nullptr;
77 }
78
IsPluginAvailable()79 bool OsAccountPluginManager::IsPluginAvailable()
80 {
81 std::lock_guard<std::mutex> lock(libMutex_, std::adopt_lock);
82 return libHandle_ != nullptr;
83 }
84 } // namespace AccountSA
85 } // namespace OHOS