Cogs.Core
Module.MacOS.cpp
1#include "Module.h"
2#include "Logging/Logger.h"
3#include <array>
4#include <span>
5#include <string_view>
6
7#include <dlfcn.h>
8
9namespace {
10 const Cogs::Logging::Log logger = Cogs::Logging::getLogger("Module");
11
13 std::span<const char*> dllVersions() {
14#if defined( DEBUG )
15 static std::array paths = { ".macOS.Debug.dylib" };
16 return std::span<const char*>(paths);
17#elif defined( OSOMP_EnableProfiler )
18 static std::array paths = { ".macOS.ReleaseMemProfile.dylib", ".macOS.Release.dylib" };
19 return std::span<const char*>(paths);
20#elif defined( ASAN )
21 static std::array paths = { ".macOS.ReleaseASan.dylib"), ".macOS.Release.dylib" };
22 return std::span<const char*>(paths);
23#elif defined( TSAN )
24 static std::array paths = { ".macOS.ReleaseTSan.dylib", ".macOS.Release.dylib" };
25 return std::span<const char*>(paths);
26#else
27 static std::array paths = { ".macOS.Release.dylib" };
28 return std::span<const char*>(paths);
29#endif
30 }
31}
32
43void Cogs::Module::load(const std::string& path, LoadStatus& status, void*& handle) {
44 if (path.find(".dylib") == std::string::npos){
45 std::span<const char*> versions = dllVersions();
46 std::string libraryPath;
47 libraryPath.reserve(path.size() + 40);
48
49 for (const char* version : versions) {
50 libraryPath.clear();
51 libraryPath += "lib";
52 libraryPath += path;
53 libraryPath += version;
54
55 handle = ::dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_LOCAL);
56 if (handle) break;
57 }
58 }
59 else {
60 handle = dlopen(path.data(), RTLD_NOW | RTLD_LOCAL);
61 }
62 if(handle == nullptr) {
63 LOG_ERROR(logger, "dlopen failed: %s", dlerror());
64 }
65 status = handle ? LoadStatus::Loaded : LoadStatus::Failed;
66}
67
68void Cogs::Module::unload(void* handle) {
69 if (handle) {
70 dlclose(handle);
71 }
72}
73
80void* Cogs::Module::getProcAddress(void* handle, const char* procName) {
81 return dlsym(handle, procName);
82}
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