diff --git a/.github/workflows/msvc_x86.yml b/.github/workflows/msvc_x86.yml new file mode 100644 index 0000000..8d2cebf --- /dev/null +++ b/.github/workflows/msvc_x86.yml @@ -0,0 +1,57 @@ +name: Build + +on: + pull_request: + push: + release: + types: published + +jobs: + build: + runs-on: windows-2019 + strategy: + matrix: + platform: [Win32] + buildtype: [Release] + + steps: + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.0.2 + - uses: actions/checkout@v2 + with: + submodules: 'true' + - name: Configure build + run: | + ./premake5 vs2019 + - name: Build + run: | + msbuild -m build/MaxPayne3.FusionFix.sln /property:Configuration=${{matrix.buildtype}} /property:Platform=${{matrix.platform}} + - name: Move binaries to data + run: | + cp "./bin/MaxPayne3.FusionFix.asi" "./data/plugins/MaxPayne3.FusionFix.asi" + 7z a MaxPayne3.FusionFix.zip ./data/* + - name: Upload artifact to actions + uses: actions/upload-artifact@v2 + with: + name: MaxPayne3.FusionFix.zip + path: ./data/* + - name: Create Release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: v1.${{ github.run_number }} + release_name: MaxPayne3.FusionFix v1.${{ github.run_number }} + draft: false + prerelease: false + - name: Upload Release Asset + id: upload-release-asset + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./MaxPayne3.FusionFix.zip + asset_name: MaxPayne3.FusionFix.zip + asset_content_type: application/zip diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6ef9495 --- /dev/null +++ b/.gitignore @@ -0,0 +1,331 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Bb]uild/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..0fdafb7 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,9 @@ +[submodule "external/injector"] + path = external/injector + url = https://github.com/thelink2012/injector +[submodule "external/hooking"] + path = external/hooking + url = https://github.com/ThirteenAG/Hooking.Patterns +[submodule "external/inireader"] + path = external/inireader + url = https://github.com/ThirteenAG/IniReader diff --git a/data/plugins/MaxPayne3.FusionFix.ini b/data/plugins/MaxPayne3.FusionFix.ini new file mode 100644 index 0000000..5c7fcbd --- /dev/null +++ b/data/plugins/MaxPayne3.FusionFix.ini @@ -0,0 +1,3 @@ +[MAIN] +HideSkipButton = 1 +OutlinesSizeMultiplier = 1.0f diff --git a/external/hooking b/external/hooking new file mode 160000 index 0000000..542b8db --- /dev/null +++ b/external/hooking @@ -0,0 +1 @@ +Subproject commit 542b8dbcd9f7b55811da256deea74902f7aa9067 diff --git a/external/inireader b/external/inireader new file mode 160000 index 0000000..85c2845 --- /dev/null +++ b/external/inireader @@ -0,0 +1 @@ +Subproject commit 85c2845b9dda0fa1f36612f8476d432dab1730d7 diff --git a/external/injector b/external/injector new file mode 160000 index 0000000..07e6a54 --- /dev/null +++ b/external/injector @@ -0,0 +1 @@ +Subproject commit 07e6a5430885146575b075c689c26ce2bac1951a diff --git a/license b/license new file mode 100644 index 0000000..0e0eb99 --- /dev/null +++ b/license @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Sergey P. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/premake5.bat b/premake5.bat new file mode 100644 index 0000000..18298f5 --- /dev/null +++ b/premake5.bat @@ -0,0 +1 @@ +premake5 vs2019 \ No newline at end of file diff --git a/premake5.exe b/premake5.exe new file mode 100644 index 0000000..9048d51 Binary files /dev/null and b/premake5.exe differ diff --git a/premake5.lua b/premake5.lua new file mode 100644 index 0000000..787278d --- /dev/null +++ b/premake5.lua @@ -0,0 +1,66 @@ +workspace "MaxPayne3.FusionFix" + configurations { "Release", "Debug" } + architecture "x86" + location "build" + buildoptions {"-std:c++latest"} + kind "SharedLib" + language "C++" + targetdir "bin/%{cfg.buildcfg}" + targetextension ".asi" + + defines { "rsc_CompanyName=\"MaxPayne3.FusionFix\"" } + defines { "rsc_LegalCopyright=\"MaxPayne3.FusionFix\""} + defines { "rsc_FileVersion=\"1.0.0.0\"", "rsc_ProductVersion=\"1.0.0.0\"" } + defines { "rsc_InternalName=\"%{prj.name}\"", "rsc_ProductName=\"%{prj.name}\"", "rsc_OriginalFilename=\"%{prj.name}.dll\"" } + defines { "rsc_FileDescription=\"MaxPayne3.FusionFix\"" } + defines { "rsc_UpdateUrl=\"https://github.com/ThirteenAG/MaxPayne3.FusionFix\"" } + + includedirs { "source" } + files { "source/dllmain.cpp" } + files { "source/resources/Versioninfo.rc" } + + includedirs { "external/hooking" } + includedirs { "external/injector/include" } + includedirs { "external/inireader" } + files { "external/hooking/Hooking.Patterns.h", "external/hooking/Hooking.Patterns.cpp" } + + characterset ("Unicode") + + pbcommands = { + "setlocal EnableDelayedExpansion", + --"set \"path=" .. (gamepath) .. "\"", + "set file=$(TargetPath)", + "FOR %%i IN (\"%file%\") DO (", + "set filename=%%~ni", + "set fileextension=%%~xi", + "set target=!path!!filename!!fileextension!", + "if exist \"!target!\" copy /y \"!file!\" \"!target!\"", + ")" } + + function setpaths (gamepath, exepath, scriptspath) + scriptspath = scriptspath or "scripts/" + if (gamepath) then + cmdcopy = { "set \"path=" .. gamepath .. scriptspath .. "\"" } + table.insert(cmdcopy, pbcommands) + postbuildcommands (cmdcopy) + debugdir (gamepath) + if (exepath) then + debugcommand (gamepath .. exepath) + dir, file = exepath:match'(.*/)(.*)' + debugdir (gamepath .. (dir or "")) + end + end + targetdir ("bin") + end + + filter "configurations:Debug" + defines { "DEBUG" } + symbols "On" + + filter "configurations:Release" + defines { "NDEBUG" } + optimize "On" + staticruntime "On" + +project "MaxPayne3.FusionFix" + setpaths("E:/Games/Steam/steamapps/common/Max Payne 3/Max Payne 3/", "MaxPayne3.exe", "plugins/") \ No newline at end of file diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..492448e --- /dev/null +++ b/readme.md @@ -0,0 +1,26 @@ +[![Actions Status: Release](https://github.com/ThirteenAG/MaxPayne3.FusionFix/actions/workflows/msvc_x86.yml/badge.svg)](https://github.com/ThirteenAG/MaxPayne3.FusionFix/actions) [![Discord](https://img.shields.io/badge/chat-on%20discord-7289da.svg?logo=discord)](https://discord.gg/RaZXpKExNj) + +

+ +

+ +# MaxPayne3.FusionFix + +This is a small project intended to add ability to hide ![skip](https://i.imgur.com/vwELI93.png) button in Max Payne 3. +Additionally, added an option to increase the size of subtitle text outlines. + +## Installation: + +### **Download**: [MaxPayne3.FusionFix.zip](https://github.com/ThirteenAG/MaxPayne3.FusionFix/releases/latest/download/MaxPayne3.FusionFix.zip) + +This requires [ASI Loader](https://github.com/ThirteenAG/Ultimate-ASI-Loader/releases/latest/download/Ultimate-ASI-Loader.zip). + +Unpack the content of archives to your **Max Payne 3** directory. + +## Screenshots: + +Before: +![](https://i.imgur.com/IOqRXKR.jpg) + +After: +![](https://i.imgur.com/28KZ32b.jpg) diff --git a/source/ModuleList.hpp b/source/ModuleList.hpp new file mode 100644 index 0000000..f8cc6b1 --- /dev/null +++ b/source/ModuleList.hpp @@ -0,0 +1,185 @@ +#pragma once + +#include +#include +#include +#include + +// Stores a list of loaded modules with their names, WITHOUT extension +class ModuleList +{ +public: + enum class SearchLocation + { + All, + LocalOnly, + SystemOnly, + }; + + // Initializes module list + // Needs to be called before any calls to Get or GetAll + void Enumerate(SearchLocation location = SearchLocation::All) + { + constexpr size_t INITIAL_SIZE = sizeof(HMODULE) * 256; + HMODULE* modules = static_cast(malloc(INITIAL_SIZE)); + if (modules != nullptr) + { + typedef BOOL(WINAPI * Func)(HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded); + + HMODULE hLib = LoadLibrary(TEXT("kernel32")); + assert(hLib != nullptr); // If this fails then everything is probably broken anyway + + Func pEnumProcessModules = reinterpret_cast(GetProcAddress(hLib, "K32EnumProcessModules")); + if (pEnumProcessModules == nullptr) + { + // Try psapi + FreeLibrary(hLib); + hLib = LoadLibrary(TEXT("psapi")); + if (hLib != nullptr) + { + pEnumProcessModules = reinterpret_cast(GetProcAddress(hLib, "EnumProcessModules")); + } + } + + if (pEnumProcessModules != nullptr) + { + const HANDLE currentProcess = GetCurrentProcess(); + DWORD cbNeeded = 0; + if (pEnumProcessModules(currentProcess, modules, INITIAL_SIZE, &cbNeeded) != 0) + { + if (cbNeeded > INITIAL_SIZE) + { + HMODULE* newModules = static_cast(realloc(modules, cbNeeded)); + if (newModules != nullptr) + { + modules = newModules; + + if (pEnumProcessModules(currentProcess, modules, cbNeeded, &cbNeeded) != 0) + { + EnumerateInternal(modules, location, cbNeeded / sizeof(HMODULE)); + } + } + } + else + { + EnumerateInternal(modules, location, cbNeeded / sizeof(HMODULE)); + } + } + } + + if (hLib != nullptr) + { + FreeLibrary(hLib); + } + + free(modules); + } + } + + // Recreates module list + void ReEnumerate(SearchLocation location = SearchLocation::All) + { + Clear(); + Enumerate(location); + } + + // Clears module list + void Clear() + { + m_moduleList.clear(); + } + + // Gets handle of a loaded module with given name, NULL otherwise + HMODULE Get(const wchar_t* moduleName) const + { + // If vector is empty then we're trying to call it without calling Enumerate first + assert(m_moduleList.size() != 0); + + auto it = std::find_if(m_moduleList.begin(), m_moduleList.end(), [&](const auto& e) { + return _wcsicmp(moduleName, std::get<1>(e).c_str()) == 0; + }); + return it != m_moduleList.end() ? std::get<0>(*it) : nullptr; + } + + // Gets handles to all loaded modules with given name + std::vector GetAll(const wchar_t* moduleName) const + { + // If vector is empty then we're trying to call it without calling Enumerate first + assert(m_moduleList.size() != 0); + + std::vector results; + for (auto& e : m_moduleList) + { + if (_wcsicmp(moduleName, std::get<1>(e).c_str()) == 0) + { + results.push_back(std::get<0>(e)); + } + } + + return results; + } + +private: + void EnumerateInternal(HMODULE* modules, SearchLocation location, size_t numModules) + { + auto GetModuleFileNameW = [](HMODULE hModule) -> std::wstring + { + static constexpr auto INITIAL_BUFFER_SIZE = MAX_PATH; + static constexpr auto MAX_ITERATIONS = 7; + std::wstring ret; + auto bufferSize = INITIAL_BUFFER_SIZE; + for (size_t iterations = 0; iterations < MAX_ITERATIONS; ++iterations) + { + ret.resize(bufferSize); + auto charsReturned = ::GetModuleFileNameW(hModule, &ret[0], bufferSize); + if (charsReturned < ret.length()) + { + ret.resize(charsReturned); + return ret; + } + else + { + bufferSize *= 2; + } + } + return L""; + }; + + const auto exeModulePath = GetModuleFileNameW(NULL).substr(0, GetModuleFileNameW(NULL).find_last_of(L"/\\")); + + m_moduleList.reserve(numModules); + for (size_t i = 0; i < numModules; i++) + { + // Obtain module name, with resizing if necessary + auto moduleName = GetModuleFileNameW(*modules); + + if (!moduleName.empty()) + { + auto starts_with = [](const std::wstring &big_str, const std::wstring &small_str) -> bool + { + return big_str.compare(0, small_str.length(), small_str) == 0; + }; + + const wchar_t* nameBegin = wcsrchr(moduleName.c_str(), '\\') + 1; + const wchar_t* dotPos = wcsrchr(nameBegin, '.'); + bool isLocal = starts_with(std::wstring(moduleName), exeModulePath); + + if ((isLocal && location != SearchLocation::SystemOnly) || (!isLocal && location != SearchLocation::LocalOnly)) + { + if (dotPos != nullptr) + { + m_moduleList.emplace_back(*modules, std::wstring(nameBegin, dotPos), isLocal); + } + else + { + m_moduleList.emplace_back(*modules, nameBegin, isLocal); + } + } + } + + modules++; + } + } + +public: std::vector< std::tuple > m_moduleList; +}; \ No newline at end of file diff --git a/source/dllmain.cpp b/source/dllmain.cpp new file mode 100644 index 0000000..9e2d263 --- /dev/null +++ b/source/dllmain.cpp @@ -0,0 +1,67 @@ +#include + +float fOutlinesSizeMultiplier; +float* dword_1FCA9A8; +void __fastcall sub_010AFD30(float* _this, void* edx, float a2) +{ + a2 *= fOutlinesSizeMultiplier; + + if (a2 <= 0.0) + { + _this[8] = 0.0; + _this[13] = 0.0; + } + else + { + _this[8] = a2 / *dword_1FCA9A8; + _this[13] = a2 / *dword_1FCA9A8; + } +} + +void Init() +{ + CIniReader iniReader(""); + bool bHideSkipButton = iniReader.ReadInteger("MAIN", "HideSkipButton", 1) != 0; + fOutlinesSizeMultiplier = iniReader.ReadFloat("MAIN", "OutlinesSizeMultiplier", 0.0f); + + if (bHideSkipButton) + { + auto pattern = hook::pattern("8B C8 89 86 ? ? ? ? E8 ? ? ? ? D9 EE 8B 86 ? ? ? ? 8B 38 83 EC 08"); + injector::MakeNOP(pattern.count(22).get(0).get(8), 5, true); + injector::MakeNOP(pattern.count(22).get(3).get(8), 5, true); + } + + if (fOutlinesSizeMultiplier) + { + dword_1FCA9A8 = *hook::get_pattern("F3 0F 10 86 ? ? ? ? F3 0F 59 05 ? ? ? ? 51 8D 8C 24", 12); + + auto pattern = hook::pattern("E8 ? ? ? ? 68 ? ? ? ? 8D 94 24 ? ? ? ? 6A 02"); + injector::MakeCALL(pattern.get_first(0), sub_010AFD30, true); + + pattern = hook::pattern("D9 1C 24 E8 ? ? ? ? 68 ? ? ? ? 68"); + injector::MakeCALL(pattern.get_first(3), sub_010AFD30, true); + + pattern = hook::pattern("E8 ? ? ? ? 68 ? ? ? ? 8D 44 24 20 6A 03 50 88 1D ? ? ? ? C6 05 ? ? ? ? ? 88 1D ? ? ? ? E8 ? ? ? ? 8B 08"); + injector::MakeCALL(pattern.get_first(0), sub_010AFD30, true); + + pattern = hook::pattern("E8 ? ? ? ? F3 0F 10 44 24 ? 8D 4C 24 30 F3 0F 11 05 ? ? ? ? F3 0F 10 44 24 ? 51 B9 ? ? ? ? F3 0F 11 05 ? ? ? ? E8 ? ? ? ? 8A 5C 24 0F 80 FB FF 75 0C"); + injector::MakeCALL(pattern.get_first(0), sub_010AFD30, true); + } +} + +CEXP void InitializeASI() +{ + std::call_once(CallbackHandler::flag, []() + { + CallbackHandler::RegisterCallback(Init, hook::pattern("C6 44 24 ? ? F3 0F 11 44 24 ? F3 0F 11 44 24 ? 89 4C 24 54")); + }); +} + +BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) +{ + if (reason == DLL_PROCESS_ATTACH) + { + if (!IsUALPresent()) { InitializeASI(); } + } + return TRUE; +} \ No newline at end of file diff --git a/source/misc.h b/source/misc.h new file mode 100644 index 0000000..2a7f128 --- /dev/null +++ b/source/misc.h @@ -0,0 +1,215 @@ +#pragma once +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include +#include +#include +#include "IniReader.h" +#include "injector\injector.hpp" +#include "injector\calling.hpp" +#include "injector\hooking.hpp" +#include "injector\assembly.hpp" +#include "injector\utility.hpp" +#include "Hooking.Patterns.h" +#include "ModuleList.hpp" + +#ifndef CEXP +#define CEXP extern "C" __declspec(dllexport) +#endif + +void CreateThreadAutoClose(LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId) +{ + CloseHandle(CreateThread(lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId)); +} + +bool IsUALPresent() +{ + ModuleList dlls; + dlls.Enumerate(ModuleList::SearchLocation::LocalOnly); + for (auto& e : dlls.m_moduleList) + { + if (GetProcAddress(std::get(e), "DirectInput8Create") != NULL && GetProcAddress(std::get(e), "DirectSoundCreate8") != NULL && GetProcAddress(std::get(e), "InternetOpenA") != NULL) + return true; + } + return false; +} + +class CallbackHandler +{ +public: + static inline void RegisterCallback(std::function&& fn) + { + fn(); + } + + static inline void RegisterCallback(std::wstring_view module_name, std::function&& fn) + { + if (module_name.empty() || GetModuleHandleW(module_name.data()) != NULL) + { + fn(); + } + else + { + RegisterDllNotification(); + GetCallbackList().emplace(module_name, std::forward>(fn)); + } + } + + static inline void RegisterCallback(std::function&& fn, bool bPatternNotFound, ptrdiff_t offset = 0x1100, uint32_t * ptr = nullptr) + { + if (!bPatternNotFound) + { + fn(); + } + else + { + auto mh = GetModuleHandle(NULL); + IMAGE_NT_HEADERS* ntHeader = (IMAGE_NT_HEADERS*)((DWORD)mh + ((IMAGE_DOS_HEADER*)mh)->e_lfanew); + if (ptr == nullptr) + ptr = (uint32_t*)((DWORD)mh + ntHeader->OptionalHeader.BaseOfCode + ntHeader->OptionalHeader.SizeOfCode - offset); + std::thread([](std::function&& fn, uint32_t* ptr, uint32_t val) + { + while (*ptr == val) + std::this_thread::yield(); + + fn(); + }, fn, ptr, *ptr).detach(); + } + } + + static inline void RegisterCallback(std::function&& fn, hook::pattern pattern) + { + if (!pattern.empty()) + { + fn(); + } + else + { + auto* ptr = new ThreadParams{ fn, pattern }; + CreateThreadAutoClose(0, 0, (LPTHREAD_START_ROUTINE)& ThreadProc, (LPVOID)ptr, 0, NULL); + } + } + +private: + static inline void call(std::wstring_view module_name) + { + if (GetCallbackList().count(module_name.data())) + { + GetCallbackList().at(module_name.data())(); + GetCallbackList().erase(module_name.data()); + } + + //if (GetCallbackList().empty()) //win7 crash in splinter cell + // UnRegisterDllNotification(); + } + + static inline void invoke_all() + { + for (auto&& fn : GetCallbackList()) + fn.second(); + } + +private: + struct Comparator + { + bool operator() (const std::wstring& s1, const std::wstring& s2) const + { + std::wstring str1(s1.length(), ' '); + std::wstring str2(s2.length(), ' '); + std::transform(s1.begin(), s1.end(), str1.begin(), tolower); + std::transform(s2.begin(), s2.end(), str2.begin(), tolower); + return str1 < str2; + } + }; + + static std::map, Comparator>& GetCallbackList() + { + static std::map, Comparator> functions; + return functions; + } + + struct ThreadParams + { + std::function fn; + hook::pattern pattern; + }; + + typedef NTSTATUS(NTAPI* _LdrRegisterDllNotification) (ULONG, PVOID, PVOID, PVOID); + typedef NTSTATUS(NTAPI* _LdrUnregisterDllNotification) (PVOID); + + typedef struct _LDR_DLL_LOADED_NOTIFICATION_DATA + { + ULONG Flags; //Reserved. + PUNICODE_STRING FullDllName; //The full path name of the DLL module. + PUNICODE_STRING BaseDllName; //The base file name of the DLL module. + PVOID DllBase; //A pointer to the base address for the DLL in memory. + ULONG SizeOfImage; //The size of the DLL image, in bytes. + } LDR_DLL_LOADED_NOTIFICATION_DATA, LDR_DLL_UNLOADED_NOTIFICATION_DATA, * PLDR_DLL_LOADED_NOTIFICATION_DATA, * PLDR_DLL_UNLOADED_NOTIFICATION_DATA; + + typedef union _LDR_DLL_NOTIFICATION_DATA + { + LDR_DLL_LOADED_NOTIFICATION_DATA Loaded; + LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded; + } LDR_DLL_NOTIFICATION_DATA, * PLDR_DLL_NOTIFICATION_DATA; + +private: + static inline void CALLBACK LdrDllNotification(ULONG NotificationReason, PLDR_DLL_NOTIFICATION_DATA NotificationData, PVOID Context) + { + static constexpr auto LDR_DLL_NOTIFICATION_REASON_LOADED = 1; + if (NotificationReason == LDR_DLL_NOTIFICATION_REASON_LOADED) + { + call(NotificationData->Loaded.BaseDllName->Buffer); + } + } + + static inline void RegisterDllNotification() + { + LdrRegisterDllNotification = (_LdrRegisterDllNotification)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "LdrRegisterDllNotification"); + if (LdrRegisterDllNotification && !cookie) + LdrRegisterDllNotification(0, LdrDllNotification, 0, &cookie); + } + + static inline void UnRegisterDllNotification() + { + LdrUnregisterDllNotification = (_LdrUnregisterDllNotification)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "LdrUnregisterDllNotification"); + if (LdrUnregisterDllNotification && cookie) + LdrUnregisterDllNotification(cookie); + } + + static inline DWORD WINAPI ThreadProc(LPVOID ptr) + { + auto paramsPtr = static_cast(ptr); + auto params = *paramsPtr; + delete paramsPtr; + + HANDLE hTimer = NULL; + LARGE_INTEGER liDueTime; + liDueTime.QuadPart = -30 * 10000000LL; + hTimer = CreateWaitableTimer(NULL, TRUE, NULL); + SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, 0); + + while (params.pattern.clear().empty()) + { + Sleep(0); + + if (WaitForSingleObject(hTimer, 0) == WAIT_OBJECT_0) + { + CloseHandle(hTimer); + return 0; + } + }; + + params.fn(); + + return 0; + } +private: + static inline _LdrRegisterDllNotification LdrRegisterDllNotification; + static inline _LdrUnregisterDllNotification LdrUnregisterDllNotification; + static inline void* cookie; +public: + static inline std::once_flag flag; +}; \ No newline at end of file diff --git a/source/resources/VersionInfo.h b/source/resources/VersionInfo.h new file mode 100644 index 0000000..cc2b890 Binary files /dev/null and b/source/resources/VersionInfo.h differ diff --git a/source/resources/Versioninfo.rc b/source/resources/Versioninfo.rc new file mode 100644 index 0000000..fdc9b79 Binary files /dev/null and b/source/resources/Versioninfo.rc differ