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 "libraryloader.h"
17
18 #include <dlfcn.h>
19 #include <string>
20
21 #include "accesstoken_common_log.h"
22
23 namespace OHOS {
24 namespace Security {
25 namespace AccessToken {
26 namespace {
27 typedef void* (*FUNC_CREATE) (void);
28 typedef void (*FUNC_DESTROY) (void*);
29 }
30
LibraryLoader(const std::string & path)31 LibraryLoader::LibraryLoader(const std::string& path)
32 {
33 handle_ = dlopen(path.c_str(), RTLD_LAZY);
34 if (handle_ == nullptr) {
35 PrintErrorLog(path);
36 return;
37 }
38 Create();
39 }
40
~LibraryLoader()41 LibraryLoader::~LibraryLoader()
42 {
43 if (instance_ != nullptr) {
44 Destroy();
45 }
46 #ifndef FUZZ_ENABLE
47 if (handle_ != nullptr) {
48 dlclose(handle_);
49 handle_ = nullptr;
50 }
51 #endif // FUZZ_ENABLE
52 }
53
PrintErrorLog(const std::string & targetName)54 bool LibraryLoader::PrintErrorLog(const std::string& targetName)
55 {
56 char* error;
57 if ((error = dlerror()) != nullptr) {
58 LOGE(ATM_DOMAIN, ATM_TAG, "Get %{public}s failed, errMsg=%{public}s.",
59 targetName.c_str(), error);
60 return false;
61 }
62 return true;
63 }
64
Create()65 void LibraryLoader::Create()
66 {
67 void* (*create)(void) = reinterpret_cast<FUNC_CREATE>(dlsym(handle_, "Create"));
68 if (!PrintErrorLog("Create")) {
69 return;
70 }
71 instance_ = create();
72 }
73
Destroy()74 void LibraryLoader::Destroy()
75 {
76 void (*destroy)(void*) = reinterpret_cast<FUNC_DESTROY>(dlsym(handle_, "Destroy"));
77 if (!PrintErrorLog("Destroy")) {
78 return;
79 }
80 destroy(instance_);
81 instance_ = nullptr;
82 }
83 } // AccessToken
84 } // Security
85 } // OHOS