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