载入中...
搜索中...
未找到
Plugins.cpp
浏览该文件的文档.
1#include "plugins/Plugins.h"
2
3#include "common/Exception.h"
5
6#include <simplesquirrel/simplesquirrel.hpp>
7
8#if defined(_WIN32)
9# define WIN32_LEAN_AND_MEAN
10# include <windows.h>
11#else
12# include <dlfcn.h>
13#include <unistd.h>
14#endif
15
16#include <filesystem>
17#include <unordered_set>
18#include <vector>
19
20namespace eve::plugins {
21namespace {
22
23struct Images {
24 std::unordered_set<std::string> loaded;
25 std::vector<void*> resident;
26 uint64_t serial = 0;
27};
28
29Images& images() {
30 static Images state;
31 return state;
32}
33
34std::string identity(const std::string& path) {
35 if (path.empty()) throw Exception("plugins: empty path");
36 return std::filesystem::weakly_canonical(std::filesystem::absolute(path)).string();
37}
38
39Result<void> failure(DiagnosticCode code, std::string message, const std::string& path) {
40 return Result<void>::failure(Diagnostic::error(code, std::move(message), path, {}, "plugins"));
41}
42
43// Load a unique sibling image: the original can be rebuilt on Windows, and the
44// loader cannot reuse the previous image by filename/inode. Keeping the sibling
45// in the same directory preserves $ORIGIN / @loader_path dependency resolution.
46std::filesystem::path shadowCopy(const std::filesystem::path& source) {
47#if defined(_WIN32)
48 const auto process = GetCurrentProcessId();
49#else
50 const auto process = getpid();
51#endif
52 for (;;) {
53 const auto name = ".eve-" + std::to_string(process) + "-" + std::to_string(++images().serial) + "-" +
54 source.filename().string();
55 const auto shadow = source.parent_path() / name;
56 std::error_code error;
57 if (std::filesystem::copy_file(source, shadow, std::filesystem::copy_options::none, error)) return shadow;
58 if (error == std::errc::file_exists) continue;
59 const auto message = error.message();
60 std::filesystem::remove(shadow, error);
61 throw Exception("plugins: cannot copy library '%s': %s", source.string().c_str(), message.c_str());
62 }
63}
64
65} // namespace
66
67using PluginInitFn = int (*)();
68
70
71Plugins::Plugins() = default;
72Plugins::~Plugins() = default;
73
74Result<void> Plugins::install(const std::string& path, bool replace) {
75 bool registering = false;
76 try {
77 const std::string key = identity(path);
78 auto& state = images();
79 if (replace && !state.loaded.count(key)) return failure(DiagnosticCode::NotFound, "plugin is not loaded", key);
80 if (!replace && state.loaded.count(key)) return Result<void>::success(Status::success(StatusCode::NoOp));
81 // Allocate bookkeeping before native initialization can publish code pointers.
82 state.resident.reserve(state.resident.size() + 1);
84 if (!registration.ok()) return registration;
85 registering = true;
86 const auto shadow = shadowCopy(key);
87#if defined(_WIN32)
88 HMODULE native = LoadLibraryExW(shadow.c_str(), nullptr,
89 LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
90 void* mod = native;
91 const auto loadError = GetLastError();
92 if (!mod) {
93 std::error_code ignored;
94 std::filesystem::remove(shadow, ignored);
95 throw Exception("plugins: LoadLibrary failed (err=%lu)", loadError);
96 }
97 auto init = reinterpret_cast<PluginInitFn>(GetProcAddress(native, "eve_plugin_init"));
98#else
99 void* mod = dlopen(shadow.c_str(), RTLD_NOW | RTLD_LOCAL);
100 const std::string loadError = mod ? "" : dlerror();
101 std::error_code ignored;
102 std::filesystem::remove(shadow, ignored);
103 if (!mod) throw Exception("plugins: dlopen failed: %s", loadError.c_str());
104 auto init = reinterpret_cast<PluginInitFn>(dlsym(mod, "eve_plugin_init"));
105#endif
106 // Even a failed exposer can leave native closures in the VM's type map.
107 // Never unmap an initialized image while any VM may still refer to it.
108 state.resident.push_back(mod);
109 if (!init) throw Exception("plugins: missing eve_plugin_init");
110 const int rc = init();
111 if (rc != 0) throw Exception("plugins: eve_plugin_init returned %d", rc);
113 registering = false;
114 if (!committed.ok()) return committed;
115 state.loaded.insert(key);
117 } catch (const std::exception& error) {
118 if (registering) {
119 auto rollback = ModuleManager::finishPluginRegistration(false);
120 rollback.ignore("plugin candidate failed; preserve the previous generation");
121 }
122 return failure(DiagnosticCode::InvalidArgument, error.what(), path);
123 } catch (...) {
124 if (registering) {
125 auto rollback = ModuleManager::finishPluginRegistration(false);
126 rollback.ignore("plugin initializer threw; preserve the previous generation");
127 }
128 return failure(DiagnosticCode::InvalidArgument, "plugin initializer threw", path);
129 }
130}
131
132Result<void> Plugins::loadPlugin(const std::string& path) { return install(path, false); }
133Result<void> Plugins::reload(const std::string& path) { return install(path, true); }
134
135bool Plugins::load(const std::string& path) {
136 auto result = loadPlugin(path);
137 if (!result.ok()) throw Exception("plugins.load: %s", result.status().describe().c_str());
138 return true;
139}
140
141bool Plugins::unload(const std::string& path) {
142 (void)path;
143 return false;
144}
145
146bool Plugins::isLoaded(const std::string& path) const {
147 if (path.empty()) return false;
148 try {
149 return images().loaded.count(identity(path)) > 0;
150 } catch (...) {
151 return false;
152 }
153}
154
155void Plugins::expose(ssq::Table& table) {
156 auto cls = table.addClass(name, Plugins::create, false);
157 expose(cls);
158}
159
160void Plugins::expose(ssq::Class& cls) {
161 cls.addFunc("getName", &Plugins::getName);
162 cls.addFunc("load", &Plugins::load);
163 cls.addFunc("loadPlugin", [vm = cls.getHandle()](Plugins* self, const std::string& path) {
164 return script::projectResult(vm, self->loadPlugin(path));
165 });
166 cls.addFunc("reload", [vm = cls.getHandle()](Plugins* self, const std::string& path) {
167 return script::projectResult(vm, self->reload(path));
168 });
169 cls.addFunc("unload", &Plugins::unload);
170 cls.addFunc("isLoaded", &Plugins::isLoaded);
171}
172
173} // namespace eve::plugins
bool committed
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::string message
DiagnosticCode code
Poco::JSON::Object::Ptr result
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
uint64_t serial
Definition Plugins.cpp:26
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
std::vector< void * > resident
Definition Plugins.cpp:25
std::string_view source
The single Squirrel projection for common Result, Status and Value.
uint64_t identity
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
static eve::Result< void > beginPluginRegistration()
Begins an atomic native-plugin module registration transaction.
static eve::Result< void > finishPluginRegistration(bool commit)
Commits or rolls back the active plugin registration transaction.
virtual std::string getName() const =0
Returns the name.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
加载导出 eve_plugin_init 的原生动态库(dll / so / dylib)。
Definition Plugins.h:12
bool isLoaded(const std::string &path) const
插件是否已加载。
Definition Plugins.cpp:146
bool load(const std::string &path)
Compatibility wrapper for loadPlugin; throws on failure, returns true on success.
Definition Plugins.cpp:135
Result< void > reload(const std::string &path)
Publishes a new plugin generation without restarting the script VM.
Definition Plugins.cpp:133
Result< void > loadPlugin(const std::string &path)
Loads a plugin once; aliases of a canonical path identify the same plugin.
Definition Plugins.cpp:132
bool unload(const std::string &path)
插件为进程期驻留;该兼容方法始终返回 false。
Definition Plugins.cpp:141
int(*)() PluginInitFn
Definition Plugins.cpp:67
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47