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 "plugin_lib.h"
17 
18 #include <dlfcn.h>
19 #include <filesystem>
20 #include <string>
21 
22 #include "avsession_log.h"
23 
24 namespace OHOS::AVSession {
25 
PluginLib(const std::string & libName)26 PluginLib::PluginLib(const std::string &libName)
27     : libName_(GetRealPath(libName)), handle_(nullptr)
28 {
29     if (!CheckPathExist(libName_)) {
30         SLOGE("%{public}s path invalid", libName_.c_str());
31         return;
32     }
33     handle_ = dlopen(libName_.c_str(), RTLD_NOW);
34     if (handle_ == nullptr) {
35         LogDlfcnErr("open lib failed");
36     return;
37 }
38 SLOGI("%{public}s open succ", libName_.c_str());
39 }
40 
~PluginLib()41 PluginLib::~PluginLib()
42 {
43 #ifndef TEST_COVERAGE
44     if (handle_ == nullptr || dlclose(handle_) != 0) {
45         LogDlfcnErr("close lib failed");
46     }
47 #endif
48     SLOGI("%{public}s close succ", libName_.c_str());
49 }
50 
LoadSymbol(const std::string & symbolName)51 void *PluginLib::LoadSymbol(const std::string &symbolName)
52 {
53     if (handle_ == nullptr) {
54         SLOGE("%{public}s lib is null", libName_.c_str());
55     return nullptr;
56     }
57     void *sym = dlsym(handle_, symbolName.c_str());
58     if (sym == nullptr) {
59         LogDlfcnErr("load symbol [" + symbolName + "] failed");
60         return nullptr;
61     }
62     SLOGI("%{public}s load symbol succ", symbolName.c_str());
63     return sym;
64 }
65 
LogDlfcnErr(const std::string & desc)66 void PluginLib::LogDlfcnErr(const std::string &desc)
67 {
68     SLOGE("[%{public}s] %{public}s, reason = %{public}s",
69         libName_.c_str(), desc.c_str(), dlerror());
70     // reset errors
71     dlerror();
72 }
73 
GetRealPath(const std::string & path)74 std::string PluginLib::GetRealPath(const std::string &path)
75 {
76     auto realPath = std::filesystem::weakly_canonical(path);
77     return realPath.string();
78 }
79 
CheckPathExist(const std::string & path)80 bool PluginLib::CheckPathExist(const std::string &path)
81 {
82     return std::filesystem::exists(path);
83 }
84 
85 }   // namespace OHOS::AVSession