1 /*
2 * Copyright (c) 2024-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 "interface_loader.h"
17 #include "power_log.h"
18
19 namespace OHOS {
20 namespace PowerMgr {
21 static constexpr uint32_t MAX_INTERFACE_COUNT = 128;
22
InterfaceLoader(const std::string & libPath,const std::vector<std::string> & symbolArr)23 InterfaceLoader::InterfaceLoader(const std::string& libPath, const std::vector<std::string>& symbolArr)
24 : LibraryLoader(libPath)
25 {
26 if (symbolArr.size() > MAX_INTERFACE_COUNT) {
27 POWER_HILOGE(COMP_SVC, "Symbol count is invalid");
28 return;
29 }
30 for (const std::string& s : symbolArr) {
31 POWER_HILOGE(COMP_SVC, "InterfaceLoader add symbol: %{public}s", s.c_str());
32 interfaces_.insert(std::make_pair(s, nullptr));
33 }
34 }
35
~InterfaceLoader()36 InterfaceLoader::~InterfaceLoader() noexcept
37 {
38 POWER_HILOGI(COMP_SVC, "InterfaceLoader instance destroyed");
39 }
40
Init()41 bool InterfaceLoader::Init()
42 {
43 std::unique_lock lock(shMutex_);
44 if (isInited_) {
45 POWER_HILOGW(COMP_SVC, "Interface already loaded");
46 return true;
47 }
48 bool ret = LoadAllInterfaces();
49 POWER_HILOGI(COMP_SVC, "Interface loading result: %{public}u", static_cast<uint32_t>(ret));
50 if (ret) {
51 isInited_ = true;
52 }
53 return ret;
54 }
55
DeInit()56 void InterfaceLoader::DeInit()
57 {
58 std::unique_lock lock(shMutex_);
59 if (isInited_) {
60 isInited_ = false;
61 interfaces_.clear();
62 }
63 }
64
QueryInterface(const std::string & symbol) const65 void* InterfaceLoader::QueryInterface(const std::string& symbol) const
66 {
67 std::shared_lock lock(shMutex_);
68 if (!isInited_) {
69 POWER_HILOGE(COMP_SVC, "Interface not loading or loading failed");
70 return nullptr;
71 }
72 auto iter = interfaces_.find(symbol);
73 if (iter == interfaces_.end() || iter->second == nullptr) {
74 POWER_HILOGE(COMP_SVC, "%{public}s symbol not found", symbol.c_str());
75 return nullptr;
76 }
77 return iter->second;
78 }
79
LoadAllInterfaces()80 bool InterfaceLoader::LoadAllInterfaces()
81 {
82 void* curFunc = nullptr;
83 for (auto iter = interfaces_.begin(); iter != interfaces_.end(); ++iter) {
84 curFunc = LoadInterface(iter->first.c_str());
85 if (curFunc != nullptr) {
86 iter->second = curFunc;
87 }
88 }
89 return true;
90 }
91
92 } // namespace PowerMgr
93 } // namespace OHOS