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