-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathloader.cpp
More file actions
500 lines (433 loc) · 16.6 KB
/
Copy pathloader.cpp
File metadata and controls
500 lines (433 loc) · 16.6 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/*
* Copyright (C) 2013-2014 LINK/2012 <dma_2012@hotmail.com>
* Licensed under the MIT License, see LICENSE at top level directory.
*
*/
#include <stdinc.hpp>
#include "loader.hpp"
#include <unicode.hpp>
using namespace modloader;
#ifndef NDEBUG
#include <debugger.hpp>
#endif
extern int InstallExceptionCatcher(void (*cb)(const char* buffer));
#define USE_TEST 0
REGISTER_ML_NULL();
// Mod Loader object
Loader loader;
static HINSTANCE hLoaderModule = NULL;
static std::string MakePathRelativeTo(const std::string& path, const std::string& base)
{
if(path.size() >= base.size() && !_strnicmp(path.c_str(), base.c_str(), base.size()))
return path.substr(base.size());
return path;
}
/*
* DllMain
* Entry-point
*/
extern "C"
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if(fdwReason == DLL_PROCESS_ATTACH)
{
hLoaderModule = hinstDLL;
if(!loader.Patch())
return FALSE;
}
return TRUE;
}
/*
* Loader::Patch
* Patches the game code to run the loader
*/
bool Loader::Patch()
{
typedef function_hooker_stdcall<0x8246EC, int(HINSTANCE, HINSTANCE, LPSTR, int)> winmain_hook;
typedef function_hooker<0x53ECBD, void(int)> ridle_hook;
typedef function_hooker<0x53ECCB, void(int)> rfidle_hook; // Actually void() but... meh
auto& gvm = injector::address_manager::singleton();
gvm.set_name("Mod Loader");
// Check if we have WinMain proc address, otherwise this game isn't supported
if(try_address(winmain_hook::addr))
{
if(injector::ReadMemory<int>(0xC920E8)) // RwInitialized -- should enter only when using the mss32 loader on III/VC
{
const char* buf = "You installed Mod Loader wrongly!\n\n"
"You need Ultimate ASI Loader, and modloader.asi must be in the 'scripts/' directory.\n\n"
"Please refer to the 'Readme.txt' or 'Leia-me.txt' for more information.";
this->Error(buf);
return false;
}
// Hook WinMain to run mod loader
injector::make_static_hook<winmain_hook>([this](winmain_hook::func_type WinMain,
HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// Avoind circular looping forever
static bool bRan = false;
if(bRan) return WinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
bRan = true;
#ifndef NDEBUG
auto& gvm = injector::address_manager::singleton();
if(!gvm.IsSA())
{
static int& gGameState = *mem_ptr(0xC8D4C0).get<int>();
gGameState = 5; // skip intro
if(gvm.IsIII())
MakeNOP(raw_ptr(0x5811F8), 10);
else if(gvm.IsVC())
MakeNOP(raw_ptr(0x601B3B), 10);
if(gvm.IsIII())
MakeJMP(raw_ptr(0x405DB0), &Loader::Log);
else if(gvm.IsVC())
MakeJMP(raw_ptr(0x401000), &Loader::Log);
// Debugger does not attach properly in III/VC DxWnd, so we need to do it manually.
LaunchDebugger();
}
#endif
// Install exception filter to log crashes
InstallExceptionCatcher([](const char* buffer)
{
Log("\n\n");
LogGameVersion();
Log(buffer);
loader.Shutdown();
});
// To be called each frame
auto CallTick = [this](ridle_hook::func_type Idle, int& i)
{
this->Tick();
return Idle(i);
};
// Do tick hook only if possible
if(try_address(ridle_hook::addr)) make_static_hook<ridle_hook>(CallTick);
if(try_address(rfidle_hook::addr)) make_static_hook<rfidle_hook>(CallTick);
// Startup the loader and call WinMain, Shutdown the loader after WinMain.
// If any mod hooked WinMain at Startup, no conflict will happen, we're takin' care of that
{
this->Startup();
auto WinMain = (winmain_hook::func_type_raw) ReadRelativeOffset(winmain_hook::addr + 1).get();
auto result = WinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
this->Shutdown();
return result;
}
});
return true;
}
else
{
char buf[128];
this->Error("This game is not supported\nGame Info:\n%s", gvm.GetVersionText(buf));
return false;
}
}
/*
* Loader::Startup
* Starts the loader
*/
void Loader::Startup()
{
char rootPath[MAX_PATH];
char moduleFilename[MAX_PATH];
char appDataPath[MAX_PATH];
GetCurrentDirectoryA(sizeof(rootPath), rootPath);
MakeSureStringIsDirectory(this->gamePath = rootPath);
if(hLoaderModule && GetModuleFileNameA(hLoaderModule, moduleFilename, sizeof(moduleFilename)))
{
this->modulePath = moduleFilename;
this->modulePath.erase(this->modulePath.find_last_of("\\/") + 1);
MakeSureStringIsDirectory(this->modulePath);
}
else
this->modulePath = this->gamePath;
std::string rootModloaderPath = this->gamePath + "modloader";
std::string moduleModloaderPath = this->modulePath + "modloader";
// If not running yet and a 'modloader' folder exists, let's start up.
// Prefer the ASI directory, then fall back to the traditional game root folder.
if(!this->bRunning && (IsDirectoryA(rootModloaderPath.c_str()) || IsDirectoryA(moduleModloaderPath.c_str())))
{
// Cleanup the base structure
memset(this, 0, sizeof(modloader_t));
// Initialise configs and counters
this->vkRefresh = VK_F4;
this->bRunning = false;
this->bAutoRefresh = true;
this->bEnableMenu = true;
this->bEnableLog = true;
this->bEnablePlugins = true;
this->maxBytesInLog = 5242880; // 5 MiB
this->currentModId = 0;
this->currentFileId = 0x8000000000000000; // File id should have the hibit set
// Setup root path variables
MakeSureStringIsDirectory(this->gamePath = rootPath);
MakeSureStringIsDirectory(this->modulePath);
this->modloaderPath = IsDirectoryA(moduleModloaderPath.c_str())? moduleModloaderPath : rootModloaderPath;
MakeSureStringIsDirectory(this->modloaderPath);
MakeSureStringIsDirectory(this->modloaderRelativePath = MakePathRelativeTo(this->modloaderPath, this->gamePath));
this->mods = FolderInformation(this->modloaderRelativePath);
// Open the log file
OpenLog();
LogGameVersion();
Log("Using Mod Loader folder \"%s\"", this->modloaderPath.c_str());
// Setup "%ProgramData%/modloader/" variable
if(SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_COMMON_APPDATA|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, appDataPath)))
MakeSureStringIsDirectory(MakeSureStringIsDirectory(this->commonAppDataPath = appDataPath).append("modloader"));
// Setup "%LocalAppData%/modloader/" variable
if(SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, appDataPath)))
MakeSureStringIsDirectory(MakeSureStringIsDirectory(this->localAppDataPath = appDataPath).append("modloader"));
// Setup basic path variables
this->dataPath = ".data/";
this->pluginPath = ".data/plugins/";
this->profilesPath= ".profiles/";
// Setup config file names
this->folderConfigFilename = "modloader.ini";
this->basicConfig = dataPath + "config.ini";
this->pluginConfigFilename = "plugins.ini";
this->folderConfigDefault = modloaderPath + dataPath + "modloader.ini.0";
this->basicConfigDefault = modloaderPath + dataPath + "config.ini.0";
this->pluginConfigDefault = modloaderPath + dataPath + "plugins.ini.0";
// Make sure the important folders exist
if(!MakeSureDirectoryExistA((modloaderPath + dataPath).c_str())
|| !MakeSureDirectoryExistA((modloaderPath + profilesPath).c_str())
|| !MakeSureDirectoryExistA((modloaderPath + pluginPath).c_str())
|| !MakeSureDirectoryExistA(commonAppDataPath.c_str())
|| !MakeSureDirectoryExistA(localAppDataPath.c_str()))
{
Log("Warning: Mod Loader important directories could not be created (1).");
}
else
{
char hash_as_string[128];
std::string normal_path = NormalizePath(this->gamePath);
static_assert(sizeof(size_t) == 4, "%.8x not correct");
sprintf(hash_as_string, "%.8x", modloader::hash(normal_path));
std::string unique_id;
unique_id += "10"; // version of the hashing method, increase if it changes
unique_id += hash_as_string;
this->localAppDataPath += unique_id;
this->commonAppDataPath += unique_id;
MakeSureStringIsDirectory(this->localAppDataPath);
MakeSureStringIsDirectory(this->commonAppDataPath);
if(!MakeSureDirectoryExistA(localAppDataPath.c_str())
|| !MakeSureDirectoryExistA(commonAppDataPath.c_str()))
{
Log("Warning: Mod Loader important directories could not be created (2).");
}
}
// Before loading inis, we should update from the old ini format to the new ini format (ofc only if the ini format is old)
this->UpdateOldConfig();
// Load the basic configuration file
CopyFileA(basicConfigDefault.c_str(), (modloaderPath + basicConfig).c_str(), TRUE);
this->ReadBasicConfig();
// Check if logging is disabled by the basic config file
if(!this->bEnableLog)
{
Log("Logging is disabled. Closing log file...");
CloseLog();
}
// Register exported methods and vars
modloader_t::has_game_started= false;
modloader_t::has_game_loaded = false;
modloader_t::gamepath = this->gamePath.data();
//modloader_t::cachepath = this->cachePath.data();
modloader_t::commonappdata = this->commonAppDataPath.data();
modloader_t::localappdata = this->localAppDataPath.data();
modloader_t::Log = this->Log;
modloader_t::vLog = this->vLog;
modloader_t::Error = this->Error;
modloader_t::CreateSharedData= this->CreateSharedData;
modloader_t::DeleteSharedData= this->DeleteSharedData;
modloader_t::FindSharedData = this->FindSharedData;
// Initialise sub systems
this->ParseCommandLine(); // Parse command line arguments
this->StartupMenu();
this->LoadPlugins(); // Load plugins at /modloader/.data/plugins
this->BeforeFirstScan();
this->ScanAndUpdate(); // Search and install mods at /modloader
this->StartupWatcher(); // Startups the automatic refresher
// Startup successfully
this->bRunning = true;
Log("\nMod Loader has started up!\n");
}
}
/*
* Loader::Shutdown
* Shut downs the loader
*/
void Loader::Shutdown()
{
if(this->bRunning)
{
// Unload the plugins
Log("\nShutting down Mod Loader...");
this->ShutdownWatcher();
this->ShutdownMenu();
this->UnloadPlugins();
Log("Mod Loader has been shutdown.");
// Finish containers
this->plugins_priority.clear();
this->extMap.clear();
this->mods.Clear();
// Close the log file
this->CloseLog();
this->bRunning = false;
}
}
/*
* Loader::Shutdown
* This is called every frame
*/
void Loader::Tick()
{
static int& gGameState = *mem_ptr(0xC8D4C0).get<int>();
this->has_game_started = (gGameState >= 7);
this->has_game_loaded = (gGameState >= 9);
this->CheckWatcher(); // updates from changes in the filesystem
this->TestHotkeys();
}
/*
* Loader::TestHotkeys
* Test hotkeys for specific actions
*/
void Loader::TestHotkeys()
{
if(false) // Unecessary, we got a menu and we got a automatic refresher
{
static bool prevF4 = false;
static bool currF4 = false;
// Get current hotkey states
currF4 = (GetKeyState(vkRefresh) & 0x8000) != 0;
// Check hotkey states
if(currF4 && !prevF4)
{
this->ScanAndUpdate();
}
// Save previous states
prevF4 = currF4;
}
}
/*
* Loader::LogGameVersion
* Logs the game version into the logging stream
*/
void Loader::LogGameVersion()
{
char buffer[128];
Log("Game version: %s", injector::address_manager::singleton().GetVersionText(buffer));
}
/*
* Loader::BeforeFirstScan
* Performs some important operations before the first scan such as loading modloader.ini and profiles
*/
void Loader::BeforeFirstScan()
{
// Load modloader.ini and .profiles/*, then check out if we have a command line profile to take care of
this->mods.LoadConfigFromINI();
if(this->modprof_cmd.size())
{
if(auto* prof = this->mods.FindProfile(modprof_cmd))
this->mods.SwitchToProfileAsAnonymous(*prof);
else
Log("Warning: Profile \"%s\" received from command line does not exist", modprof_cmd.c_str());
}
// Check for conditional profiles
for(Profile& prof : this->mods.Profiles())
{
auto& module = prof.GetModuleCondition();
if(module.size() && GetModuleHandleA(module.c_str()))
{
this->mods.SwitchToProfileAsAnonymous(prof);
break;
}
}
}
/*
* Loader::ScanAndUpdate
* Rescans and Updates the mods
*/
void Loader::ScanAndUpdate()
{
Updating xup;
mods.Scan();
mods.Update();
}
/*
* Loader::UpdateFromJournal
* Updates mods that changed in the last few seconds specified in the journal
*/
void Loader::UpdateFromJournal(const Journal& journal)
{
Updating xup;
mods.Scan(journal);
mods.Update();
}
/*
* Loader::NotifyUpdateForPlugins
* Notify the plugins that we've installed/uninstalled stuff
* This normally happens after a rescan
*/
void Loader::NotifyUpdateForPlugins()
{
for(auto& plugin : this->plugins)
plugin.Update();
}
/*
* Loader::FindHandlerForFile
* Finds the plugin responssible for handling the file @m,
* also the plugins that wants to receive the file at @callme
*/
auto Loader::FindHandlerForFile(modloader::file& m, ref_list<PluginInformation>& callme) -> PluginInformation*
{
PluginInformation* handler = nullptr;
// Iterate on the plugins to find a handler for it
for(PluginInformation& plugin : this->GetPluginsBy(m.filext()))
{
auto state = plugin.FindBehaviour(m);
if(state == BehaviourType::Yes)
{
// We found a handler and behaviour, stop the search immediately, don't check for other callme's
handler = &plugin;
break;
}
else if(state == BehaviourType::CallMe)
{
// This plugin requests this file to be sent for some reason (readme files?)
callme.emplace_back(plugin);
}
}
return handler;
}
/*
* Loader::GetPluginsBy
* Gets a list of plugins sorted for file-behaviour-search.
* That's, sort by priority and extension.
*/
auto Loader::GetPluginsBy(const std::string& extension) -> ref_list<PluginInformation>
{
SimplePriorityPred<PluginInformation> pred_base;
auto list = refs(this->plugins);
// Checks if the specified plugin list contains any plugin 'p'
auto contains = [](ref_list<PluginInformation>& plugins, const PluginInformation& p)
{
return std::any_of(plugins.begin(), plugins.end(), [&p](const PluginInformation& a) { return a == p; });
};
// Predicate to execute the sorting
auto pred = [&, this](const PluginInformation& a, const PluginInformation& b)
{
if(a.priority == b.priority) // If priorities are equal, check for extension!
{
auto it = this->extMap.find(extension);
if(it != extMap.end()) // handleabe extension should have priority over other extensions
{
bool ca = contains(it->second, a);
bool cb = contains(it->second, b);
if(ca && !cb) return true; // a has priority over b
else if(!ca && cb) return false; // b has priority over a
}
}
return pred_base(a, b);
};
// Sort and return
std::sort(list.begin(), list.end(), pred);
return list;
}