1 /*
2 * Copyright (c) 2022 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 "library_loader.h"
17
18 #include "common/log_wrapper.h"
19
20 #if defined(UNIX_PLATFORM)
21 #include <dlfcn.h>
22 #elif defined(WINDOWS_PLATFORM)
23 #include <windows.h>
24 #ifdef ERROR
25 #undef ERROR
26 #endif
27 #else
28 #error "Unsupported platform"
29 #endif
30
31 #include <string>
32
33 namespace OHOS::ArkCompiler::Toolchain {
34 #ifdef WINDOWS_PLATFORM
Load(std::string_view libraryName)35 void* Load(std::string_view libraryName)
36 {
37 HMODULE module = LoadLibrary(libraryName.data());
38 void* handle = reinterpret_cast<void*>(module);
39 if (handle != nullptr) {
40 return handle;
41 }
42
43 LOGE("Failed to open %{public}s, reason:%{public}sn", libraryName.data(),
44 std::to_string(GetLastError()).c_str());
45 return nullptr;
46 }
47
ResolveSymbol(void * handle,std::string_view symbol)48 void* ResolveSymbol(void* handle, std::string_view symbol)
49 {
50 HMODULE module = reinterpret_cast<HMODULE>(handle);
51 void* addr = reinterpret_cast<void*>(GetProcAddress(module, symbol.data()));
52 if (addr != nullptr) {
53 return addr;
54 }
55 LOGE("Failed to get symbol:%{public}s, reason:%{public}s", symbol.data(),
56 std::to_string(GetLastError()).c_str());
57 return nullptr;
58 }
59
CloseHandle(void * handle)60 void CloseHandle(void* handle)
61 {
62 if (handle != nullptr) {
63 FreeLibrary(reinterpret_cast<HMODULE>(handle));
64 }
65 }
66 #else // UNIX_PLATFORM
67 void* Load(std::string_view libraryName)
68 {
69 void* handle = dlopen(libraryName.data(), RTLD_LAZY);
70 if (handle != nullptr) {
71 return handle;
72 }
73 LOGE("Failed to open %{public}s, reason:%{public}sn", libraryName.data(), dlerror());
74 return nullptr;
75 }
76
77 void* ResolveSymbol(void* handle, std::string_view symbol)
78 {
79 void* addr = dlsym(handle, symbol.data());
80 if (addr != nullptr) {
81 return addr;
82 }
83 LOGE("Failed to get symbol:%{public}s, reason:%{public}sn", symbol.data(), dlerror());
84 return nullptr;
85 }
86
87 void CloseHandle(void* handle)
88 {
89 if (handle != nullptr) {
90 dlclose(handle);
91 }
92 }
93 #endif
94 }