1 /*
2 * Copyright (c) 2023 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 "lib_loader.h"
17
18 #include <dlfcn.h>
19 #include <string>
20
21 #include "directory_ex.h"
22 #include "security_collector_log.h"
23
24 namespace OHOS::Security::SecurityCollector {
LibLoader(const std::string soPath)25 LibLoader::LibLoader(const std::string soPath)
26 : m_libPath(soPath)
27 {
28 }
29
~LibLoader()30 LibLoader::~LibLoader()
31 {
32 UnLoadLib();
33 }
34
LoadLib()35 ErrorCode LibLoader::LoadLib()
36 {
37 LOGI("LoadLib start");
38 std::string realPath;
39 if (!PathToRealPath(m_libPath, realPath) || realPath.find("/system/lib") != 0) {
40 LOGE("LoadLib m_libPath error, realPath: %{public}s", realPath.c_str());
41 m_isLoaded = false;
42 return RET_DLOPEN_LIB_FAIL;
43 }
44 m_handle = dlopen(realPath.c_str(), RTLD_LAZY);
45 if (m_handle == nullptr) {
46 LOGE("LoadLib m_handle error");
47 m_isLoaded = false;
48 return RET_DLOPEN_LIB_FAIL;
49 }
50 LOGI("dlopen success");
51 m_isLoaded = true;
52 return SUCCESS;
53 }
54
UnLoadLib()55 void LibLoader::UnLoadLib()
56 {
57 LOGI("UnLoadLib start");
58 if (!m_isLoaded) {
59 LOGI("lib not found");
60 return;
61 }
62 // should call dlclose(m_handle)
63 LOGI("dlclose end");
64 m_handle = nullptr;
65 m_isLoaded = false;
66 }
67
CallGetCollector()68 ICollector* LibLoader::CallGetCollector()
69 {
70 LOGI("CallGetCollector start");
71 if (!m_isLoaded) {
72 LOGE("lib not found");
73 return nullptr;
74 }
75 typedef ICollector* (*GetCollectorFunc)();
76 GetCollectorFunc getCollector = reinterpret_cast<GetCollectorFunc>(dlsym(m_handle, "GetCollector"));
77 if (!getCollector) {
78 LOGE("Failed to get GetCollector function");
79 return nullptr;
80 }
81 return getCollector();
82 }
83 }