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 "library_windows.h"
17
18 #pragma warning(push)
19 // C5039 'function': pointer or reference to potentially throwing function passed to extern C function under -EHc.
20 // Undefined behavior may occur if this function throws an exception.
21 #pragma warning(disable : 5039)
22 #include <windows.h>
23 #pragma warning(pop)
24
25 #include <base/containers/iterator.h>
26 #include <base/containers/string.h>
27 #include <base/containers/string_view.h>
28 #include <base/namespace.h>
29 #include <core/log.h>
30 #include <core/namespace.h>
31
32 CORE_BEGIN_NAMESPACE()
33 using BASE_NS::string;
34 using BASE_NS::string_view;
35
LibraryWindows(const string_view filename)36 LibraryWindows::LibraryWindows(const string_view filename)
37 {
38 string tmp(filename);
39 // fix the slashes. (without the correct backslashes the LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR wont work)
40 for (auto& t : tmp) {
41 if (t == '/') {
42 t = '\\';
43 }
44 }
45 libraryHandle_ =
46 LoadLibraryEx(tmp.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
47 if (!libraryHandle_) {
48 DWORD errorCode = GetLastError();
49 CORE_LOG_E("Loading dynamic library '%s' failed: 0x%lx", tmp.c_str(), errorCode);
50 }
51 }
52
~LibraryWindows()53 LibraryWindows::~LibraryWindows()
54 {
55 if (libraryHandle_) {
56 FreeLibrary(libraryHandle_);
57 libraryHandle_ = nullptr;
58 }
59 }
60
GetPlugin() const61 IPlugin* LibraryWindows::GetPlugin() const
62 {
63 if (!libraryHandle_) {
64 return nullptr;
65 }
66
67 return reinterpret_cast<IPlugin*>(GetProcAddress(libraryHandle_, "gPluginData"));
68 }
69
Destroy()70 void LibraryWindows::Destroy()
71 {
72 delete this;
73 }
74
Load(const string_view filePath)75 ILibrary::Ptr ILibrary::Load(const string_view filePath)
76 {
77 return ILibrary::Ptr { new LibraryWindows(filePath) };
78 }
79
GetFileExtension()80 string_view ILibrary::GetFileExtension()
81 {
82 return ".dll";
83 }
84 CORE_END_NAMESPACE()
85