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 "func_loader.h"
17
18 #include <climits>
19 #include <cstdio>
20 #include <cstdlib>
21 #include <cstring>
22 #include <dlfcn.h>
23 #include <unistd.h>
24
25 #include "concurrent_task_log.h"
26
27 namespace OHOS {
28 namespace ConcurrentTask {
FuncLoader(const std::string & funcImplPath)29 FuncLoader::FuncLoader(const std::string& funcImplPath) : funcImplPath_(funcImplPath)
30 {
31 LoadFile(funcImplPath_.c_str());
32 }
33
~FuncLoader()34 FuncLoader::~FuncLoader()
35 {
36 if (fileHandle_ != nullptr) {
37 dlclose(fileHandle_);
38 }
39 fileHandle_ = nullptr;
40 }
41
LoadFile(const char * fileName)42 void FuncLoader::LoadFile(const char* fileName)
43 {
44 if (!fileName || strlen(fileName) == 0 || strlen(fileName) > PATH_MAX) {
45 CONCUR_LOGE("%{public}s, load file fail", __func__);
46 return;
47 }
48 const char* preFix = "lib";
49 if (strncmp(fileName, preFix, strlen(preFix)) != 0) {
50 CONCUR_LOGE("invailed fileName!");
51 return;
52 }
53 fileHandle_ = dlopen(fileName, RTLD_LAZY);
54 if (fileHandle_ == nullptr) {
55 enable_ = false;
56 CONCUR_LOGE("dlopen fail");
57 return;
58 }
59 CONCUR_LOGD("%{public}s, load file success", __func__);
60 enable_ = true;
61 }
62
LoadSymbol(const char * sysName)63 void* FuncLoader::LoadSymbol(const char* sysName)
64 {
65 if (!enable_) {
66 return nullptr;
67 }
68 void* funcSym = dlsym(fileHandle_, sysName);
69 if (funcSym == nullptr) {
70 CONCUR_LOGE("dlsym func %{public}s fail", sysName);
71 enable_ = false;
72 return nullptr;
73 }
74 CONCUR_LOGD("dlsym func %{public}s success", sysName);
75 return funcSym;
76 }
77
GetLoadSuccess()78 bool FuncLoader::GetLoadSuccess()
79 {
80 return enable_;
81 }
82
83 } // namespace ConcurrentTask
84 } // namespace OHOS