• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 void 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.", targetName.c_str(), error);
59     }
60 }
61 
Create()62 void LibraryLoader::Create()
63 {
64     void* (*create)(void) = reinterpret_cast<FUNC_CREATE>(dlsym(handle_, "Create"));
65     if (create == nullptr) {
66         PrintErrorLog("Create");
67         return;
68     }
69     instance_ = create();
70 }
71 
Destroy()72 void LibraryLoader::Destroy()
73 {
74     void (*destroy)(void*) = reinterpret_cast<FUNC_DESTROY>(dlsym(handle_, "Destroy"));
75     if (destroy == nullptr) {
76         PrintErrorLog("Destroy");
77         return;
78     }
79     destroy(instance_);
80     instance_ = nullptr;
81 }
82 } // AccessToken
83 } // Security
84 } // OHOS