Cogs.Core
Module.Linux.cpp
1#include "Module.h"
2#include "Logging/Logger.h"
3
4#include <array>
5#include <span>
6#include <string_view>
7
8#include <dlfcn.h>
9
10namespace {
11
12 const Cogs::Logging::Log logger = Cogs::Logging::getLogger("Module");
13
15 std::span<const char*> dllVersions() {
16#if defined( DEBUG )
17 static std::array paths = { ".x64.Debug.so" };
18 return std::span<const char*>(paths);
19#elif defined( OSOMP_EnableProfiler )
20 static std::array paths = { ".x64.ReleaseMemProfile.so", ".x64.Release.so" };
21 return std::span<const char*>(paths);
22#elif defined( ASAN )
23 static std::array paths = { ".x64.ReleaseASan.so", ".x64.Release.so" };
24 return std::span<const char*>(paths);
25#elif defined( TSAN )
26 static std::array paths = { ".x64.ReleaseTSan.so", ".x64.Release.so" };
27 return std::span<const char*>(paths);
28#else
29 static std::array paths = { ".x64.Release.so" };
30 return std::span<const char*>(paths);
31#endif
32 }
33}
34
45void Cogs::Module::load(const std::string& path, LoadStatus& status, void*& handle) {
46 if (path.find(".so") == std::string::npos) {
47
48 std::span<const char*> versions = dllVersions();
49 std::string libraryPath;
50 libraryPath.reserve(path.size() + 40);
51
52 for (const char* version : versions) {
53 libraryPath.clear();
54 libraryPath += "lib";
55 libraryPath += path;
56 libraryPath += version;
57
58 handle = ::dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_LOCAL);
59 if (handle) break;
60 }
61 }
62 else {
63 handle = ::dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
64 }
65 if(handle == nullptr) {
66 LOG_ERROR(logger, "dlopen failed: %s", dlerror());
67 }
68 status = handle ? LoadStatus::Loaded : LoadStatus::Failed;
69}
70
71void Cogs::Module::unload(void* handle) {
72 if (handle) {
73 dlclose(handle);
74 }
75}
76
83void* Cogs::Module::getProcAddress(void* handle, const char* procName) {
84 return dlsym(handle, procName);
85}
Log implementation class.
Definition: LogManager.h:139
static void load(const std::string &path, LoadStatus &status, void *&handle)
Attempts to load a shared library with the given name.
constexpr Log getLogger(const char(&name)[LEN]) noexcept
Definition: LogManager.h:180