|
10 | 10 | #endif
|
11 | 11 |
|
12 | 12 | namespace thorin {
|
13 |
| -bool World::load_plugin(const char* plugin_name) { |
| 13 | +[[nodiscard]] static void* load_plugin_module(const char* plugin_name) { |
14 | 14 | #ifdef _WIN32
|
15 |
| - return false; |
| 15 | + return LoadLibraryA(plugin_name); |
16 | 16 | #else
|
17 |
| - void *handle = dlopen(plugin_name, RTLD_LAZY | RTLD_GLOBAL); |
18 |
| - if (!handle) { |
19 |
| - ELOG("Error loading plugin {}: {}", plugin_name, dlerror()); |
20 |
| - ELOG("Is plugin contained in LD_LIBRARY_PATH?"); |
21 |
| - return false; |
22 |
| - } |
23 |
| - dlerror(); |
24 |
| - |
25 |
| - char *error; |
26 |
| - auto initfunc = reinterpret_cast<plugin_init_func_t*>(dlsym(handle, "init")); |
27 |
| - if ((error = dlerror()) != NULL) { |
28 |
| - ILOG("Plugin {} did not supply an init function", plugin_name); |
29 |
| - } else { |
30 |
| - initfunc(); |
31 |
| - } |
| 17 | + return dlopen(plugin_name, RTLD_LAZY | RTLD_GLOBAL); |
| 18 | +#endif |
| 19 | +} |
32 | 20 |
|
33 |
| - data_.plugin_modules_.push_back(handle); |
34 |
| - return true; |
| 21 | +static bool unload_plugin_module(void* plugin_module) { |
| 22 | +#ifdef _WIN32 |
| 23 | + return FreeLibrary(static_cast<HMODULE>(plugin_module)) == TRUE; |
| 24 | +#else |
| 25 | + return dlclose(plugin_module) == 0; |
35 | 26 | #endif
|
36 | 27 | }
|
37 | 28 |
|
38 | 29 | template <typename T>
|
39 |
| -static T* lookup_plugin_function(void* plugin_module, const char* function_name) { |
| 30 | +[[nodiscard]] static T* lookup_plugin_function(void* plugin_module, const char* function_name) { |
40 | 31 | #ifdef _WIN32
|
| 32 | + return reinterpret_cast<T*>(GetProcAddress(static_cast<HMODULE>(plugin_module), function_name)); |
41 | 33 | #else
|
42 |
| - if (void* func = dlsym(plugin_module, function_name)) { |
43 |
| - return reinterpret_cast<T*>(func); |
44 |
| - } |
| 34 | + return reinterpret_cast<T*>(dlsym(plugin_module, function_name)); |
45 | 35 | #endif
|
46 |
| - return nullptr; |
| 36 | +} |
| 37 | + |
| 38 | +bool World::load_plugin(const char* plugin_name) { |
| 39 | + void* module = load_plugin_module(plugin_name); |
| 40 | + |
| 41 | + if (!module) { |
| 42 | + ELOG("failed to load plugin {}", plugin_name); |
| 43 | + return false; |
| 44 | + } |
| 45 | + |
| 46 | + if (auto init = lookup_plugin_function<plugin_init_func_t>(module, "init")) { |
| 47 | + if (!init()) { |
| 48 | + ELOG("failed to initialize plugin {}", plugin_name); |
| 49 | + unload_plugin_module(module); |
| 50 | + return false; |
| 51 | + } |
| 52 | + } else { |
| 53 | + ILOG("plugin {} did not supply an init function", plugin_name); |
| 54 | + } |
| 55 | + |
| 56 | + data_.plugin_modules_.push_back(module); |
| 57 | + return true; |
47 | 58 | }
|
48 | 59 |
|
49 | 60 | unique_plugin_intrinsic World::load_plugin_intrinsic(const char* function_name) const {
|
|
0 commit comments