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 "os/library_loader.h"
17
18 #include <windows.h>
19
20 namespace panda::os::library_loader {
Load(std::string_view filename)21 Expected<LibraryHandle, Error> Load(std::string_view filename)
22 {
23 HMODULE module = LoadLibrary(filename.data());
24 void *handle = reinterpret_cast<void *>(module);
25 if (handle != nullptr) {
26 return LibraryHandle(handle);
27 }
28 return Unexpected(Error(std::string("Failed to load library ") + filename.data() + std::string(", error code ") +
29 std::to_string(GetLastError())));
30 }
31
ResolveSymbol(const LibraryHandle &handle, std::string_view name)32 Expected<void *, Error> ResolveSymbol(const LibraryHandle &handle, std::string_view name)
33 {
34 HMODULE module = reinterpret_cast<HMODULE>(handle.GetNativeHandle());
35 void *p = reinterpret_cast<void *>(GetProcAddress(module, name.data()));
36 if (p != nullptr) {
37 return p;
38 }
39 return Unexpected(Error(std::string("Failed to resolve symbol ") + name.data() + std::string(", error code ") +
40 std::to_string(GetLastError())));
41 }
42
CloseHandle(void *handle)43 void CloseHandle(void *handle)
44 {
45 if (handle != nullptr) {
46 FreeLibrary(reinterpret_cast<HMODULE>(handle));
47 }
48 }
49 } // namespace panda::os::library_loader
50