-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathModInit.cpp
More file actions
433 lines (341 loc) · 14 KB
/
Copy pathModInit.cpp
File metadata and controls
433 lines (341 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#include "ModInit.hpp"
#include <AppShell/Shell.hpp>
#include <OsintgramCXX/App/ModHandles.hpp>
#include <dev_tools/commons/Utils.hpp>
#include <dev_tools/commons/Terminal.hpp>
#include <nlohmann/json.hpp>
#include <filesystem>
#include <fstream>
#ifdef __linux__
#include <dlfcn.h>
#endif
#ifdef _WIN32
#include <windows.h>
#endif
using json = nlohmann::json;
namespace fs = std::filesystem;
std::string currentProcessingLibrary;
std::vector<int> processedEntries;
std::vector<fs::path> lookupPaths = {
DevTools::CurrentWorkingDirectory() / "Resources",
DevTools::CurrentWorkingDirectory(),
DevTools::ExecutableDirectory() / "Resources",
DevTools::ExecutableDirectory(),
#if defined(__linux__) && !defined(__ANDROID__)
"/etc/OsintgramCXX",
DevTools::UserHomeDirectory().string() + "/.config/OsintgramCXX",
"/Data/base/" + std::to_string(getuid()) + "/OsintgramCXX",
"/Data/base/shared/OsintgramCXX",
#elif defined(__ANDROID__)
"/data/data/com.termux/files/.config/OsintgramCXX",
"/data/local/tmp/OsintgramCXX",
"/sdcard/Android/data/com.termux/files/.config/OsintgramCXX",
"/sdcard/Android/data/com.termux/files/config/OsintgramCXX",
"/sdcard/OsintgramCXX",
"/storage/emulated/0/Android/data/com.termux/files/.config/OsintgramCXX",
"/storage/emulated/0/Android/data/com.termux/files/config/OsintgramCXX",
"/storage/emulated/0/OsintgramCXX",
// I might consider, but don't take the actual word for it, if you do see this one
"/data/data/net.bc100dev.osintgram.android/files",
#endif
#ifdef _WIN32
DevTools::UserHomeDirectory().string() + R"(\AppData\Local\OsintgramCXX)",
DevTools::UserHomeDirectory().string() + R"(\AppData\Local\OsintgramCXX\Resources)",
DevTools::UserHomeDirectory().string() + R"(\AppData\Roaming\OsintgramCXX)",
DevTools::UserHomeDirectory().string() + R"(\AppData\Roaming\OsintgramCXX\Resources)",
#endif
};
fs::path locate_json(const std::string& filename);
std::string find_lib(const std::string& file) {
fs::path result;
// 1. look for libraries within the cwd (current working directory) and the executables directory
if (fs::exists(DevTools::ExecutableDirectory() / file))
return fs::path(DevTools::ExecutableDirectory() / file).string();
#ifdef __linux__
// 2. look for libraries in the "LD_LIBRARY_PATH" environment
if (const char* ldLibPathEnv = getenv("LD_LIBRARY_PATH")) {
std::string ldEntry;
while (std::getline(std::istringstream(ldLibPathEnv), ldEntry, ':')) {
result = ldEntry / fs::path(file);
if (fs::exists(result))
return result.string();
}
}
// 3. look for libraries in the system paths
// as per tests suggest, this does take quite some time.
// as long as the library exists within the executable's range, PWD and LD_LIBRARY_PATH, this shouldn't be a problem
// otherwise, have fun
#if defined(__ANDROID__)
std::string sysPaths = "/data/data/com.termux/files/usr/lib:/system/lib:/system/lib32:/system/lib64";
#else
// yes, I added that AnlinxOS path, deal with it :skull:
std::string sysPaths =
"/usr/lib:/usr/lib32:/usr/lib64:/usr/local/lib:/usr/local/lib32:/usr/local/lib64:/lib:/lib32:/lib64:/System/" +
std::string(CPU_ARCHITECTURE);
#endif
std::string entry;
std::stringstream ss(sysPaths);
while (std::getline(ss, entry, ':')) {
result = fs::path(entry) / fs::path(file);
if (fs::exists(result))
return result.string();
}
// 4. Persistent / User Storage paths
for (const auto& it : lookupPaths) {
if (fs::exists(it / file))
return it / file;
}
#endif
#ifdef _WIN32
// windows, at least you aren't this hard...
// right?
if (const char* pathEnv = getenv("PATH")) {
std::string pathEntry;
std::istringstream ss(pathEnv);
while (std::getline(ss, pathEntry, ';')) {
result = pathEntry / fs::path(file);
if (fs::exists(result))
return result.string();
}
}
std::string userProfile = DevTools::UserHomeDirectory().string();
std::vector<std::string> winPaths = {
userProfile + R"(\AppData\Local\OsintgramCXX)",
userProfile + R"(\AppData\Local\OsintgramCXX\mods.d)",
userProfile + R"(\AppData\Local\OsintgramCXX\mods.d\)" + std::string(CPU_ARCHITECTURE)
};
for (const auto& it : winPaths) {
result = fs::path(it) / file;
if (fs::exists(result))
return result.string();
}
#endif
return "";
}
void* get_method_from_handle(void* handle, const char* symbol) {
#ifdef __linux__
void* p = dlsym(handle, symbol);
if (p == nullptr)
throw std::runtime_error("dlsym failed for " + currentProcessingLibrary + ": " + std::string(dlerror()));
return p;
#endif
#ifdef _WIN32
return (void*)GetProcAddress((HMODULE)handle, symbol);
#else
// for you macOS users :skull:
return nullptr;
#endif
}
std::string get_error_from_lib() {
#ifdef __linux__
return dlerror();
#elif defined(_WIN32)
char buf[512] = {0};
unsigned long len = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, GetLastError(), 0, buf, sizeof(buf), nullptr);
if (len == 0)
return "[UNKNOWN_ERROR]";
buf[len] = '\0';
return buf;
#else
return "[UNSPECIFIED]";
#endif
}
void parse_json(const json& j) {
if (!j.is_object() || !j.contains("command_sets"))
throw std::runtime_error("Unexpected JSON content");
if (j["command_sets"].is_array() && !j["command_sets"].empty()) {
for (const auto& command_set : j["command_sets"]) {
if (command_set.is_string() && !std::string(command_set).empty()) {
if (fs::path jsonFile = locate_json(command_set); fs::exists(jsonFile)) {
std::string data;
// we use scope block to make the file closing happen as soon as the scope block is finished
{
if (std::ifstream in(jsonFile); in.is_open()) {
std::stringstream ss;
ss << in.rdbuf();
data = ss.str();
}
}
parse_json(json::parse(data));
}
continue;
}
void* libHandle = nullptr;
if (!command_set.contains("label") && !command_set["label"].is_string())
throw std::runtime_error("invalid command set (\"label\" key is missing or contains invalid data)");
if (!command_set.contains("id") && !command_set["id"].is_number())
throw std::runtime_error("invalid command set (\"id\" key is missing or contains invalid data)");
OsintgramCXX::LibraryEntry libEntryData{};
libEntryData.label = command_set["label"];
libEntryData.id = command_set["id"];
if (std::ranges::find(processedEntries, libEntryData.id) != processedEntries.end())
continue;
processedEntries.emplace_back(libEntryData.id);
if (command_set.contains("author") && command_set["author"].is_string())
libEntryData.author = command_set["author"];
if (command_set.contains("description") && command_set["description"].is_string())
libEntryData.description = command_set["description"];
std::string objName;
// construct platform name
#ifdef __linux__
objName = "linux:";
#endif
#ifdef __ANDROID__
objName = "android:";
#endif
#ifdef _WIN64
objName = "windows:";
#endif
// construct architecture
#ifdef __x86_64__
objName.append("x64");
#endif
#ifdef __aarch64__
objName.append("arm64");
#endif
if (!command_set["lib"].contains(objName)) {
std::cerr << "data for this current platform (" << objName << ") does not exist, passing on..."
<< std::endl;
continue;
}
if (!command_set["lib"][objName].is_string())
throw std::runtime_error("library entry for \"" + objName + "\" is not a string");
std::string libName = command_set["lib"][objName];
std::string libPath = find_lib(libName);
if (libPath.empty())
throw std::runtime_error("Library " + libName + " not found");
currentProcessingLibrary = libName;
#ifdef __linux__
libHandle = dlopen(libPath.c_str(), RTLD_NOW);
#endif
#ifdef _WIN32
libHandle = LoadLibraryA(libPath.c_str());
#endif
if (command_set["handlers"].is_object() && !command_set["handlers"].empty()) {
json h_obj = command_set["handlers"];
std::string symbolName;
if (h_obj.contains("OnLoad") && h_obj["OnLoad"].is_string()) {
symbolName = h_obj["OnLoad"];
libEntryData.handler_onLoad = [libHandle, libName, symbolName]() -> int {
using FunctionType = int();
void* funcPtr = get_method_from_handle(libHandle, symbolName.c_str());
if (!funcPtr) {
std::cerr << "[ERROR] Failed to resolve symbol from \"" << libName << "\": " << symbolName
<< " -> "
<< get_error_from_lib() << std::endl;
return -1;
}
return reinterpret_cast<FunctionType*>(funcPtr)();
};
}
if (h_obj.contains("OnStop") && h_obj["OnStop"].is_string()) {
symbolName = h_obj["OnStop"];
libEntryData.handler_onExit = [libHandle, libName, symbolName]() -> int {
using FunctionType = int();
void* funcPtr = get_method_from_handle(libHandle, symbolName.c_str());
if (!funcPtr) {
std::cerr << "[ERROR] Failed to resolve symbol from " << libName << ": " << symbolName
<< " -> "
<< get_error_from_lib() << std::endl;
return -1;
}
return reinterpret_cast<FunctionType*>(funcPtr)();
};
}
}
if (command_set["cmd_list"].is_array() && !command_set["cmd_list"].empty()) {
for (const auto& cmd : command_set["cmd_list"]) {
if ((cmd.contains("cmd") && cmd.contains("description") && cmd.contains("exec_symbol")) &&
(cmd["cmd"].is_string() && cmd["description"].is_string() && cmd["exec_symbol"].is_string())) {
std::string cmdName = cmd["cmd"];
std::string desc = cmd["description"];
std::string sym = cmd["exec_symbol"];
void* funcPtr = get_method_from_handle(libHandle, sym.c_str());
if (funcPtr == nullptr)
throw std::runtime_error(
std::string("Command symbol for ").append(libName) + " not found, " + sym);
Application::C_CommandExec cmdExec = [funcPtr](const char* _c, int a, char** b, int c,
char** d) {
return reinterpret_cast<int (*)(const char*, int, char**, int, char**)>(funcPtr)(_c, a,
b, c,
d);
};
Application::ShellLibEntry cmdEntry{};
cmdEntry.cmd = cmdName;
cmdEntry.description = desc;
cmdEntry.execHandler = cmdExec;
libEntryData.commands.push_back(cmdEntry);
}
}
}
OsintgramCXX::loadedLibraries[libHandle] = libEntryData;
}
}
}
fs::path locate_json(const std::string& filename) {
for (const auto& it : lookupPaths) {
if (fs::exists(fs::path(it) / filename))
return fs::path(fs::path(it) / filename);
}
return "";
}
void init_data() {
std::vector<std::string> jsonFiles;
if (const char* cJsonFile = getenv("OsintgramCXX_JsonCommandList")) {
std::string _e = cJsonFile;
std::string delim;
#ifdef _WIN32
delim = ";";
#else
delim = ":";
#endif
if (DevTools::StringContains(_e, delim))
jsonFiles = DevTools::SplitString(_e, delim);
}
for (const auto& it : lookupPaths) {
if (fs::path path = it / "commands.json"; fs::exists(path))
jsonFiles.emplace_back(path.string());
}
if (jsonFiles.empty()) {
std::cerr << "No files under the name of commands.json found." << std::endl;
return;
}
for (const auto& it : jsonFiles) {
json j;
std::ifstream in(it);
if (!in.is_open()) {
std::cerr << "Could not open command list file \"" << it << "\", continuing..." << std::endl;
continue;
}
in >> j;
parse_json(j);
}
}
void ModLoader_load() {
init_data();
}
void ModLoader_start() {
// this method just calls on the handlers of "OnLoad", threaded.
for (const auto& vec : OsintgramCXX::loadedLibraries | std::views::values) {
if (vec.handler_onLoad != nullptr)
vec.handler_onLoad();
}
}
void ModLoader_stop() {
for (const auto& [handle, vec] : OsintgramCXX::loadedLibraries) {
if (vec.handler_onExit != nullptr)
vec.handler_onExit();
#ifdef __linux__
if (handle)
dlclose(handle);
#endif
#ifdef _WIN32
if (handle)
FreeLibrary((HMODULE)handle);
#endif
}
}
namespace OsintgramCXX {
std::map<void*, LibraryEntry> loadedLibraries;
}