• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 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 "wifi_library_utils.h"
17 #include <dlfcn.h>
18 #include "wifi_logger.h"
19 namespace OHOS {
20 namespace Wifi {
21 DEFINE_WIFILOG_LABEL("WifiLibraryUtils");
WifiLibraryUtils(const std::string & libName,void * & libHandle,bool isDlClose)22 WifiLibraryUtils::WifiLibraryUtils(const std::string &libName, void*& libHandle, bool isDlClose)
23     : libHandle_(libHandle), libName_(libName), isDlClose_(isDlClose)
24 {
25     if (libName.empty()) {
26         return;
27     }
28     if (libHandle_ != nullptr) {
29         WIFI_LOGD("Library %s has been loaded", libName.c_str());
30         return;
31     }
32     libHandle_ = dlopen(libName.c_str(), RTLD_LAZY);
33     if (libHandle_ == nullptr) {
34         WIFI_LOGE("Failed to load library %s, error: %s", libName.c_str(), dlerror());
35     } else {
36         WIFI_LOGI("Library %s loaded successfully", libName.c_str());
37     }
38 }
39 
~WifiLibraryUtils()40 WifiLibraryUtils::~WifiLibraryUtils()
41 {
42     if (isDlClose_ && libHandle_ != nullptr) {
43         if (dlclose(libHandle_) != 0) {
44             WIFI_LOGE("Failed to close library %s, error: %s", libName_.c_str(), dlerror());
45         } else {
46             WIFI_LOGI("Library %s closed successfully", libName_.c_str());
47         }
48         libHandle_ = nullptr;
49     }
50 }
51 
GetFunction(const std::string & funcName)52 void* WifiLibraryUtils::GetFunction(const std::string &funcName)
53 {
54     if (libHandle_ == nullptr) {
55         WIFI_LOGE("Library %s is not loaded", libName_.c_str());
56         return nullptr;
57     }
58     void *func = dlsym(libHandle_, funcName.c_str());
59     if (func == nullptr) {
60         WIFI_LOGE("Failed to get function %s from library %s, error: %s",
61             funcName.c_str(), libName_.c_str(), dlerror());
62     }
63     return func;
64 }
65 } // namespace Wifi
66 } // namespace OHOS