From 3dc9e1f9ac4027cfc679b3940895aa075a01f3d6 Mon Sep 17 00:00:00 2001 From: Sirius902 <3645979-Sirius902@users.noreply.gitlab.com> Date: Mon, 23 Oct 2023 12:58:02 -0700 Subject: [PATCH] Code style change and reformat --- .clang-format | 7 +- src/ConsoleLib.cpp | 42 +-- src/ConsoleLib.h | 2 +- src/DCInstance.cpp | 33 +-- src/DCInstance.h | 12 +- src/LuaBackend.cpp | 424 +++++++++++++++--------------- src/LuaBackend.h | 36 +-- src/MemoryLib.h | 613 ++++++++++++++++++++++++-------------------- src/config.cpp | 106 ++++---- src/config.h | 7 +- src/game_info.h | 12 +- src/header_text.cpp | 83 +++--- src/lua_exec.cpp | 256 +++++++++--------- src/main_dll.cpp | 290 +++++++++++---------- src/wil_extra.h | 28 +- 15 files changed, 1029 insertions(+), 922 deletions(-) diff --git a/.clang-format b/.clang-format index 3b06bff..0b47531 100644 --- a/.clang-format +++ b/.clang-format @@ -1,8 +1,5 @@ --- Language: Cpp -BasedOnStyle: Google -ColumnLimit: 120 -AccessModifierOffset: -4 -DerivePointerAlignment: false -IndentWidth: 4 +BasedOnStyle: LLVM +PointerAlignment: Left --- diff --git a/src/ConsoleLib.cpp b/src/ConsoleLib.cpp index 9ed2280..22ddcbb 100644 --- a/src/ConsoleLib.cpp +++ b/src/ConsoleLib.cpp @@ -1,27 +1,27 @@ #include "ConsoleLib.h" void ConsoleLib::MessageOutput(const std::string& Text, int MessageType) { - HANDLE _hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + HANDLE _hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - switch (MessageType) { - case 0: - SetConsoleTextAttribute(_hConsole, 11); - std::cout << "MESSAGE: "; - break; - case 1: - SetConsoleTextAttribute(_hConsole, 10); - std::cout << "SUCCESS: "; - break; - case 2: - SetConsoleTextAttribute(_hConsole, 14); - std::cout << "WARNING: "; - break; - case 3: - SetConsoleTextAttribute(_hConsole, 12); - std::cout << "ERROR: "; - break; - } + switch (MessageType) { + case 0: + SetConsoleTextAttribute(_hConsole, 11); + std::cout << "MESSAGE: "; + break; + case 1: + SetConsoleTextAttribute(_hConsole, 10); + std::cout << "SUCCESS: "; + break; + case 2: + SetConsoleTextAttribute(_hConsole, 14); + std::cout << "WARNING: "; + break; + case 3: + SetConsoleTextAttribute(_hConsole, 12); + std::cout << "ERROR: "; + break; + } - SetConsoleTextAttribute(_hConsole, 7); - std::cout << Text; + SetConsoleTextAttribute(_hConsole, 7); + std::cout << Text; } diff --git a/src/ConsoleLib.h b/src/ConsoleLib.h index 757af88..3ddf8bd 100644 --- a/src/ConsoleLib.h +++ b/src/ConsoleLib.h @@ -8,4 +8,4 @@ namespace ConsoleLib { void MessageOutput(const std::string& Text, int MessageType); -}; // namespace ConsoleLib +}; // namespace ConsoleLib diff --git a/src/DCInstance.cpp b/src/DCInstance.cpp index a8da5de..0b6415a 100644 --- a/src/DCInstance.cpp +++ b/src/DCInstance.cpp @@ -1,35 +1,36 @@ #include "DCInstance.h" void DCInstance::InitializeRPC(const char* applicationID) { - Discord_Initialize(applicationID, NULL, 1, NULL); + Discord_Initialize(applicationID, NULL, 1, NULL); - std::memset(&DCInstance::Presence, 0, sizeof(DCInstance::Presence)); + std::memset(&DCInstance::Presence, 0, sizeof(DCInstance::Presence)); - auto _currTime = std::chrono::system_clock::now().time_since_epoch(); - auto _secondCast = std::chrono::duration_cast(_currTime); + auto _currTime = std::chrono::system_clock::now().time_since_epoch(); + auto _secondCast = + std::chrono::duration_cast(_currTime); - DCInstance::Presence.startTimestamp = _secondCast.count(); - Discord_UpdatePresence(&DCInstance::Presence); + DCInstance::Presence.startTimestamp = _secondCast.count(); + Discord_UpdatePresence(&DCInstance::Presence); } void DCInstance::UpdateDetails(const char* input) { - DCInstance::Presence.details = input; - Discord_UpdatePresence(&DCInstance::Presence); + DCInstance::Presence.details = input; + Discord_UpdatePresence(&DCInstance::Presence); } void DCInstance::UpdateState(const char* input) { - DCInstance::Presence.state = input; - Discord_UpdatePresence(&DCInstance::Presence); + DCInstance::Presence.state = input; + Discord_UpdatePresence(&DCInstance::Presence); } void DCInstance::UpdateLImage(const char* key, const char* text) { - DCInstance::Presence.largeImageKey = key; - DCInstance::Presence.largeImageText = text; - Discord_UpdatePresence(&DCInstance::Presence); + DCInstance::Presence.largeImageKey = key; + DCInstance::Presence.largeImageText = text; + Discord_UpdatePresence(&DCInstance::Presence); } void DCInstance::UpdateSImage(const char* key, const char* text) { - DCInstance::Presence.smallImageKey = key; - DCInstance::Presence.smallImageText = text; - Discord_UpdatePresence(&DCInstance::Presence); + DCInstance::Presence.smallImageKey = key; + DCInstance::Presence.smallImageText = text; + Discord_UpdatePresence(&DCInstance::Presence); } diff --git a/src/DCInstance.h b/src/DCInstance.h index 5026a10..480ee04 100644 --- a/src/DCInstance.h +++ b/src/DCInstance.h @@ -9,12 +9,12 @@ class DCInstance { public: - static inline DiscordRichPresence Presence; + static inline DiscordRichPresence Presence; - static void InitializeRPC(const char* applicationID); + static void InitializeRPC(const char* applicationID); - static void UpdateDetails(const char* input); - static void UpdateState(const char* input); - static void UpdateLImage(const char* key, const char* text); - static void UpdateSImage(const char* key, const char* text); + static void UpdateDetails(const char* input); + static void UpdateState(const char* input); + static void UpdateLImage(const char* key, const char* text); + static void UpdateSImage(const char* key, const char* text); }; diff --git a/src/LuaBackend.cpp b/src/LuaBackend.cpp index 4abefc6..7e812c4 100644 --- a/src/LuaBackend.cpp +++ b/src/LuaBackend.cpp @@ -6,33 +6,36 @@ namespace fs = std::filesystem; -LuaBackend::LuaBackend(const std::vector& ScriptPaths, std::uint64_t BaseInput) { - frameLimit = 16; - LoadScripts(ScriptPaths, BaseInput); +LuaBackend::LuaBackend(const std::vector& ScriptPaths, + std::uint64_t BaseInput) { + frameLimit = 16; + LoadScripts(ScriptPaths, BaseInput); } -int LuaBackend::ExceptionHandle(lua_State* luaState, sol::optional thrownException, - sol::string_view description) { - (void)description; +int LuaBackend::ExceptionHandle( + lua_State* luaState, sol::optional thrownException, + sol::string_view description) { + (void)description; - const std::exception _ex = *thrownException; - ConsoleLib::MessageOutput(_ex.what() + '\n', 3); + const std::exception _ex = *thrownException; + ConsoleLib::MessageOutput(_ex.what() + '\n', 3); - return sol::stack::push(luaState, _ex.what()); + return sol::stack::push(luaState, _ex.what()); } -void LuaBackend::LoadScripts(const std::vector& ScriptPaths, std::uint64_t BaseInput) { - loadedScripts.clear(); +void LuaBackend::LoadScripts(const std::vector& ScriptPaths, + std::uint64_t BaseInput) { + loadedScripts.clear(); - for (auto scriptsDir : ScriptPaths) { - if (!fs::is_directory(scriptsDir)) { - continue; - } + for (auto scriptsDir : ScriptPaths) { + if (!fs::is_directory(scriptsDir)) { + continue; + } - for (auto _path : fs::directory_iterator(scriptsDir)) { - auto _script = std::make_unique(); + for (auto _path : fs::directory_iterator(scriptsDir)) { + auto _script = std::make_unique(); - // clang-format off + // clang-format off _script->luaState.open_libraries( sol::lib::base, sol::lib::package, @@ -45,196 +48,207 @@ void LuaBackend::LoadScripts(const std::vector& ScriptPaths, std::uint sol::lib::bit32, sol::lib::utf8 ); - // clang-format on - - _script->luaState.set_exception_handler(&ExceptionHandle); - - SetFunctions(&_script->luaState); - - fs::path _luaPath = scriptsDir / L"io_packages" / L"?.lua"; - fs::path _dllPath = scriptsDir / L"io_packages" / L"?.dll"; - - _script->luaState["package"]["path"] = _luaPath.string(); - _script->luaState["package"]["cpath"] = _dllPath.string(); - - fs::path _loadPath = scriptsDir / L"io_load"; - - _script->luaState["LOAD_PATH"] = _loadPath.string(); - _script->luaState["SCRIPT_PATH"] = scriptsDir.string(); - _script->luaState["CHEATS_PATH"] = "NOT_AVAILABLE"; - - fs::path _pathFull = MemoryLib::PName; - auto _pathExe = _pathFull.filename().string(); - - _script->luaState["ENGINE_VERSION"] = 5; - _script->luaState["ENGINE_TYPE"] = "BACKEND"; - _script->luaState["GAME_ID"] = CRC::Calculate(_pathExe.c_str(), _pathExe.length(), CRC::CRC_32()); - _script->luaState["BASE_ADDR"] = BaseInput; - - const auto _filePath = _path.path(); - const auto _filePathStr = _filePath.string(); - - if (_filePath.extension() == ".lua") { - _script->luaState["LUA_NAME"] = _filePath.filename().string(); - - ConsoleLib::MessageOutput("Found script: \"" + _filePathStr + "\" Initializing...\n", 0); - - auto _result = _script->luaState.script_file(_filePathStr, &sol::script_pass_on_error); - - _script->initFunction = _script->luaState["_OnInit"]; - _script->frameFunction = _script->luaState["_OnFrame"]; - - if (_result.valid()) { - if (!_script->initFunction && !_script->frameFunction) { - ConsoleLib::MessageOutput( - "No event handlers exist or all of them have " - "errors.\n", - 3); - ConsoleLib::MessageOutput( - "Initialization of this script cannot " - "continue...\n", - 3); - return; - } - - if (!_script->initFunction) - ConsoleLib::MessageOutput( - "The event handler for initialization either has " - "errors or " - "does not exist.\n", - 2); - - if (!_script->frameFunction) - ConsoleLib::MessageOutput( - "The event handler for framedraw either has errors " - "or does not " - "exist.\n", - 2); - - ConsoleLib::MessageOutput("Initialization of this script was successful!\n\n", 1); - - loadedScripts.push_back(std::move(_script)); - } else { - sol::error err = _result; - ConsoleLib::MessageOutput(err.what() + '\n', 3); - ConsoleLib::MessageOutput("Initialization of this script was aborted.\n", 3); - } - } + // clang-format on + + _script->luaState.set_exception_handler(&ExceptionHandle); + + SetFunctions(&_script->luaState); + + fs::path _luaPath = scriptsDir / L"io_packages" / L"?.lua"; + fs::path _dllPath = scriptsDir / L"io_packages" / L"?.dll"; + + _script->luaState["package"]["path"] = _luaPath.string(); + _script->luaState["package"]["cpath"] = _dllPath.string(); + + fs::path _loadPath = scriptsDir / L"io_load"; + + _script->luaState["LOAD_PATH"] = _loadPath.string(); + _script->luaState["SCRIPT_PATH"] = scriptsDir.string(); + _script->luaState["CHEATS_PATH"] = "NOT_AVAILABLE"; + + fs::path _pathFull = MemoryLib::PName; + auto _pathExe = _pathFull.filename().string(); + + _script->luaState["ENGINE_VERSION"] = 5; + _script->luaState["ENGINE_TYPE"] = "BACKEND"; + _script->luaState["GAME_ID"] = + CRC::Calculate(_pathExe.c_str(), _pathExe.length(), CRC::CRC_32()); + _script->luaState["BASE_ADDR"] = BaseInput; + + const auto _filePath = _path.path(); + const auto _filePathStr = _filePath.string(); + + if (_filePath.extension() == ".lua") { + _script->luaState["LUA_NAME"] = _filePath.filename().string(); + + ConsoleLib::MessageOutput( + "Found script: \"" + _filePathStr + "\" Initializing...\n", 0); + + auto _result = _script->luaState.script_file( + _filePathStr, &sol::script_pass_on_error); + + _script->initFunction = _script->luaState["_OnInit"]; + _script->frameFunction = _script->luaState["_OnFrame"]; + + if (_result.valid()) { + if (!_script->initFunction && !_script->frameFunction) { + ConsoleLib::MessageOutput( + "No event handlers exist or all of them have " + "errors.\n", + 3); + ConsoleLib::MessageOutput("Initialization of this script cannot " + "continue...\n", + 3); + return; + } + + if (!_script->initFunction) + ConsoleLib::MessageOutput( + "The event handler for initialization either has " + "errors or " + "does not exist.\n", + 2); + + if (!_script->frameFunction) + ConsoleLib::MessageOutput( + "The event handler for framedraw either has errors " + "or does not " + "exist.\n", + 2); + + ConsoleLib::MessageOutput( + "Initialization of this script was successful!\n\n", 1); + + loadedScripts.push_back(std::move(_script)); + } else { + sol::error err = _result; + ConsoleLib::MessageOutput(err.what() + '\n', 3); + ConsoleLib::MessageOutput( + "Initialization of this script was aborted.\n", 3); } + } } + } } void LuaBackend::SetFunctions(LuaState* _state) { - _state->set_function("ReadByte", MemoryLib::ReadByte); - _state->set_function("ReadShort", MemoryLib::ReadShort); - _state->set_function("ReadInt", MemoryLib::ReadInt); - _state->set_function("ReadLong", MemoryLib::ReadLong); - _state->set_function("ReadFloat", MemoryLib::ReadFloat); - _state->set_function("ReadBoolean", MemoryLib::ReadBool); - _state->set_function("ReadArray", MemoryLib::ReadBytes); - _state->set_function("ReadString", MemoryLib::ReadString); - - _state->set_function("WriteByte", MemoryLib::WriteByte); - _state->set_function("WriteShort", MemoryLib::WriteShort); - _state->set_function("WriteInt", MemoryLib::WriteInt); - _state->set_function("WriteLong", MemoryLib::WriteLong); - _state->set_function("WriteFloat", MemoryLib::WriteFloat); - _state->set_function("WriteBoolean", MemoryLib::WriteBool); - _state->set_function("WriteArray", MemoryLib::WriteBytes); - _state->set_function("WriteString", MemoryLib::WriteString); - _state->set_function("WriteExec", MemoryLib::WriteExec); - _state->set_function("GetPointer", MemoryLib::GetPointer); - - _state->set_function("ReadByteA", MemoryLib::ReadByteAbsolute); - _state->set_function("ReadShortA", MemoryLib::ReadShortAbsolute); - _state->set_function("ReadIntA", MemoryLib::ReadIntAbsolute); - _state->set_function("ReadLongA", MemoryLib::ReadLongAbsolute); - _state->set_function("ReadFloatA", MemoryLib::ReadFloatAbsolute); - _state->set_function("ReadBooleanA", MemoryLib::ReadBoolAbsolute); - _state->set_function("ReadArrayA", MemoryLib::ReadBytesAbsolute); - _state->set_function("ReadStringA", MemoryLib::ReadStringAbsolute); - - _state->set_function("WriteByteA", MemoryLib::WriteByteAbsolute); - _state->set_function("WriteShortA", MemoryLib::WriteShortAbsolute); - _state->set_function("WriteIntA", MemoryLib::WriteIntAbsolute); - _state->set_function("WriteLongA", MemoryLib::WriteLongAbsolute); - _state->set_function("WriteFloatA", MemoryLib::WriteFloatAbsolute); - _state->set_function("WriteBooleanA", MemoryLib::WriteBoolAbsolute); - _state->set_function("WriteArrayA", MemoryLib::WriteBytesAbsolute); - _state->set_function("WriteStringA", MemoryLib::WriteStringAbsolute); - _state->set_function("GetPointerA", MemoryLib::GetPointerAbsolute); - - _state->set_function("InitializeRPC", DCInstance::InitializeRPC); - _state->set_function("UpdateDetails", DCInstance::UpdateDetails); - _state->set_function("UpdateState", DCInstance::UpdateState); - _state->set_function("UpdateLImage", DCInstance::UpdateLImage); - _state->set_function("UpdateSImage", DCInstance::UpdateSImage); - - _state->set_function("ULShift32", [](std::uint32_t base, std::uint32_t shift) { return base << shift; }); - - _state->set_function("ConsolePrint", - sol::overload( - [_state](sol::object Text) { - HANDLE _hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - - SetConsoleTextAttribute(_hConsole, 14); - std::cout << "[" + _state->globals()["LUA_NAME"].get() + "] "; - - SetConsoleTextAttribute(_hConsole, 7); - std::cout << Text.as() << '\n'; - }, - - [_state](sol::object Text, int MessageType) { - HANDLE _hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - - SetConsoleTextAttribute(_hConsole, 14); - std::cout << "[" + _state->globals()["LUA_NAME"].get() + "] "; - - switch (MessageType) { - case 0: - SetConsoleTextAttribute(_hConsole, 11); - std::cout << "MESSAGE: "; - break; - case 1: - SetConsoleTextAttribute(_hConsole, 10); - std::cout << "SUCCESS: "; - break; - case 2: - SetConsoleTextAttribute(_hConsole, 14); - std::cout << "WARNING: "; - break; - case 3: - SetConsoleTextAttribute(_hConsole, 12); - std::cout << "ERROR: "; - break; - } - - SetConsoleTextAttribute(_hConsole, 7); - std::cout << Text.as() << '\n'; - })); - - _state->set_function("GetHertz", [this]() { - switch (frameLimit) { - default: - return 60; - case 8: - return 120; - case 4: - return 240; - } - }); - - _state->set_function("SetHertz", [this](int Input) { - switch (Input) { - default: - frameLimit = 16; - break; - case 120: - frameLimit = 8; - break; - case 240: - frameLimit = 4; - break; - } - }); + _state->set_function("ReadByte", MemoryLib::ReadByte); + _state->set_function("ReadShort", MemoryLib::ReadShort); + _state->set_function("ReadInt", MemoryLib::ReadInt); + _state->set_function("ReadLong", MemoryLib::ReadLong); + _state->set_function("ReadFloat", MemoryLib::ReadFloat); + _state->set_function("ReadBoolean", MemoryLib::ReadBool); + _state->set_function("ReadArray", MemoryLib::ReadBytes); + _state->set_function("ReadString", MemoryLib::ReadString); + + _state->set_function("WriteByte", MemoryLib::WriteByte); + _state->set_function("WriteShort", MemoryLib::WriteShort); + _state->set_function("WriteInt", MemoryLib::WriteInt); + _state->set_function("WriteLong", MemoryLib::WriteLong); + _state->set_function("WriteFloat", MemoryLib::WriteFloat); + _state->set_function("WriteBoolean", MemoryLib::WriteBool); + _state->set_function("WriteArray", MemoryLib::WriteBytes); + _state->set_function("WriteString", MemoryLib::WriteString); + _state->set_function("WriteExec", MemoryLib::WriteExec); + _state->set_function("GetPointer", MemoryLib::GetPointer); + + _state->set_function("ReadByteA", MemoryLib::ReadByteAbsolute); + _state->set_function("ReadShortA", MemoryLib::ReadShortAbsolute); + _state->set_function("ReadIntA", MemoryLib::ReadIntAbsolute); + _state->set_function("ReadLongA", MemoryLib::ReadLongAbsolute); + _state->set_function("ReadFloatA", MemoryLib::ReadFloatAbsolute); + _state->set_function("ReadBooleanA", MemoryLib::ReadBoolAbsolute); + _state->set_function("ReadArrayA", MemoryLib::ReadBytesAbsolute); + _state->set_function("ReadStringA", MemoryLib::ReadStringAbsolute); + + _state->set_function("WriteByteA", MemoryLib::WriteByteAbsolute); + _state->set_function("WriteShortA", MemoryLib::WriteShortAbsolute); + _state->set_function("WriteIntA", MemoryLib::WriteIntAbsolute); + _state->set_function("WriteLongA", MemoryLib::WriteLongAbsolute); + _state->set_function("WriteFloatA", MemoryLib::WriteFloatAbsolute); + _state->set_function("WriteBooleanA", MemoryLib::WriteBoolAbsolute); + _state->set_function("WriteArrayA", MemoryLib::WriteBytesAbsolute); + _state->set_function("WriteStringA", MemoryLib::WriteStringAbsolute); + _state->set_function("GetPointerA", MemoryLib::GetPointerAbsolute); + + _state->set_function("InitializeRPC", DCInstance::InitializeRPC); + _state->set_function("UpdateDetails", DCInstance::UpdateDetails); + _state->set_function("UpdateState", DCInstance::UpdateState); + _state->set_function("UpdateLImage", DCInstance::UpdateLImage); + _state->set_function("UpdateSImage", DCInstance::UpdateSImage); + + _state->set_function( + "ULShift32", + [](std::uint32_t base, std::uint32_t shift) { return base << shift; }); + + _state->set_function( + "ConsolePrint", + sol::overload( + [_state](sol::object Text) { + HANDLE _hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + + SetConsoleTextAttribute(_hConsole, 14); + std::cout << "[" + + _state->globals()["LUA_NAME"].get() + + "] "; + + SetConsoleTextAttribute(_hConsole, 7); + std::cout << Text.as() << '\n'; + }, + + [_state](sol::object Text, int MessageType) { + HANDLE _hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + + SetConsoleTextAttribute(_hConsole, 14); + std::cout << "[" + + _state->globals()["LUA_NAME"].get() + + "] "; + + switch (MessageType) { + case 0: + SetConsoleTextAttribute(_hConsole, 11); + std::cout << "MESSAGE: "; + break; + case 1: + SetConsoleTextAttribute(_hConsole, 10); + std::cout << "SUCCESS: "; + break; + case 2: + SetConsoleTextAttribute(_hConsole, 14); + std::cout << "WARNING: "; + break; + case 3: + SetConsoleTextAttribute(_hConsole, 12); + std::cout << "ERROR: "; + break; + } + + SetConsoleTextAttribute(_hConsole, 7); + std::cout << Text.as() << '\n'; + })); + + _state->set_function("GetHertz", [this]() { + switch (frameLimit) { + default: + return 60; + case 8: + return 120; + case 4: + return 240; + } + }); + + _state->set_function("SetHertz", [this](int Input) { + switch (Input) { + default: + frameLimit = 16; + break; + case 120: + frameLimit = 8; + break; + case 240: + frameLimit = 4; + break; + } + }); } diff --git a/src/LuaBackend.h b/src/LuaBackend.h index 1f7960a..01c1f14 100644 --- a/src/LuaBackend.h +++ b/src/LuaBackend.h @@ -15,22 +15,26 @@ using LuaFunction = sol::safe_function; class LuaBackend { public: - struct LuaScript { - LuaState luaState; - LuaFunction initFunction; - LuaFunction frameFunction; - }; - - std::vector> loadedScripts; - int frameLimit; - - LuaBackend(const std::vector& ScriptPaths, std::uint64_t BaseInput); - - static int ExceptionHandle(lua_State* luaState, sol::optional thrownException, - sol::string_view description); - - void LoadScripts(const std::vector& ScriptPaths, std::uint64_t BaseInput); - void SetFunctions(LuaState* _state); + struct LuaScript { + LuaState luaState; + LuaFunction initFunction; + LuaFunction frameFunction; + }; + + std::vector> loadedScripts; + int frameLimit; + + LuaBackend(const std::vector& ScriptPaths, + std::uint64_t BaseInput); + + static int + ExceptionHandle(lua_State* luaState, + sol::optional thrownException, + sol::string_view description); + + void LoadScripts(const std::vector& ScriptPaths, + std::uint64_t BaseInput); + void SetFunctions(LuaState* _state); }; #endif diff --git a/src/MemoryLib.h b/src/MemoryLib.h index 5c31534..696abd7 100644 --- a/src/MemoryLib.h +++ b/src/MemoryLib.h @@ -18,326 +18,377 @@ class MemoryLib { private: - static inline STARTUPINFOW _sInfo; - static inline PROCESS_INFORMATION _pInfo; - static inline bool _bigEndian = false; - - class protect_lock { - private: - std::uintptr_t address; - std::size_t size; - DWORD protection; - bool is_acquired; - - public: - protect_lock(std::uintptr_t address, std::size_t size) - : address(address), size(size), protection(0), is_acquired(false) { - if (VirtualProtect((void*)address, size, PAGE_READWRITE, &protection) != 0) is_acquired = true; - } - - ~protect_lock() { - if (good()) VirtualProtect((void*)address, size, protection, &protection); - } - - bool good() const noexcept { return is_acquired; } - }; - -public: - static inline std::uint64_t ExecAddress; - static inline std::uint64_t BaseAddress; - static inline DWORD PIdentifier = 0; - static inline HANDLE PHandle = NULL; - static inline std::wstring PName; - - static HMODULE FindBaseAddr(HANDLE InputHandle, std::wstring InputName) { - HMODULE hMods[1024]; - DWORD cbNeeded; - unsigned int i; - - if (EnumProcessModules(InputHandle, hMods, sizeof(hMods), &cbNeeded)) { - for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { - std::wstring szModName; - if (wil::GetModuleFileNameExW(InputHandle, hMods[i], szModName)) { - if (szModName.find(InputName) != std::wstring::npos) return hMods[i]; - } - } - } - - return nullptr; - } - - static DWORD FindProcessId(const std::wstring& processName) { - PROCESSENTRY32 processInfo; - processInfo.dwSize = sizeof(processInfo); - - HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); - if (processesSnapshot == INVALID_HANDLE_VALUE) return 0; - - Process32First(processesSnapshot, &processInfo); - if (!processName.compare(processInfo.szExeFile)) { - CloseHandle(processesSnapshot); - return processInfo.th32ProcessID; - } - - while (Process32Next(processesSnapshot, &processInfo)) { - if (!processName.compare(processInfo.szExeFile)) { - CloseHandle(processesSnapshot); - return processInfo.th32ProcessID; - } - } - - CloseHandle(processesSnapshot); - return 0; - } - - static void SetBaseAddr(std::uint64_t InputAddress) { BaseAddress = InputAddress; } - - static int ExecuteProcess(std::wstring InputName, std::uint64_t InputAddress, bool InputEndian) { - ZeroMemory(&_sInfo, sizeof(_sInfo)); - _sInfo.cb = sizeof(_sInfo); - ZeroMemory(&_pInfo, sizeof(_pInfo)); - - if (CreateProcessW(InputName.c_str(), NULL, NULL, NULL, TRUE, 0, NULL, NULL, &_sInfo, &_pInfo) == 0) return -1; + static inline STARTUPINFOW _sInfo; + static inline PROCESS_INFORMATION _pInfo; + static inline bool _bigEndian = false; - BaseAddress = InputAddress; - _bigEndian = InputEndian; + class protect_lock { + private: + std::uintptr_t address; + std::size_t size; + DWORD protection; + bool is_acquired; - return 0; - }; - - static bool LatchProcess(std::wstring InputName, std::uint64_t InputAddress, bool InputEndian) { - ZeroMemory(&_sInfo, sizeof(_sInfo)); - _sInfo.cb = sizeof(_sInfo); - ZeroMemory(&_pInfo, sizeof(_pInfo)); - - PIdentifier = FindProcessId(std::wstring(InputName.begin(), InputName.end())); - PHandle = OpenProcess(PROCESS_ALL_ACCESS, false, PIdentifier); - - wil_extra::GetProcessImageFileNameW(MemoryLib::PHandle, PName); - BaseAddress = InputAddress; - - ExecAddress = (std::uint64_t)FindBaseAddr(PHandle, PName); - _bigEndian = InputEndian; - - if (PHandle == NULL) return false; - - return true; - }; - - static void ExternProcess(DWORD InputID, HANDLE InputH, std::uint64_t InputAddress) { - PIdentifier = InputID; - PHandle = InputH; - - wil_extra::GetProcessImageFileNameW(MemoryLib::PHandle, PName); - - BaseAddress = InputAddress; - ExecAddress = (std::uint64_t)FindBaseAddr(PHandle, PName); - }; - - template , int> = 0> - static T readScalarAbsolute(std::uint64_t Address) { - protect_lock lock(Address, sizeof(T)); - if (!lock.good()) return 0; - - return *reinterpret_cast(Address); + public: + protect_lock(std::uintptr_t address, std::size_t size) + : address(address), size(size), protection(0), is_acquired(false) { + if (VirtualProtect((void*)address, size, PAGE_READWRITE, &protection) != + 0) + is_acquired = true; } - static inline std::uint8_t ReadByteAbsolute(std::uint64_t Address) { - return readScalarAbsolute(Address); + ~protect_lock() { + if (good()) + VirtualProtect((void*)address, size, protection, &protection); } - static inline std::uint16_t ReadShortAbsolute(std::uint64_t Address) { - return readScalarAbsolute(Address); - } - - static inline std::uint32_t ReadIntAbsolute(std::uint64_t Address) { - return readScalarAbsolute(Address); - } - - static inline std::uint64_t ReadLongAbsolute(std::uint64_t Address) { - return readScalarAbsolute(Address); - } - - static inline float ReadFloatAbsolute(std::uint64_t Address) { return readScalarAbsolute(Address); } - - static inline bool ReadBoolAbsolute(std::uint64_t Address) { return ReadByteAbsolute(Address) != 0; } - - static std::vector ReadBytesAbsolute(std::uint64_t Address, int Length) { - std::vector _buffer; - - protect_lock lock(Address, static_cast(Length)); - if (lock.good()) { - _buffer.resize(Length); - std::memcpy(_buffer.data(), (void*)Address, Length); - } + bool good() const noexcept { return is_acquired; } + }; - return _buffer; - } - - static std::string ReadStringAbsolute(std::uint64_t Address, int Length) { - std::string _output; - - protect_lock lock(Address, static_cast(Length)); - if (lock.good()) { - _output.resize(Length); - std::memcpy(_output.data(), (void*)Address, Length); +public: + static inline std::uint64_t ExecAddress; + static inline std::uint64_t BaseAddress; + static inline DWORD PIdentifier = 0; + static inline HANDLE PHandle = NULL; + static inline std::wstring PName; + + static HMODULE FindBaseAddr(HANDLE InputHandle, std::wstring InputName) { + HMODULE hMods[1024]; + DWORD cbNeeded; + unsigned int i; + + if (EnumProcessModules(InputHandle, hMods, sizeof(hMods), &cbNeeded)) { + for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { + std::wstring szModName; + if (wil::GetModuleFileNameExW(InputHandle, hMods[i], szModName)) { + if (szModName.find(InputName) != std::wstring::npos) + return hMods[i]; } - - return _output; + } } - template - static T readScalar(std::uint64_t Address, bool absolute = false) { - if (absolute) { - return readScalarAbsolute(Address); - } else { - return readScalarAbsolute(Address + BaseAddress); - } - } + return nullptr; + } - static inline std::uint8_t ReadByte(std::uint64_t Address, bool absolute = false) { - return readScalar(Address, absolute); - } + static DWORD FindProcessId(const std::wstring& processName) { + PROCESSENTRY32 processInfo; + processInfo.dwSize = sizeof(processInfo); - static inline std::uint16_t ReadShort(std::uint64_t Address, bool absolute = false) { - return readScalar(Address, absolute); - } + HANDLE processesSnapshot = + CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); + if (processesSnapshot == INVALID_HANDLE_VALUE) + return 0; - static inline std::uint32_t ReadInt(std::uint64_t Address, bool absolute = false) { - return readScalar(Address, absolute); + Process32First(processesSnapshot, &processInfo); + if (!processName.compare(processInfo.szExeFile)) { + CloseHandle(processesSnapshot); + return processInfo.th32ProcessID; } - static inline std::uint64_t ReadLong(std::uint64_t Address, bool absolute = false) { - return readScalar(Address, absolute); + while (Process32Next(processesSnapshot, &processInfo)) { + if (!processName.compare(processInfo.szExeFile)) { + CloseHandle(processesSnapshot); + return processInfo.th32ProcessID; + } } - static inline float ReadFloat(std::uint64_t Address, bool absolute = false) { - return readScalar(Address, absolute); - } + CloseHandle(processesSnapshot); + return 0; + } - static inline bool ReadBool(std::uint64_t Address, bool absolute = false) { - return ReadByte(Address, absolute) != 0; - } + static void SetBaseAddr(std::uint64_t InputAddress) { + BaseAddress = InputAddress; + } - static std::vector ReadBytes(std::uint64_t Address, int Length, bool absolute = false) { - if (absolute) { - return ReadBytesAbsolute(Address, Length); - } else { - return ReadBytesAbsolute(Address + BaseAddress, Length); - } - } + static int ExecuteProcess(std::wstring InputName, std::uint64_t InputAddress, + bool InputEndian) { + ZeroMemory(&_sInfo, sizeof(_sInfo)); + _sInfo.cb = sizeof(_sInfo); + ZeroMemory(&_pInfo, sizeof(_pInfo)); - static std::string ReadString(std::uint64_t Address, int Length, bool absolute = false) { - if (absolute) { - return ReadStringAbsolute(Address, Length); - } else { - return ReadStringAbsolute(Address + BaseAddress, Length); - } - } + if (CreateProcessW(InputName.c_str(), NULL, NULL, NULL, TRUE, 0, NULL, NULL, + &_sInfo, &_pInfo) == 0) + return -1; - template , int> = 0> - static void writeScalarAbsolute(std::uint64_t Address, T t) { - protect_lock lock(Address, sizeof(T)); - if (!lock.good()) return; + BaseAddress = InputAddress; + _bigEndian = InputEndian; - *reinterpret_cast(Address) = t; - } + return 0; + }; - static inline void WriteByteAbsolute(std::uint64_t Address, std::uint8_t Input) { - writeScalarAbsolute(Address, Input); - } + static bool LatchProcess(std::wstring InputName, std::uint64_t InputAddress, + bool InputEndian) { + ZeroMemory(&_sInfo, sizeof(_sInfo)); + _sInfo.cb = sizeof(_sInfo); + ZeroMemory(&_pInfo, sizeof(_pInfo)); - static inline void WriteShortAbsolute(std::uint64_t Address, std::uint16_t Input) { - writeScalarAbsolute(Address, Input); - } + PIdentifier = + FindProcessId(std::wstring(InputName.begin(), InputName.end())); + PHandle = OpenProcess(PROCESS_ALL_ACCESS, false, PIdentifier); - static inline void WriteIntAbsolute(std::uint64_t Address, std::uint32_t Input) { - writeScalarAbsolute(Address, Input); - } + wil_extra::GetProcessImageFileNameW(MemoryLib::PHandle, PName); + BaseAddress = InputAddress; - static inline void WriteLongAbsolute(std::uint64_t Address, std::uint64_t Input) { - writeScalarAbsolute(Address, Input); - } + ExecAddress = (std::uint64_t)FindBaseAddr(PHandle, PName); + _bigEndian = InputEndian; - static inline void WriteFloatAbsolute(std::uint64_t Address, float Input) { - writeScalarAbsolute(Address, Input); - } + if (PHandle == NULL) + return false; - static inline void WriteBoolAbsolute(std::uint64_t Address, bool Input) { - WriteByteAbsolute(Address, Input ? 1 : 0); - } + return true; + }; - static void WriteBytesAbsolute(std::uint64_t Address, std::vector Input) { - protect_lock lock(Address, Input.size()); - if (lock.good()) std::memcpy((void*)Address, Input.data(), Input.size()); - } - - static void WriteStringAbsolute(std::uint64_t Address, std::string Input) { - protect_lock lock(Address, Input.size()); - if (lock.good()) std::memcpy((void*)Address, Input.data(), Input.size()); - } + static void ExternProcess(DWORD InputID, HANDLE InputH, + std::uint64_t InputAddress) { + PIdentifier = InputID; + PHandle = InputH; - template - static void writeScalar(std::uint64_t Address, T const& t, bool absolute = false) { - if (absolute) { - writeScalarAbsolute(Address, t); - } else { - writeScalarAbsolute(Address + BaseAddress, t); - } - } + wil_extra::GetProcessImageFileNameW(MemoryLib::PHandle, PName); - static inline void WriteByte(std::uint64_t Address, std::uint8_t Input, bool absolute = false) { - writeScalar(Address, Input, absolute); - } + BaseAddress = InputAddress; + ExecAddress = (std::uint64_t)FindBaseAddr(PHandle, PName); + }; - static inline void WriteShort(std::uint64_t Address, std::uint16_t Input, bool absolute = false) { - writeScalar(Address, Input, absolute); - } + template , int> = 0> + static T readScalarAbsolute(std::uint64_t Address) { + protect_lock lock(Address, sizeof(T)); + if (!lock.good()) + return 0; - static inline void WriteInt(std::uint64_t Address, std::uint32_t Input, bool absolute = false) { - writeScalar(Address, Input, absolute); - } + return *reinterpret_cast(Address); + } - static inline void WriteLong(std::uint64_t Address, std::uint64_t Input, bool absolute = false) { - writeScalar(Address, Input, absolute); - } + static inline std::uint8_t ReadByteAbsolute(std::uint64_t Address) { + return readScalarAbsolute(Address); + } - static inline void WriteFloat(std::uint64_t Address, float Input, bool absolute = false) { - writeScalar(Address, Input, absolute); - } + static inline std::uint16_t ReadShortAbsolute(std::uint64_t Address) { + return readScalarAbsolute(Address); + } - static inline void WriteBool(std::uint64_t Address, bool Input, bool absolute = false) { - WriteByte(Address, Input ? 1 : 0, absolute); - } + static inline std::uint32_t ReadIntAbsolute(std::uint64_t Address) { + return readScalarAbsolute(Address); + } - static void WriteBytes(std::uint64_t Address, std::vector Input, bool absolute = false) { - if (absolute) { - WriteBytesAbsolute(Address, std::move(Input)); - } else { - WriteBytesAbsolute(Address + BaseAddress, std::move(Input)); - } - } + static inline std::uint64_t ReadLongAbsolute(std::uint64_t Address) { + return readScalarAbsolute(Address); + } - static void WriteString(std::uint64_t Address, std::string Input, bool absolute = false) { - if (absolute) { - WriteStringAbsolute(Address, std::move(Input)); - } else { - WriteStringAbsolute(Address + BaseAddress, std::move(Input)); - } - } + static inline float ReadFloatAbsolute(std::uint64_t Address) { + return readScalarAbsolute(Address); + } - static void WriteExec(std::uint64_t Address, std::vector Input) { - protect_lock lock(Address, Input.size()); - if (lock.good()) std::memcpy((void*)(Address + ExecAddress), Input.data(), Input.size()); - } + static inline bool ReadBoolAbsolute(std::uint64_t Address) { + return ReadByteAbsolute(Address) != 0; + } - static inline std::uint64_t GetPointer(std::uint64_t Address, std::uint64_t Offset, bool absolute = false) { - std::uint64_t _temp = ReadLong(Address, absolute); - return _temp + Offset; - } + static std::vector ReadBytesAbsolute(std::uint64_t Address, + int Length) { + std::vector _buffer; - static inline std::uint64_t GetPointerAbsolute(std::uint64_t Address, std::uint64_t Offset) { - std::uint64_t _temp = ReadLongAbsolute(Address); - return _temp + Offset; - } + protect_lock lock(Address, static_cast(Length)); + if (lock.good()) { + _buffer.resize(Length); + std::memcpy(_buffer.data(), (void*)Address, Length); + } + + return _buffer; + } + + static std::string ReadStringAbsolute(std::uint64_t Address, int Length) { + std::string _output; + + protect_lock lock(Address, static_cast(Length)); + if (lock.good()) { + _output.resize(Length); + std::memcpy(_output.data(), (void*)Address, Length); + } + + return _output; + } + + template + static T readScalar(std::uint64_t Address, bool absolute = false) { + if (absolute) { + return readScalarAbsolute(Address); + } else { + return readScalarAbsolute(Address + BaseAddress); + } + } + + static inline std::uint8_t ReadByte(std::uint64_t Address, + bool absolute = false) { + return readScalar(Address, absolute); + } + + static inline std::uint16_t ReadShort(std::uint64_t Address, + bool absolute = false) { + return readScalar(Address, absolute); + } + + static inline std::uint32_t ReadInt(std::uint64_t Address, + bool absolute = false) { + return readScalar(Address, absolute); + } + + static inline std::uint64_t ReadLong(std::uint64_t Address, + bool absolute = false) { + return readScalar(Address, absolute); + } + + static inline float ReadFloat(std::uint64_t Address, bool absolute = false) { + return readScalar(Address, absolute); + } + + static inline bool ReadBool(std::uint64_t Address, bool absolute = false) { + return ReadByte(Address, absolute) != 0; + } + + static std::vector ReadBytes(std::uint64_t Address, int Length, + bool absolute = false) { + if (absolute) { + return ReadBytesAbsolute(Address, Length); + } else { + return ReadBytesAbsolute(Address + BaseAddress, Length); + } + } + + static std::string ReadString(std::uint64_t Address, int Length, + bool absolute = false) { + if (absolute) { + return ReadStringAbsolute(Address, Length); + } else { + return ReadStringAbsolute(Address + BaseAddress, Length); + } + } + + template , int> = 0> + static void writeScalarAbsolute(std::uint64_t Address, T t) { + protect_lock lock(Address, sizeof(T)); + if (!lock.good()) + return; + + *reinterpret_cast(Address) = t; + } + + static inline void WriteByteAbsolute(std::uint64_t Address, + std::uint8_t Input) { + writeScalarAbsolute(Address, Input); + } + + static inline void WriteShortAbsolute(std::uint64_t Address, + std::uint16_t Input) { + writeScalarAbsolute(Address, Input); + } + + static inline void WriteIntAbsolute(std::uint64_t Address, + std::uint32_t Input) { + writeScalarAbsolute(Address, Input); + } + + static inline void WriteLongAbsolute(std::uint64_t Address, + std::uint64_t Input) { + writeScalarAbsolute(Address, Input); + } + + static inline void WriteFloatAbsolute(std::uint64_t Address, float Input) { + writeScalarAbsolute(Address, Input); + } + + static inline void WriteBoolAbsolute(std::uint64_t Address, bool Input) { + WriteByteAbsolute(Address, Input ? 1 : 0); + } + + static void WriteBytesAbsolute(std::uint64_t Address, + std::vector Input) { + protect_lock lock(Address, Input.size()); + if (lock.good()) + std::memcpy((void*)Address, Input.data(), Input.size()); + } + + static void WriteStringAbsolute(std::uint64_t Address, std::string Input) { + protect_lock lock(Address, Input.size()); + if (lock.good()) + std::memcpy((void*)Address, Input.data(), Input.size()); + } + + template + static void writeScalar(std::uint64_t Address, T const& t, + bool absolute = false) { + if (absolute) { + writeScalarAbsolute(Address, t); + } else { + writeScalarAbsolute(Address + BaseAddress, t); + } + } + + static inline void WriteByte(std::uint64_t Address, std::uint8_t Input, + bool absolute = false) { + writeScalar(Address, Input, absolute); + } + + static inline void WriteShort(std::uint64_t Address, std::uint16_t Input, + bool absolute = false) { + writeScalar(Address, Input, absolute); + } + + static inline void WriteInt(std::uint64_t Address, std::uint32_t Input, + bool absolute = false) { + writeScalar(Address, Input, absolute); + } + + static inline void WriteLong(std::uint64_t Address, std::uint64_t Input, + bool absolute = false) { + writeScalar(Address, Input, absolute); + } + + static inline void WriteFloat(std::uint64_t Address, float Input, + bool absolute = false) { + writeScalar(Address, Input, absolute); + } + + static inline void WriteBool(std::uint64_t Address, bool Input, + bool absolute = false) { + WriteByte(Address, Input ? 1 : 0, absolute); + } + + static void WriteBytes(std::uint64_t Address, std::vector Input, + bool absolute = false) { + if (absolute) { + WriteBytesAbsolute(Address, std::move(Input)); + } else { + WriteBytesAbsolute(Address + BaseAddress, std::move(Input)); + } + } + + static void WriteString(std::uint64_t Address, std::string Input, + bool absolute = false) { + if (absolute) { + WriteStringAbsolute(Address, std::move(Input)); + } else { + WriteStringAbsolute(Address + BaseAddress, std::move(Input)); + } + } + + static void WriteExec(std::uint64_t Address, + std::vector Input) { + protect_lock lock(Address, Input.size()); + if (lock.good()) + std::memcpy((void*)(Address + ExecAddress), Input.data(), Input.size()); + } + + static inline std::uint64_t GetPointer(std::uint64_t Address, + std::uint64_t Offset, + bool absolute = false) { + std::uint64_t _temp = ReadLong(Address, absolute); + return _temp + Offset; + } + + static inline std::uint64_t GetPointerAbsolute(std::uint64_t Address, + std::uint64_t Offset) { + std::uint64_t _temp = ReadLongAbsolute(Address); + return _temp + Offset; + } }; diff --git a/src/config.cpp b/src/config.cpp index f2b4db4..a0504a5 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -12,65 +12,69 @@ namespace fs = std::filesystem; Config Config::load(const fs::path& path) { - Config config; - auto data = toml::parse_file(path.u8string()); + Config config; + auto data = toml::parse_file(path.u8string()); - for (const auto& [k, _] : data) { - const auto& entry = data[k]; + for (const auto& [k, _] : data) { + const auto& entry = data[k]; - const auto scripts = entry["scripts"].as_array(); - const auto base = entry["base"].value(); - const auto threadStruct = entry["thread_struct"].value(); - const auto exe = entry["exe"].value(); - const auto game_docs = entry["game_docs"].value(); + const auto scripts = entry["scripts"].as_array(); + const auto base = entry["base"].value(); + const auto threadStruct = entry["thread_struct"].value(); + const auto exe = entry["exe"].value(); + const auto game_docs = entry["game_docs"].value(); - if (!scripts) { - throw std::runtime_error{std::string{k} + ": scripts failed to parse"}; - } - if (!base) { - throw std::runtime_error{std::string{k} + ": base failed to parse"}; - } - if (!threadStruct) { - throw std::runtime_error{std::string{k} + ": threadStruct failed to parse"}; - } - if (!exe) { - throw std::runtime_error{std::string{k} + ": exe failed to parse"}; - } - if (!game_docs) { - throw std::runtime_error{std::string{k} + ": game_docs failed to parse"}; - } - - std::vector paths; - for (std::size_t i = 0; i < scripts->size(); i++) { - const auto& v = *scripts->get_as(i); - const auto str = v["path"].value(); - const auto relative = v["relative"].value(); + if (!scripts) { + throw std::runtime_error{std::string{k} + ": scripts failed to parse"}; + } + if (!base) { + throw std::runtime_error{std::string{k} + ": base failed to parse"}; + } + if (!threadStruct) { + throw std::runtime_error{std::string{k} + + ": threadStruct failed to parse"}; + } + if (!exe) { + throw std::runtime_error{std::string{k} + ": exe failed to parse"}; + } + if (!game_docs) { + throw std::runtime_error{std::string{k} + ": game_docs failed to parse"}; + } - if (!str) { - throw std::runtime_error{std::string{k} + ": at index " + std::to_string(i) + - ": script entry path failed to parse"}; - } - if (!relative) { - throw std::runtime_error{std::string{k} + ": at index " + std::to_string(i) + - ": script entry relative failed to parse"}; - } + std::vector paths; + for (std::size_t i = 0; i < scripts->size(); i++) { + const auto& v = *scripts->get_as(i); + const auto str = v["path"].value(); + const auto relative = v["relative"].value(); - paths.emplace_back(*str, *relative); - } + if (!str) { + throw std::runtime_error{std::string{k} + ": at index " + + std::to_string(i) + + ": script entry path failed to parse"}; + } + if (!relative) { + throw std::runtime_error{std::string{k} + ": at index " + + std::to_string(i) + + ": script entry relative failed to parse"}; + } - config.infos.emplace(*exe, GameInfo{.pointerStructOffset = *threadStruct, - .baseAddress = *base, - .scriptPaths = std::move(paths), - .gameDocsPathStr = *game_docs}); + paths.emplace_back(*str, *relative); } - return config; + config.infos.emplace(*exe, GameInfo{.pointerStructOffset = *threadStruct, + .baseAddress = *base, + .scriptPaths = std::move(paths), + .gameDocsPathStr = *game_docs}); + } + + return config; } -std::optional> Config::gameInfo(const std::u8string& exe) const { - if (auto info = infos.find(exe); info != infos.end()) { - return std::cref(info->second); - } else { - return {}; - } +std::optional> +Config::gameInfo(const std::u8string& exe) const { + if (auto info = infos.find(exe); info != infos.end()) { + return std::cref(info->second); + } else { + return {}; + } } diff --git a/src/config.h b/src/config.h index cd9a247..5820586 100644 --- a/src/config.h +++ b/src/config.h @@ -11,9 +11,10 @@ class Config { private: - std::unordered_map infos; + std::unordered_map infos; public: - static Config load(const std::filesystem::path& path); - std::optional> gameInfo(const std::u8string& exe) const; + static Config load(const std::filesystem::path& path); + std::optional> + gameInfo(const std::u8string& exe) const; }; diff --git a/src/game_info.h b/src/game_info.h index 9639808..0cb0558 100644 --- a/src/game_info.h +++ b/src/game_info.h @@ -5,13 +5,13 @@ #include struct ScriptPath { - std::u8string str; - bool relative; + std::u8string str; + bool relative; }; struct GameInfo { - std::uintptr_t pointerStructOffset; - std::uintptr_t baseAddress; - std::vector scriptPaths; - std::u8string gameDocsPathStr; + std::uintptr_t pointerStructOffset; + std::uintptr_t baseAddress; + std::vector scriptPaths; + std::u8string gameDocsPathStr; }; diff --git a/src/header_text.cpp b/src/header_text.cpp index 268bb1e..819a6f9 100644 --- a/src/header_text.cpp +++ b/src/header_text.cpp @@ -7,54 +7,56 @@ #include template -[[nodiscard]] constexpr static auto generateBlockText(const char (&... lines)[Len]) { - constexpr std::string_view separator = " "; - constexpr std::string_view padding = "="; - constexpr std::size_t edge_pad_amount = 3; +[[nodiscard]] constexpr static auto +generateBlockText(const char (&... lines)[Len]) { + constexpr std::string_view separator = " "; + constexpr std::string_view padding = "="; + constexpr std::size_t edge_pad_amount = 3; - constexpr std::size_t max_line_length = std::max({Len...}) - 1; - constexpr std::size_t num_lines = sizeof...(Len); + constexpr std::size_t max_line_length = std::max({Len...}) - 1; + constexpr std::size_t num_lines = sizeof...(Len); - constexpr std::size_t formatted_line_size = max_line_length + (2 * separator.size()) + (edge_pad_amount * 2); + constexpr std::size_t formatted_line_size = + max_line_length + (2 * separator.size()) + (edge_pad_amount * 2); - constexpr std::size_t text_size = (formatted_line_size + 1) * num_lines + 1; - std::array text; - text[text.size() - 1] = '\0'; + constexpr std::size_t text_size = (formatted_line_size + 1) * num_lines + 1; + std::array text; + text[text.size() - 1] = '\0'; - char* dst = text.data(); - for (const auto src : {(std::string_view{lines, Len - 1})...}) { - std::size_t sep_size = src.empty() ? 0 : separator.size(); - std::size_t total_pad = formatted_line_size - src.size() - (2 * sep_size); - std::size_t right_pad = total_pad / 2; - std::size_t left_pad = total_pad - right_pad; + char* dst = text.data(); + for (const auto src : {(std::string_view{lines, Len - 1})...}) { + std::size_t sep_size = src.empty() ? 0 : separator.size(); + std::size_t total_pad = formatted_line_size - src.size() - (2 * sep_size); + std::size_t right_pad = total_pad / 2; + std::size_t left_pad = total_pad - right_pad; - const auto copy = [](auto& dst, const auto& src) { - std::copy(src.begin(), src.end(), dst); - dst += src.size(); - }; + const auto copy = [](auto& dst, const auto& src) { + std::copy(src.begin(), src.end(), dst); + dst += src.size(); + }; - const auto cylic_copy_n = [](auto& dst, const auto& src, std::size_t n) { - for (std::size_t i = 0; i < n;) { - std::size_t copy_len = std::min(src.size(), n - i); - std::copy(src.begin(), src.begin() + copy_len, dst); - dst += copy_len; - i += copy_len; - } - }; + const auto cylic_copy_n = [](auto& dst, const auto& src, std::size_t n) { + for (std::size_t i = 0; i < n;) { + std::size_t copy_len = std::min(src.size(), n - i); + std::copy(src.begin(), src.begin() + copy_len, dst); + dst += copy_len; + i += copy_len; + } + }; - cylic_copy_n(dst, padding, left_pad); - cylic_copy_n(dst, separator, sep_size); - copy(dst, src); - cylic_copy_n(dst, separator, sep_size); - cylic_copy_n(dst, padding, right_pad); - *dst++ = '\n'; - } + cylic_copy_n(dst, padding, left_pad); + cylic_copy_n(dst, separator, sep_size); + copy(dst, src); + cylic_copy_n(dst, separator, sep_size); + cylic_copy_n(dst, padding, right_pad); + *dst++ = '\n'; + } - return text; + return text; } std::string_view getHeaderText() { - // clang-format off + // clang-format off constexpr static auto headerText = generateBlockText( "", "LuaBackendHook " HOOK_VERSION, @@ -64,7 +66,8 @@ std::string_view getHeaderText() { "Embedded Version", "" ); - // clang-format on - constexpr static auto headerTextView = std::string_view{headerText.begin(), headerText.end()}; - return headerTextView; + // clang-format on + constexpr static auto headerTextView = + std::string_view{headerText.begin(), headerText.end()}; + return headerTextView; } diff --git a/src/lua_exec.cpp b/src/lua_exec.cpp index bf718af..640c3b3 100644 --- a/src/lua_exec.cpp +++ b/src/lua_exec.cpp @@ -23,161 +23,171 @@ static std::chrono::high_resolution_clock::time_point _sClock; static std::chrono::high_resolution_clock::time_point _msClock; void ResetLUA() { - std::printf("\n"); - ConsoleLib::MessageOutput("Reloading...\n\n", 0); - _backend = new LuaBackend(_scriptPaths, MemoryLib::ExecAddress + MemoryLib::BaseAddress); - - if (_backend->loadedScripts.size() == 0) ConsoleLib::MessageOutput("No scripts found! Reload halted!\n\n", 3); - - ConsoleLib::MessageOutput("Executing initialization event handlers...\n\n", 0); - - for (auto& _script : _backend->loadedScripts) - if (_script->initFunction) { - auto _result = _script->initFunction(); - - if (!_result.valid()) { - sol::error _err = _result; - ConsoleLib::MessageOutput(_err.what(), 3); - std::printf("\n\n"); - } - } + std::printf("\n"); + ConsoleLib::MessageOutput("Reloading...\n\n", 0); + _backend = new LuaBackend(_scriptPaths, + MemoryLib::ExecAddress + MemoryLib::BaseAddress); + + if (_backend->loadedScripts.size() == 0) + ConsoleLib::MessageOutput("No scripts found! Reload halted!\n\n", 3); + + ConsoleLib::MessageOutput("Executing initialization event handlers...\n\n", + 0); + + for (auto& _script : _backend->loadedScripts) + if (_script->initFunction) { + auto _result = _script->initFunction(); + + if (!_result.valid()) { + sol::error _err = _result; + ConsoleLib::MessageOutput(_err.what(), 3); + std::printf("\n\n"); + } + } - ConsoleLib::MessageOutput("Reload complete!\n\n", 1); + ConsoleLib::MessageOutput("Reload complete!\n\n", 1); - _msClock = std::chrono::high_resolution_clock::now(); - _sClock = std::chrono::high_resolution_clock::now(); + _msClock = std::chrono::high_resolution_clock::now(); + _sClock = std::chrono::high_resolution_clock::now(); - _requestedReset = false; + _requestedReset = false; } -int EntryLUA(int ProcessID, HANDLE ProcessH, std::uint64_t TargetAddress, std::vector ScriptPaths) { - ShowWindow(GetConsoleWindow(), SW_HIDE); +int EntryLUA(int ProcessID, HANDLE ProcessH, std::uint64_t TargetAddress, + std::vector ScriptPaths) { + ShowWindow(GetConsoleWindow(), SW_HIDE); - std::cout << getHeaderText() << '\n'; + std::cout << getHeaderText() << '\n'; - ConsoleLib::MessageOutput("Initializing LuaEngine v5.0...\n\n", 0); - _scriptPaths = std::move(ScriptPaths); + ConsoleLib::MessageOutput("Initializing LuaEngine v5.0...\n\n", 0); + _scriptPaths = std::move(ScriptPaths); - MemoryLib::ExternProcess(ProcessID, ProcessH, TargetAddress); + MemoryLib::ExternProcess(ProcessID, ProcessH, TargetAddress); - _backend = new LuaBackend(_scriptPaths, MemoryLib::ExecAddress + TargetAddress); - _backend->frameLimit = 16; + _backend = + new LuaBackend(_scriptPaths, MemoryLib::ExecAddress + TargetAddress); + _backend->frameLimit = 16; - if (_backend->loadedScripts.size() == 0) { - ConsoleLib::MessageOutput("No scripts were found! Initialization halted!\n\n", 3); - return -1; + if (_backend->loadedScripts.size() == 0) { + ConsoleLib::MessageOutput( + "No scripts were found! Initialization halted!\n\n", 3); + return -1; + } + + ConsoleLib::MessageOutput("Executing initialization event handlers...\n\n", + 0); + + for (auto& _script : _backend->loadedScripts) + if (_script->initFunction) { + auto _result = _script->initFunction(); + + if (!_result.valid()) { + sol::error _err = _result; + ConsoleLib::MessageOutput(_err.what(), 3); + std::printf("\n\n"); + } } - ConsoleLib::MessageOutput("Executing initialization event handlers...\n\n", 0); - - for (auto& _script : _backend->loadedScripts) - if (_script->initFunction) { - auto _result = _script->initFunction(); + ConsoleLib::MessageOutput("Initialization complete!\n", 1); + ConsoleLib::MessageOutput( + "Press 'F1' to reload all scripts, press 'F2' to toggle the console, " + "press 'F3' to set " + "execution frequency.\n\n", + 0); - if (!_result.valid()) { - sol::error _err = _result; - ConsoleLib::MessageOutput(_err.what(), 3); - std::printf("\n\n"); - } - } - - ConsoleLib::MessageOutput("Initialization complete!\n", 1); - ConsoleLib::MessageOutput( - "Press 'F1' to reload all scripts, press 'F2' to toggle the console, " - "press 'F3' to set " - "execution frequency.\n\n", - 0); + _msClock = std::chrono::high_resolution_clock::now(); + _sClock = std::chrono::high_resolution_clock::now(); - _msClock = std::chrono::high_resolution_clock::now(); - _sClock = std::chrono::high_resolution_clock::now(); - - return 0; + return 0; } void ExecuteLUA() { - if (_requestedReset == false) { - auto _currTime = std::chrono::high_resolution_clock::now(); - auto _sTime = std::chrono::duration_cast(_currTime - _sClock).count(); - - if (GetKeyState(VK_F3) & 0x8000 && _funcThreeState) { - switch (_backend->frameLimit) { - case 16: - _backend->frameLimit = 8; - ConsoleLib::MessageOutput("Frequency set to 120Hz.\n", 0); - break; - case 8: - _backend->frameLimit = 4; - ConsoleLib::MessageOutput("Frequency set to 240Hz.\n", 0); - break; - case 4: - _backend->frameLimit = 16; - ConsoleLib::MessageOutput("Frequency set to 60Hz.\n", 0); - break; - } - - _sTime = 0; - _funcThreeState = false; - _sClock = std::chrono::high_resolution_clock::now(); - } - if (GetKeyState(VK_F2) & 0x8000 && _funcTwoState) { - if (_showConsole) { - ShowWindow(GetConsoleWindow(), SW_HIDE); - _showConsole = false; - } - - else { - ShowWindow(GetConsoleWindow(), SW_RESTORE); - _showConsole = true; - } - - _sTime = 0; - _funcTwoState = false; - _sClock = std::chrono::high_resolution_clock::now(); - } - if (GetKeyState(VK_F1) & 0x8000 && _funcOneState) { - _requestedReset = true; + if (_requestedReset == false) { + auto _currTime = std::chrono::high_resolution_clock::now(); + auto _sTime = std::chrono::duration_cast( + _currTime - _sClock) + .count(); + + if (GetKeyState(VK_F3) & 0x8000 && _funcThreeState) { + switch (_backend->frameLimit) { + case 16: + _backend->frameLimit = 8; + ConsoleLib::MessageOutput("Frequency set to 120Hz.\n", 0); + break; + case 8: + _backend->frameLimit = 4; + ConsoleLib::MessageOutput("Frequency set to 240Hz.\n", 0); + break; + case 4: + _backend->frameLimit = 16; + ConsoleLib::MessageOutput("Frequency set to 60Hz.\n", 0); + break; + } + + _sTime = 0; + _funcThreeState = false; + _sClock = std::chrono::high_resolution_clock::now(); + } + if (GetKeyState(VK_F2) & 0x8000 && _funcTwoState) { + if (_showConsole) { + ShowWindow(GetConsoleWindow(), SW_HIDE); + _showConsole = false; + } + + else { + ShowWindow(GetConsoleWindow(), SW_RESTORE); + _showConsole = true; + } + + _sTime = 0; + _funcTwoState = false; + _sClock = std::chrono::high_resolution_clock::now(); + } + if (GetKeyState(VK_F1) & 0x8000 && _funcOneState) { + _requestedReset = true; - _sTime = 0; - _funcOneState = false; - _sClock = std::chrono::high_resolution_clock::now(); - } + _sTime = 0; + _funcOneState = false; + _sClock = std::chrono::high_resolution_clock::now(); + } - for (int i = 0; i < _backend->loadedScripts.size(); i++) { - auto& _script = _backend->loadedScripts[i]; + for (int i = 0; i < _backend->loadedScripts.size(); i++) { + auto& _script = _backend->loadedScripts[i]; - if (_script->frameFunction) { - auto _result = _script->frameFunction(); + if (_script->frameFunction) { + auto _result = _script->frameFunction(); - if (!_result.valid()) { - sol::error _err = _result; - ConsoleLib::MessageOutput(_err.what(), 3); - std::printf("\n\n"); + if (!_result.valid()) { + sol::error _err = _result; + ConsoleLib::MessageOutput(_err.what(), 3); + std::printf("\n\n"); - _backend->loadedScripts.erase(_backend->loadedScripts.begin() + i); - } - } + _backend->loadedScripts.erase(_backend->loadedScripts.begin() + i); } + } + } - _msClock = std::chrono::high_resolution_clock::now(); + _msClock = std::chrono::high_resolution_clock::now(); - if (_sTime > 250) { - _funcOneState = true; - _funcTwoState = true; - _funcThreeState = true; - _sClock = std::chrono::high_resolution_clock::now(); - } + if (_sTime > 250) { + _funcOneState = true; + _funcTwoState = true; + _funcThreeState = true; + _sClock = std::chrono::high_resolution_clock::now(); } + } - else - ResetLUA(); + else + ResetLUA(); } bool CheckLUA() { - auto _int = MemoryLib::ReadInt(0); + auto _int = MemoryLib::ReadInt(0); - if (_int == 0) return false; + if (_int == 0) + return false; - return true; + return true; } int VersionLUA() { return 128; } diff --git a/src/main_dll.cpp b/src/main_dll.cpp index fb820c9..043fdb1 100644 --- a/src/main_dll.cpp +++ b/src/main_dll.cpp @@ -34,7 +34,9 @@ namespace ranges = std::ranges; using MiniDumpWriteDumpProc = decltype(&MiniDumpWriteDump_); -using DirectInput8CreateProc = HRESULT(WINAPI*)(HINSTANCE hinst, DWORD dwVersion, LPCVOID riidltf, LPVOID* ppvOut, +using DirectInput8CreateProc = HRESULT(WINAPI*)(HINSTANCE hinst, + DWORD dwVersion, + LPCVOID riidltf, LPVOID* ppvOut, LPVOID punkOuter); using GameFrameProc = std::uint64_t(__cdecl*)(void* rcx); @@ -51,192 +53,210 @@ std::optional gameInfo; std::uint64_t moduleAddress = 0; template - requires std::same_as, std::uintptr_t> -std::optional followPointerChain(std::uintptr_t start, const R& offsets) { - std::uintptr_t current = start; + requires std::same_as, std::uintptr_t> +std::optional followPointerChain(std::uintptr_t start, + const R& offsets) { + std::uintptr_t current = start; - for (auto it = ranges::begin(offsets); it != ranges::end(offsets); ++it) { - if (current == 0) return {}; + for (auto it = ranges::begin(offsets); it != ranges::end(offsets); ++it) { + if (current == 0) + return {}; - if (it != ranges::end(offsets) - 1) { - current = *reinterpret_cast(current + *it); - } else { - current += *it; - } + if (it != ranges::end(offsets) - 1) { + current = *reinterpret_cast(current + *it); + } else { + current += *it; } + } - return current; + return current; } std::uint64_t __cdecl frameHook(void* rcx) { - ExecuteLUA(); - return frameProc(rcx); + ExecuteLUA(); + return frameProc(rcx); } LONG WINAPI crashDumpHandler(PEXCEPTION_POINTERS exceptionPointers) { - HANDLE file = CreateFileW(L"CrashDump.dmp", GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFileW(L"CrashDump.dmp", GENERIC_READ | GENERIC_WRITE, 0, + NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (file != INVALID_HANDLE_VALUE) { - MINIDUMP_EXCEPTION_INFORMATION mdei; + if (file != INVALID_HANDLE_VALUE) { + MINIDUMP_EXCEPTION_INFORMATION mdei; - mdei.ThreadId = GetCurrentThreadId(); - mdei.ExceptionPointers = exceptionPointers; - mdei.ClientPointers = TRUE; + mdei.ThreadId = GetCurrentThreadId(); + mdei.ExceptionPointers = exceptionPointers; + mdei.ClientPointers = TRUE; - (*writeDumpProc)(GetCurrentProcess(), GetCurrentProcessId(), file, MiniDumpNormal, &mdei, 0, 0); + (*writeDumpProc)(GetCurrentProcess(), GetCurrentProcessId(), file, + MiniDumpNormal, &mdei, 0, 0); - CloseHandle(file); - } + CloseHandle(file); + } - return EXCEPTION_EXECUTE_HANDLER; + return EXCEPTION_EXECUTE_HANDLER; } bool hookGame() { - static_assert(sizeof(std::uint64_t) == sizeof(std::uintptr_t)); + static_assert(sizeof(std::uint64_t) == sizeof(std::uintptr_t)); - constexpr static auto frameProcOffsets = std::to_array({0x3E8, 0x0, 0x20}); - constexpr static auto graphicsProcOffsets = std::to_array({0x2D8}); + constexpr static auto frameProcOffsets = + std::to_array({0x3E8, 0x0, 0x20}); + constexpr static auto graphicsProcOffsets = + std::to_array({0x2D8}); - std::uintptr_t pointerStruct = moduleAddress + gameInfo->pointerStructOffset; + std::uintptr_t pointerStruct = moduleAddress + gameInfo->pointerStructOffset; - if (auto ptr = followPointerChain(pointerStruct, frameProcOffsets)) { - frameProcPtr = reinterpret_cast(*ptr); - } else { - return false; - } + if (auto ptr = followPointerChain(pointerStruct, frameProcOffsets)) { + frameProcPtr = reinterpret_cast(*ptr); + } else { + return false; + } - if (*frameProcPtr == nullptr) return false; + if (*frameProcPtr == nullptr) + return false; - DWORD originalProt = 0; - VirtualProtect(frameProcPtr, sizeof(frameProcPtr), PAGE_READWRITE, &originalProt); - frameProc = *frameProcPtr; - *frameProcPtr = frameHook; - VirtualProtect(frameProcPtr, sizeof(frameProcPtr), originalProt, &originalProt); + DWORD originalProt = 0; + VirtualProtect(frameProcPtr, sizeof(frameProcPtr), PAGE_READWRITE, + &originalProt); + frameProc = *frameProcPtr; + *frameProcPtr = frameHook; + VirtualProtect(frameProcPtr, sizeof(frameProcPtr), originalProt, + &originalProt); - SetUnhandledExceptionFilter(crashDumpHandler); + SetUnhandledExceptionFilter(crashDumpHandler); - return true; + return true; } DWORD WINAPI entry(LPVOID lpParameter) { - (void)lpParameter; + (void)lpParameter; - std::wstring modulePathStr; - wil::GetModuleFileNameW(nullptr, modulePathStr); + std::wstring modulePathStr; + wil::GetModuleFileNameW(nullptr, modulePathStr); - fs::path modulePath = fs::path{modulePathStr}; - fs::path moduleDir = modulePath.parent_path(); - std::wstring moduleNameW = modulePath.filename(); + fs::path modulePath = fs::path{modulePathStr}; + fs::path moduleDir = modulePath.parent_path(); + std::wstring moduleNameW = modulePath.filename(); - std::u8string moduleName = - ztd::text::transcode(moduleNameW, ztd::text::wide_utf16, ztd::text::utf8, ztd::text::replacement_handler); + std::u8string moduleName = + ztd::text::transcode(moduleNameW, ztd::text::wide_utf16, ztd::text::utf8, + ztd::text::replacement_handler); - try { - config = Config::load("LuaBackend.toml"); - auto entry = config->gameInfo(moduleName); - if (entry) { - gameInfo = *entry; - } else { - return 0; - } + try { + config = Config::load("LuaBackend.toml"); + auto entry = config->gameInfo(moduleName); + if (entry) { + gameInfo = *entry; + } else { + return 0; + } - moduleAddress = (std::uint64_t)GetModuleHandleW(nullptr); - std::uint64_t baseAddress = moduleAddress + gameInfo->baseAddress; - - fs::path gameDocsRoot = [&]() { - PWSTR docsRootStr; - SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &docsRootStr); - - return fs::path{docsRootStr} / gameInfo->gameDocsPathStr; - }(); - - std::vector scriptPaths; - for (const auto& path : gameInfo->scriptPaths) { - if (path.relative) { - fs::path gameScriptsPath = gameDocsRoot / path.str; - if (fs::exists(gameScriptsPath)) { - scriptPaths.push_back(gameScriptsPath); - } - } else { - fs::path gameScriptsPath = fs::path{path.str}; - if (fs::exists(gameScriptsPath)) { - scriptPaths.push_back(gameScriptsPath); - } - } - } + moduleAddress = (std::uint64_t)GetModuleHandleW(nullptr); + std::uint64_t baseAddress = moduleAddress + gameInfo->baseAddress; - if (!scriptPaths.empty()) { - AllocConsole(); - SetConsoleOutputCP(CP_UTF8); - FILE* f; - freopen_s(&f, "CONOUT$", "w", stdout); - - if (EntryLUA(GetCurrentProcessId(), GetCurrentProcess(), baseAddress, std::move(scriptPaths)) == 0) { - // TODO: Hook after game initialization is done. - while (!hookGame()) { - std::this_thread::sleep_for(std::chrono::milliseconds(16)); - } - } else { - std::cout << "Failed to initialize internal LuaBackend!" << std::endl; - } + fs::path gameDocsRoot = [&]() { + PWSTR docsRootStr; + SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &docsRootStr); + + return fs::path{docsRootStr} / gameInfo->gameDocsPathStr; + }(); + + std::vector scriptPaths; + for (const auto& path : gameInfo->scriptPaths) { + if (path.relative) { + fs::path gameScriptsPath = gameDocsRoot / path.str; + if (fs::exists(gameScriptsPath)) { + scriptPaths.push_back(gameScriptsPath); } - } catch (std::exception& e) { - std::string msg = "entry exception: " + std::string(e.what()) + "\n\nScripts failed to load."; - std::wstring wmsg = - ztd::text::transcode(msg, ztd::text::compat_utf8, ztd::text::wide_utf16, ztd::text::replacement_handler); - MessageBoxW(NULL, wmsg.c_str(), L"LuaBackendHook", MB_ICONERROR | MB_OK); + } else { + fs::path gameScriptsPath = fs::path{path.str}; + if (fs::exists(gameScriptsPath)) { + scriptPaths.push_back(gameScriptsPath); + } + } } - return 0; + if (!scriptPaths.empty()) { + AllocConsole(); + SetConsoleOutputCP(CP_UTF8); + FILE* f; + freopen_s(&f, "CONOUT$", "w", stdout); + + if (EntryLUA(GetCurrentProcessId(), GetCurrentProcess(), baseAddress, + std::move(scriptPaths)) == 0) { + // TODO: Hook after game initialization is done. + while (!hookGame()) { + std::this_thread::sleep_for(std::chrono::milliseconds(16)); + } + } else { + std::cout << "Failed to initialize internal LuaBackend!" << std::endl; + } + } + } catch (std::exception& e) { + std::string msg = "entry exception: " + std::string(e.what()) + + "\n\nScripts failed to load."; + std::wstring wmsg = + ztd::text::transcode(msg, ztd::text::compat_utf8, ztd::text::wide_utf16, + ztd::text::replacement_handler); + MessageBoxW(NULL, wmsg.c_str(), L"LuaBackendHook", MB_ICONERROR | MB_OK); + } + + return 0; } BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) { - (void)hinstDLL; - (void)lpReserved; - static HMODULE dbgHelp = nullptr; - static HMODULE dinput8 = nullptr; - - switch (fdwReason) { - case DLL_PROCESS_ATTACH: { - std::wstring systemDirectoryStr; - wil::GetSystemDirectoryW(systemDirectoryStr); - fs::path dllPath = fs::path{systemDirectoryStr} / L"DBGHELP.dll"; + (void)hinstDLL; + (void)lpReserved; + static HMODULE dbgHelp = nullptr; + static HMODULE dinput8 = nullptr; - dbgHelp = LoadLibraryW(dllPath.wstring().c_str()); - writeDumpProc = (MiniDumpWriteDumpProc)GetProcAddress(dbgHelp, "MiniDumpWriteDump"); + switch (fdwReason) { + case DLL_PROCESS_ATTACH: { + std::wstring systemDirectoryStr; + wil::GetSystemDirectoryW(systemDirectoryStr); + fs::path dllPath = fs::path{systemDirectoryStr} / L"DBGHELP.dll"; - fs::path dinput8Path = fs::path{systemDirectoryStr} / L"DINPUT8.dll"; + dbgHelp = LoadLibraryW(dllPath.wstring().c_str()); + writeDumpProc = + (MiniDumpWriteDumpProc)GetProcAddress(dbgHelp, "MiniDumpWriteDump"); - dinput8 = LoadLibraryW(dinput8Path.wstring().c_str()); - createProc = (DirectInput8CreateProc)GetProcAddress(dinput8, "DirectInput8Create"); + fs::path dinput8Path = fs::path{systemDirectoryStr} / L"DINPUT8.dll"; - if (CreateThread(nullptr, 0, entry, nullptr, 0, nullptr) == nullptr) { - return FALSE; - } + dinput8 = LoadLibraryW(dinput8Path.wstring().c_str()); + createProc = + (DirectInput8CreateProc)GetProcAddress(dinput8, "DirectInput8Create"); - break; - } - case DLL_PROCESS_DETACH: { - FreeLibrary(dbgHelp); - FreeLibrary(dinput8); - break; - } - default: - break; + if (CreateThread(nullptr, 0, entry, nullptr, 0, nullptr) == nullptr) { + return FALSE; } - return TRUE; + break; + } + case DLL_PROCESS_DETACH: { + FreeLibrary(dbgHelp); + FreeLibrary(dinput8); + break; + } + default: + break; + } + + return TRUE; } extern "C" __declspec(dllexport) HRESULT WINAPI - DirectInput8Create(HINSTANCE hinst, DWORD dwVersion, LPCVOID riidltf, LPVOID* ppvOut, LPVOID punkOuter) { - return createProc(hinst, dwVersion, riidltf, ppvOut, punkOuter); + DirectInput8Create(HINSTANCE hinst, DWORD dwVersion, LPCVOID riidltf, + LPVOID* ppvOut, LPVOID punkOuter) { + return createProc(hinst, dwVersion, riidltf, ppvOut, punkOuter); } extern "C" __declspec(dllexport) BOOL WINAPI - MiniDumpWriteDump(HANDLE hProcess, DWORD ProcessId, HANDLE hFile, MINIDUMP_TYPE DumpType, - PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, + MiniDumpWriteDump(HANDLE hProcess, DWORD ProcessId, HANDLE hFile, + MINIDUMP_TYPE DumpType, + PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, + PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, PMINIDUMP_CALLBACK_INFORMATION CallbackParam) { - return writeDumpProc(hProcess, ProcessId, hFile, DumpType, ExceptionParam, UserStreamParam, CallbackParam); + return writeDumpProc(hProcess, ProcessId, hFile, DumpType, ExceptionParam, + UserStreamParam, CallbackParam); } diff --git a/src/wil_extra.h b/src/wil_extra.h index c2c14aa..f0b59c9 100644 --- a/src/wil_extra.h +++ b/src/wil_extra.h @@ -7,17 +7,19 @@ namespace wil_extra { template -HRESULT GetProcessImageFileNameW(HANDLE hProcess, string_type& result) WI_NOEXCEPT { - return wil::AdaptFixedSizeToAllocatedResult( - result, - [&](_Out_writes_(valueLength) PWSTR value, std::size_t valueLength, - _Out_ std::size_t* valueLengthNeededWithNul) -> HRESULT { - *valueLengthNeededWithNul = ::GetProcessImageFileNameW(hProcess, value, static_cast(valueLength)); - RETURN_LAST_ERROR_IF(*valueLengthNeededWithNul == 0); - if (*valueLengthNeededWithNul < valueLength) { - (*valueLengthNeededWithNul)++; // it fit, account for the null - } - return S_OK; - }); +HRESULT GetProcessImageFileNameW(HANDLE hProcess, + string_type& result) WI_NOEXCEPT { + return wil::AdaptFixedSizeToAllocatedResult( + result, + [&](_Out_writes_(valueLength) PWSTR value, std::size_t valueLength, + _Out_ std::size_t* valueLengthNeededWithNul) -> HRESULT { + *valueLengthNeededWithNul = ::GetProcessImageFileNameW( + hProcess, value, static_cast(valueLength)); + RETURN_LAST_ERROR_IF(*valueLengthNeededWithNul == 0); + if (*valueLengthNeededWithNul < valueLength) { + (*valueLengthNeededWithNul)++; // it fit, account for the null + } + return S_OK; + }); } -} // namespace wil_extra +} // namespace wil_extra