Debian Codegraph @

Source/Core/Common/DynamicLibrary.cpp

raw symbols SCIP
1 // Copyright 2019 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "Common/DynamicLibrary.h"
5
6 #include <cstring>
7
8 #include <fmt/format.h>
9
10 #ifdef _WIN32
11 #include <Windows.h>
12 #else
13 #include <dlfcn.h>
14 #endif
15
16 namespace Common
17 {
18 DynamicLibrary::DynamicLibrary() = default;
19
20 DynamicLibrary::DynamicLibrary(const char* filename)
21 {
22 Open(filename);
23 }
24
25 DynamicLibrary::DynamicLibrary(void* handle)
26 {
27 m_handle = handle;
28 }
29
30 DynamicLibrary::~DynamicLibrary()
31 {
32 Close();
33 }
34
35 DynamicLibrary& DynamicLibrary::operator=(void* handle)
36 {
37 m_handle = handle;
38 return *this;
39 }
40
41 std::string DynamicLibrary::GetUnprefixedFilename(const char* filename)
42 {
43 #if defined(_WIN32)
44 return std::string(filename) + ".dll";
45 #elif defined(__APPLE__)
46 return std::string(filename) + ".dylib";
47 #else
48 return std::string(filename) + ".so";
49 #endif
50 }
51
52 std::string DynamicLibrary::GetVersionedFilename(const char* libname, int major, int minor)
53 {
54 #if defined(_WIN32)
55 if (major >= 0 && minor >= 0)
56 return fmt::format("{}-{}-{}.dll", libname, major, minor);
57 else if (major >= 0)
58 return fmt::format("{}-{}.dll", libname, major);
59 else
60 return fmt::format("{}.dll", libname);
61 #elif defined(__APPLE__)
62 const char* prefix = std::strncmp(libname, "lib", 3) ? "lib" : "";
63 if (major >= 0 && minor >= 0)
64 return fmt::format("{}{}.{}.{}.dylib", prefix, libname, major, minor);
65 else if (major >= 0)
66 return fmt::format("{}{}.{}.dylib", prefix, libname, major);
67 else
68 return fmt::format("{}{}.dylib", prefix, libname);
69 #else
70 const char* prefix = std::strncmp(libname, "lib", 3) ? "lib" : "";
71 if (major >= 0 && minor >= 0)
72 return fmt::format("{}{}.so.{}.{}", prefix, libname, major, minor);
73 else if (major >= 0)
74 return fmt::format("{}{}.so.{}", prefix, libname, major);
75 else
76 return fmt::format("{}{}.so", prefix, libname);
77 #endif
78 }
79
80 bool DynamicLibrary::Open(const char* filename)
81 {
82 #ifdef _WIN32
83 m_handle = reinterpret_cast<void*>(LoadLibraryA(filename));
84 #else
85 m_handle = dlopen(filename, RTLD_NOW);
86 #endif
87 return m_handle != nullptr;
88 }
89
90 void DynamicLibrary::Close()
91 {
92 if (!IsOpen())
93 return;
94
95 #ifdef _WIN32
96 FreeLibrary(static_cast<HMODULE>(m_handle));
97 #else
98 dlclose(m_handle);
99 #endif
100 m_handle = nullptr;
101 }
102
103 void* DynamicLibrary::GetSymbolAddress(const char* name) const
104 {
105 #ifdef _WIN32
106 return reinterpret_cast<void*>(GetProcAddress(static_cast<HMODULE>(m_handle), name));
107 #else
108 return reinterpret_cast<void*>(dlsym(m_handle, name));
109 #endif
110 }
111 } // namespace Common