2020-12-22 17:10:01 +00:00
|
|
|
#include "helpers/plugin_handler.hpp"
|
|
|
|
|
|
|
|
#include <dlfcn.h>
|
2021-02-07 12:40:47 +00:00
|
|
|
|
2020-12-22 17:10:01 +00:00
|
|
|
#include <filesystem>
|
|
|
|
|
|
|
|
namespace hex {
|
|
|
|
|
2021-02-07 12:40:47 +00:00
|
|
|
namespace fs = std::filesystem;
|
|
|
|
|
2021-02-07 13:57:13 +00:00
|
|
|
// hex::plugin::<pluginName>::internal::initializePlugin()
|
2021-02-07 12:40:47 +00:00
|
|
|
constexpr auto InitializePluginSymbol = "_ZN3hex6plugin%d%s8internal16initializePluginEv";
|
2020-12-22 17:10:01 +00:00
|
|
|
|
|
|
|
Plugin::Plugin(std::string_view path) {
|
2021-02-07 12:40:47 +00:00
|
|
|
auto fileName = fs::path(path).stem();
|
|
|
|
auto symbolName = hex::format(InitializePluginSymbol, fileName.string().length(), fileName.string().c_str());
|
2020-12-22 17:10:01 +00:00
|
|
|
this->m_handle = dlopen(path.data(), RTLD_LAZY);
|
|
|
|
if (this->m_handle == nullptr)
|
|
|
|
return;
|
|
|
|
|
2021-02-07 12:40:47 +00:00
|
|
|
this->m_initializePluginFunction = reinterpret_cast<InitializePluginFunc>(dlsym(this->m_handle, symbolName.c_str()));
|
2020-12-22 17:10:01 +00:00
|
|
|
}
|
|
|
|
|
2021-02-07 13:57:13 +00:00
|
|
|
Plugin::Plugin(Plugin &&other) {
|
|
|
|
this->m_handle = other.m_handle;
|
|
|
|
this->m_initializePluginFunction = other.m_initializePluginFunction;
|
|
|
|
|
|
|
|
other.m_handle = nullptr;
|
|
|
|
other.m_initializePluginFunction = nullptr;
|
|
|
|
}
|
|
|
|
|
2020-12-22 17:10:01 +00:00
|
|
|
Plugin::~Plugin() {
|
2021-02-01 19:07:57 +00:00
|
|
|
dlclose(this->m_handle);
|
2020-12-22 17:10:01 +00:00
|
|
|
}
|
|
|
|
|
2021-01-12 22:28:41 +00:00
|
|
|
void Plugin::initializePlugin() const {
|
2021-02-07 12:40:47 +00:00
|
|
|
if (this->m_initializePluginFunction != nullptr) {
|
2021-01-12 22:28:41 +00:00
|
|
|
this->m_initializePluginFunction();
|
2021-02-07 12:40:47 +00:00
|
|
|
}
|
2020-12-22 17:10:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void PluginHandler::load(std::string_view pluginFolder) {
|
|
|
|
if (!std::filesystem::exists(pluginFolder))
|
|
|
|
throw std::runtime_error("Failed to find plugin folder");
|
|
|
|
|
|
|
|
PluginHandler::s_pluginFolder = pluginFolder;
|
|
|
|
|
2021-01-12 15:50:15 +00:00
|
|
|
for (auto& pluginPath : std::filesystem::directory_iterator(pluginFolder)) {
|
2021-02-07 12:40:47 +00:00
|
|
|
if (pluginPath.is_regular_file() && pluginPath.path().extension() == ".hexplug")
|
2021-02-07 13:57:13 +00:00
|
|
|
PluginHandler::s_plugins.emplace_back(pluginPath.path().string());
|
2021-01-12 15:50:15 +00:00
|
|
|
}
|
2020-12-22 17:10:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void PluginHandler::unload() {
|
|
|
|
PluginHandler::s_plugins.clear();
|
|
|
|
PluginHandler::s_pluginFolder.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
void PluginHandler::reload() {
|
2021-02-07 12:40:47 +00:00
|
|
|
PluginHandler::unload();
|
2020-12-22 17:10:01 +00:00
|
|
|
PluginHandler::load(PluginHandler::s_pluginFolder);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|