VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
Loader.cpp
Go to the documentation of this file.
1#include "Loader/Loader.hpp"
2
6
7#include <cstring>
8#include <engine2/isource2server.h>
9#include <engine2/isource2serverconfig.h>
10#include <filesystem>
11#include <fstream>
12#include <iterator>
13#include <khook.hpp>
14#include <khook/memory.hpp>
15#include <string>
16#include <system_error>
17#include <tier0/dbg.h>
18#include <tier0/icommandline.h>
19#include <utility>
20
21namespace VoltMod
22{
23
25static std::string g_gameDir;
26static LoaderHandoff g_start{.HookDispatcher = &g_dispatcher};
27static HostStopFn g_stopHost = nullptr;
28
29// What the swapped slots held. Never written back: Metamod restores its own slots, and ours would undo that.
30static bool (*g_connect)(void* config, InterfaceFactory engineFactory) = nullptr;
31static void (*g_disconnect)(void* config) = nullptr;
32static InitReturnVal_t (*g_init)(void* server) = nullptr;
33static void (*g_shutdown)(void* server) = nullptr;
34
35template <class Fn>
36static Fn SwapSlot(void* object, int index, Fn replacement)
37{
38 void** slot = *static_cast<void***>(object) + index;
39 KHook::Memory::SetAccess(slot, sizeof(void*),
40 KHook::Memory::Flags::READ | KHook::Memory::Flags::WRITE | KHook::Memory::Flags::EXECUTE);
41 const Fn original = reinterpret_cast<Fn>(*slot);
42 *slot = reinterpret_cast<void*>(replacement);
43 return original;
44}
45
46/** `csgo/addons/voltmod/bin/<platform>/` holds this module, so `csgo` is four directories up. */
47static std::filesystem::path GameDir()
48{
49 std::filesystem::path dir = OwnPath().parent_path();
50 for (int level = 0; level < 4; ++level)
51 {
52 dir = dir.parent_path();
53 }
54 return dir;
55}
56
57static std::string ReadFile(const std::filesystem::path& path)
58{
59 std::ifstream file(path, std::ios::binary);
60 return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
61}
62
63/** The first server library on the `Game` paths: Metamod's loader where it is installed, else the game's. */
65{
66 // Answering nothing makes the engine load `server` itself, so a game client never runs VoltMod.
67 if (!CommandLine()->HasParm("-dedicated"))
68 {
69 return nullptr;
70 }
71
72 const std::filesystem::path gameDir = GameDir();
73 const std::filesystem::path gameinfo = gameDir / "gameinfo.gi";
74 const std::string text = ReadFile(gameinfo);
75 if (text.empty())
76 {
77 Warning("[VoltMod] Could not read %s, so VoltMod is not loaded.\n", gameinfo.string().c_str());
78 return nullptr;
79 }
80
81 for (const std::string& searchPath : GameSearchPaths(text))
82 {
83 const std::filesystem::path server = gameDir.parent_path() / searchPath / "bin" / PlatformDir / ServerFile;
84 std::error_code missing;
85 if (!std::filesystem::is_regular_file(server, missing))
86 {
87 continue;
88 }
89
90 void* module = OpenModule(server);
91 auto* factory = module ? reinterpret_cast<InterfaceFactory>(FindExport(module, "CreateInterface")) : nullptr;
92 if (factory == nullptr)
93 {
94 Warning("[VoltMod] Could not load %s: %s\n", server.string().c_str(), LastError().c_str());
95 continue;
96 }
97
98 Msg("[VoltMod] Loader started; forwarding the game server to %s\n", server.string().c_str());
99 g_gameDir = gameDir.string();
100 g_start.GameDir = g_gameDir.c_str();
101 return factory;
102 }
103
104 Warning("[VoltMod] No Game path in %s holds a server library, so VoltMod is not loaded.\n",
105 gameinfo.string().c_str());
106 return nullptr;
107}
108
110{
112 if (next == nullptr)
113 {
114 // The engine may unload this module now; KHook's threads must be joined first.
115 KHook::Shutdown();
116 }
117 return next;
118}
119
120static void StartHost()
121{
122 if (g_start.EngineFactory == nullptr || g_start.ServerFactory == nullptr)
123 {
124 Warning("[VoltMod] The engine and game factories were not found, so VoltMod is not loaded.\n");
125 return;
126 }
127
128 const std::filesystem::path path = OwnPath().parent_path() / HostFile;
129 void* host = OpenModule(path);
130 if (host == nullptr)
131 {
132 Warning("[VoltMod] Could not load %s: %s\n", path.string().c_str(), LastError().c_str());
133 return;
134 }
135
136 auto* start = reinterpret_cast<HostStartFn>(FindExport(host, HostStartName));
137 auto* stop = reinterpret_cast<HostStopFn>(FindExport(host, HostStopName));
138 if (start == nullptr || stop == nullptr)
139 {
140 Warning("[VoltMod] Could not load %s: %s\n", path.string().c_str(), LastError().c_str());
141 return;
142 }
143
144 // The server still runs without VoltMod, as it would after a failed Metamod plugin.
145 char error[512] = "";
146 if (!start(&g_start, error, sizeof(error)))
147 {
148 Warning("[VoltMod] The host did not start: %s\n", error);
149 return;
150 }
151 g_stopHost = stop;
152}
153
154static bool OnConnect(void* config, InterfaceFactory engineFactory)
155{
156 g_start.EngineFactory = engineFactory;
157 return g_connect(config, engineFactory);
158}
159
160static InitReturnVal_t OnInit(void* server)
161{
162 // First, so Metamod's plugins start after VoltMod and hook on top of it.
163 StartHost();
164 return g_init(server);
165}
166
167static void StopHost()
168{
169 if (g_stopHost != nullptr)
170 {
171 std::exchange(g_stopHost, nullptr)();
172 }
173}
174
175static void OnShutdown(void* server)
176{
177 // Here, not at Disconnect: by then the engine has shut down and a plugin's console command crashes it.
178 StopHost();
179 g_shutdown(server);
180}
181
182static void OnDisconnect(void* config)
183{
184 StopHost();
185 // Safe: this slot was swapped, not hooked through KHook.
186 KHook::Shutdown();
187 g_disconnect(config);
188}
189
190static void Patch(const char* name, void* object)
191{
192 if (std::strcmp(name, INTERFACEVERSION_SERVERCONFIG) == 0 && g_connect == nullptr)
193 {
194 g_connect = SwapSlot(object, KHook::GetVtableIndex(&ISource2ServerConfig::Connect), &OnConnect);
195 g_disconnect = SwapSlot(object, KHook::GetVtableIndex(&ISource2ServerConfig::Disconnect), &OnDisconnect);
196 }
197 else if (std::strcmp(name, INTERFACEVERSION_SERVERGAMEDLL) == 0 && g_init == nullptr)
198 {
199 // The game's own factory: asking Metamod's loader for this would patch Init again.
200 g_start.ServerFactory = FactoryAt(*static_cast<void**>(object));
201 g_init = SwapSlot(object, KHook::GetVtableIndex(&ISource2Server::Init), &OnInit);
202 g_shutdown = SwapSlot(object, KHook::GetVtableIndex(&ISource2Server::Shutdown), &OnShutdown);
203 }
204}
205
206} // namespace VoltMod
207
208void* CreateInterface(const char* name, int* returnCode)
209{
211 if (next == nullptr)
212 {
213 if (returnCode != nullptr)
214 {
215 *returnCode = IFACE_FAILED;
216 }
217 return nullptr;
218 }
219
220 void* object = next(name, returnCode);
221 if (object != nullptr)
222 {
223 VoltMod::Patch(name, object);
224 }
225 return object;
226}
void * CreateInterface(const char *name, int *returnCode)
Definition Loader.cpp:208
The loader's KHook, which every module's hooks go through.
static void Patch(const char *name, void *object)
Definition Loader.cpp:190
static void StartHost()
Definition Loader.cpp:120
static bool OnConnect(void *config, InterfaceFactory engineFactory)
Definition Loader.cpp:154
constexpr std::string_view HostFile
Definition Loader.hpp:18
static void OnDisconnect(void *config)
Definition Loader.cpp:182
void *(*)(const char *name, int *returnCode) InterfaceFactory
static HostStopFn g_stopHost
Definition Loader.cpp:27
static InitReturnVal_t(* g_init)(void *server)
Definition Loader.cpp:32
static std::string LastError()
constexpr std::string_view PlatformDir
Definition Loader.hpp:17
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:57
constexpr const char * HostStopName
static InterfaceFactory LoadNextServer()
Definition Loader.cpp:64
bool(*)(const LoaderHandoff *start, char *error, size_t errorSize) HostStartFn
static void OnShutdown(void *server)
Definition Loader.cpp:175
std::filesystem::path OwnPath()
constexpr const char * HostStartName
static void(* g_disconnect)(void *config)
Definition Loader.cpp:31
static void(* g_shutdown)(void *server)
Definition Loader.cpp:33
static LoaderHandoff g_start
Definition Loader.cpp:26
static std::filesystem::path GameDir()
Definition Loader.cpp:47
std::vector< std::string > GameSearchPaths(std::string_view gameinfo)
The Game values under SearchPaths in a gameinfo.gi, in file order.
InterfaceFactory FactoryAt(const void *address)
void * OpenModule(const std::filesystem::path &path)
static KHookForwarder g_dispatcher
Definition Loader.cpp:24
void(*)() HostStopFn
static bool(* g_connect)(void *config, InterfaceFactory engineFactory)
Definition Loader.cpp:30
static std::string g_gameDir
Definition Loader.cpp:25
static void StopHost()
Definition Loader.cpp:167
static void * FindExport(void *handle, const char *name)
static InterfaceFactory FindNextFactory()
Definition Loader.cpp:109
constexpr std::string_view ServerFile
Definition Loader.hpp:22
static InitReturnVal_t OnInit(void *server)
Definition Loader.cpp:160
static Fn SwapSlot(void *object, int index, Fn replacement)
Definition Loader.cpp:36