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 }
33 
LoadLib()34 ErrorCode LibLoader::LoadLib()
35 {
36     LOGI("LoadLib start");
37     std::string realPath;
38     if (!PathToRealPath(m_libPath, realPath) || realPath.find("/system/lib") != 0) {
39         LOGE("LoadLib m_libPath error, realPath: %{public}s", realPath.c_str());
40         return RET_DLOPEN_LIB_FAIL;
41     }
42     m_handle = dlopen(realPath.c_str(), RTLD_LAZY);
43     if (m_handle == nullptr) {
44         LOGE("LoadLib m_handle error");
45         return RET_DLOPEN_LIB_FAIL;
46     }
47     LOGI("dlopen success");
48     return SUCCESS;
49 }
50 
UnLoadLib()51 void LibLoader::UnLoadLib()
52 {
53     LOGI("UnLoadLib start");
54     if (m_handle != nullptr) {
55         dlclose(m_handle);
56     }
57     // should call dlclose(m_handle)
58     LOGI("dlclose end");
59     m_handle = nullptr;
60 }
61 
CallGetCollector()62 ICollector* LibLoader::CallGetCollector()
63 {
64     LOGI("CallGetCollector start");
65     if (m_handle == nullptr) {
66         LOGE("lib not found");
67         return nullptr;
68     }
69     typedef ICollector* (*GetCollectorFunc)();
70     GetCollectorFunc getCollector = reinterpret_cast<GetCollectorFunc>(dlsym(m_handle, "GetCollector"));
71     if (!getCollector) {
72         LOGE("Failed to get GetCollector function");
73         return nullptr;
74     }
75     return getCollector();
76 }
77 }