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 interfaces_.insert(std::make_pair(s, nullptr));
32 }
33 }
34
~InterfaceLoader()35 InterfaceLoader::~InterfaceLoader() noexcept
36 {
37 DeInit();
38 }
39
Init()40 bool InterfaceLoader::Init()
41 {
42 bool ret = LoadAllInterfaces();
43 POWER_HILOGI(COMP_SVC, "Interface loading result: %{public}u", static_cast<uint32_t>(ret));
44 if (ret) {
45 isInited_ = true;
46 }
47 return ret;
48 }
49
DeInit()50 void InterfaceLoader::DeInit()
51 {
52 if (isInited_) {
53 isInited_ = false;
54 interfaces_.clear();
55 }
56 }
57
QueryInterface(const std::string & symbol) const58 void* InterfaceLoader::QueryInterface(const std::string& symbol) const
59 {
60 if (!isInited_) {
61 POWER_HILOGE(COMP_SVC, "Interface not loading or loading failed");
62 return nullptr;
63 }
64 auto iter = interfaces_.find(symbol);
65 if (iter == interfaces_.end()) {
66 return nullptr;
67 }
68 return iter->second;
69 }
70
LoadAllInterfaces()71 bool InterfaceLoader::LoadAllInterfaces()
72 {
73 void* curFunc = nullptr;
74 for (auto iter = interfaces_.begin(); iter != interfaces_.end(); ++iter) {
75 curFunc = LoadInterface(iter->first.c_str());
76 if (curFunc == nullptr) {
77 return false;
78 }
79 iter->second = curFunc;
80 }
81 return true;
82 }
83
84 } // namespace PowerMgr
85 } // namespace OHOS