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