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 "library_loader.h"
17 #include "power_log.h"
18 
19 namespace OHOS {
20 namespace PowerMgr {
21 static constexpr uint32_t FAILURE_RETRY_TIMES = 3;
22 
LibraryLoader(const std::string & libPath,int32_t flags)23 LibraryLoader::LibraryLoader(const std::string& libPath, int32_t flags) : libPath_(libPath)
24 {
25     for (uint32_t i = 0; i < FAILURE_RETRY_TIMES; ++i) {
26         libHandle_ = dlopen(libPath.c_str(), flags);
27         if (libHandle_ != nullptr) {
28             return;
29         }
30         POWER_HILOGE(COMP_SVC, "Failed to dlopen %{public}s, reason: %{public}s, try again(%{public}u)",
31             libPath_.c_str(), dlerror(), i + 1);
32     }
33 }
34 
~LibraryLoader()35 LibraryLoader::~LibraryLoader() noexcept
36 {
37     if (libHandle_ == nullptr) {
38         return;
39     }
40     for (uint32_t i = 0; i < FAILURE_RETRY_TIMES; ++i) {
41         int32_t ret = dlclose(libHandle_);
42         if (ret == 0) {
43             break;
44         }
45         POWER_HILOGE(COMP_SVC, "Failed to dlclose %{public}s, reason: %{public}s, try again(%{public}u)",
46             libPath_.c_str(), dlerror(), i + 1);
47     }
48     libHandle_ = nullptr;
49 }
50 
LoadInterface(const char * symbolName)51 void* LibraryLoader::LoadInterface(const char* symbolName)
52 {
53     if (libHandle_ == nullptr || symbolName == nullptr) {
54         POWER_HILOGE(COMP_SVC, "library handle or symbol name is invalid");
55         return nullptr;
56     }
57     for (uint32_t i = 0; i < FAILURE_RETRY_TIMES; ++i) {
58         void* funcPtr = dlsym(libHandle_, symbolName);
59         if (funcPtr != nullptr) {
60             return funcPtr;
61         }
62         POWER_HILOGE(COMP_SVC, "Failed to dlsym %{public}s, reason: %{public}s, try again(%{public}u)", symbolName,
63             dlerror(), i + 1);
64     }
65     return nullptr;
66 }
67 
68 } // namespace PowerMgr
69 } // namespace OHOS