sku-111 edition

This commit is contained in:
Solipsis23 2023-10-09 16:54:34 +01:00
parent 0e3352c444
commit 628db9203f
54 changed files with 37965 additions and 45677 deletions

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

View File

@ -1,31 +1,31 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16 # Visual Studio Version 16
VisualStudioVersion = 16.0.33130.400 VisualStudioVersion = 16.0.33130.400
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hook_lib", "hook_lib\hook_lib.vcxproj", "{D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hook_lib", "hook_lib\hook_lib.vcxproj", "{D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64 Debug|x64 = Debug|x64
Debug|x86 = Debug|x86 Debug|x86 = Debug|x86
Release|x64 = Release|x64 Release|x64 = Release|x64
Release|x86 = Release|x86 Release|x86 = Release|x86
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Debug|x64.ActiveCfg = Debug|x64 {D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Debug|x64.ActiveCfg = Debug|x64
{D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Debug|x64.Build.0 = Debug|x64 {D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Debug|x64.Build.0 = Debug|x64
{D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Debug|x86.ActiveCfg = Debug|Win32 {D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Debug|x86.ActiveCfg = Debug|Win32
{D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Debug|x86.Build.0 = Debug|Win32 {D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Debug|x86.Build.0 = Debug|Win32
{D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Release|x64.ActiveCfg = Release|x64 {D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Release|x64.ActiveCfg = Release|x64
{D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Release|x64.Build.0 = Release|x64 {D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Release|x64.Build.0 = Release|x64
{D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Release|x86.ActiveCfg = Release|Win32 {D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Release|x86.ActiveCfg = Release|Win32
{D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Release|x86.Build.0 = Release|Win32 {D84DCA02-7BEE-40E4-81D5-75EB0AA0A9D3}.Release|x86.Build.0 = Release|Win32
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {58937352-3EDA-4AEE-A7FD-C21D6955F38B} SolutionGuid = {58937352-3EDA-4AEE-A7FD-C21D6955F38B}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

File diff suppressed because it is too large Load Diff

View File

@ -1,117 +1,117 @@
#pragma once #pragma once
#include <Windows.h> #include <Windows.h>
#include <winternl.h> #include <winternl.h>
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
#include <string> #include <string>
#include <dxgi1_5.h> #include <dxgi1_5.h>
#include <d3d12.h> #include <d3d12.h>
#include <intrin.h> #include <intrin.h>
#pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "user32.lib") #pragma comment(lib, "user32.lib")
#include "common/utils/hook.hpp" #include "common/utils/hook.hpp"
#include "common/utils/hardware_breakpoint.hpp" #include "common/utils/hardware_breakpoint.hpp"
#include "functions.hpp" #include "functions.hpp"
#include "structs.h" #include "structs.h"
#include "assets.h" #include "assets.h"
#include "ini.h" #include "ini.h"
#include "json.hpp" #include "json.hpp"
#include "splashscreen.hpp" #include "splashscreen.hpp"
extern void* exception_handler; extern void* exception_handler;
#define base g_Addrs.ModuleBase #define base g_Addrs.ModuleBase
#pragma warning(disable:4996) #pragma warning(disable:4996)
#pragma comment(lib, "Gdi32.lib") #pragma comment(lib, "Gdi32.lib")
#define INRANGE(x, a, b) (x >= a && x <= b) #define INRANGE(x, a, b) (x >= a && x <= b)
#define GET_BITS( x ) (INRANGE((x&(~0x20)),'A','F') ? ((x&(~0x20)) - 'A' + 0xa) : (INRANGE(x,'0','9') ? x - '0' : 0)) #define GET_BITS( x ) (INRANGE((x&(~0x20)),'A','F') ? ((x&(~0x20)) - 'A' + 0xa) : (INRANGE(x,'0','9') ? x - '0' : 0))
#define GET_BYTE( x ) (GET_BITS(x[0]) << 4 | GET_BITS(x[1])) #define GET_BYTE( x ) (GET_BITS(x[0]) << 4 | GET_BITS(x[1]))
struct menu_variables { struct menu_variables {
bool bInitiateMenu; bool bInitiateMenu;
bool bMenuOpen; bool bMenuOpen;
}; };
extern menu_variables vars; extern menu_variables vars;
void nlog(const char* str, ...); void nlog(const char* str, ...);
uintptr_t find_pattern(const char* module_name, const char* pattern); uintptr_t find_pattern(const char* module_name, const char* pattern);
uintptr_t find_pattern(uintptr_t start, const char* module_name, const char* pattern); uintptr_t find_pattern(uintptr_t start, const char* module_name, const char* pattern);
size_t operator"" _b(size_t val); size_t operator"" _b(size_t val);
size_t reverse_b(size_t val); size_t reverse_b(size_t val);
size_t reverse_b(const void* val); size_t reverse_b(const void* val);
size_t operator"" _g(size_t val); size_t operator"" _g(size_t val);
size_t reverse_g(size_t val); size_t reverse_g(size_t val);
size_t reverse_g(const void* val); size_t reverse_g(const void* val);
void log(const char* str); void log(const char* str);
void log(const char* file, const char* str); void log(const char* file, const char* str);
struct DvarPair struct DvarPair
{ {
const char* m_key; const char* m_key;
const char* m_value; const char* m_value;
}; };
inline bool IsBadPointer(uintptr_t* ptr) inline bool IsBadPointer(uintptr_t* ptr)
{ {
__try __try
{ {
volatile auto result = *ptr; volatile auto result = *ptr;
} }
__except (EXCEPTION_EXECUTE_HANDLER) __except (EXCEPTION_EXECUTE_HANDLER)
{ {
return true; return true;
} }
return false; return false;
} }
struct DvarMap struct DvarMap
{ {
DvarPair m_pairs[10000]; DvarPair m_pairs[10000];
}; };
extern int g_dvarmapcount; extern int g_dvarmapcount;
extern DvarPair g_dvarmap[6821]; extern DvarPair g_dvarmap[6821];
struct shaderOverride_t struct shaderOverride_t
{ {
float scrollRateX; float scrollRateX;
float scrollRateY; float scrollRateY;
float scrollRateR; float scrollRateR;
float tilingX; float tilingX;
float tilingY; float tilingY;
float rotation; float rotation;
float alpha; float alpha;
float emissive; float emissive;
float atlasTime; float atlasTime;
}; };
struct GfxSceneHudOutlineInfo struct GfxSceneHudOutlineInfo
{ {
unsigned int color; unsigned int color;
float scopeStencil; float scopeStencil;
bool drawOccludedPixels; bool drawOccludedPixels;
bool drawNonOccludedPixels; bool drawNonOccludedPixels;
bool fill; bool fill;
bool useAlternateColor; bool useAlternateColor;
bool forSpectator; bool forSpectator;
bool specialActive; bool specialActive;
unsigned __int8 renderMode; unsigned __int8 renderMode;
unsigned __int8 lineWidth; unsigned __int8 lineWidth;
unsigned __int8 temperatureSet; unsigned __int8 temperatureSet;
unsigned int mapEntLookup; unsigned int mapEntLookup;
float temperatureBase; float temperatureBase;
float temperatureScale; float temperatureScale;
float characterEVOffset; float characterEVOffset;
}; };

Binary file not shown.

View File

@ -1,6 +1,6 @@
#include "assets.h" #include "assets.h"
void test() { void test() {
sizeof(VehicleDef); sizeof(VehicleDef);
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,85 +1,85 @@
#include "minidump.hpp" #include "minidump.hpp"
#include <DbgHelp.h> #include <DbgHelp.h>
#pragma comment(lib, "dbghelp.lib") #pragma comment(lib, "dbghelp.lib")
namespace exception namespace exception
{ {
namespace namespace
{ {
constexpr MINIDUMP_TYPE get_minidump_type() constexpr MINIDUMP_TYPE get_minidump_type()
{ {
constexpr auto type = MiniDumpIgnoreInaccessibleMemory // constexpr auto type = MiniDumpIgnoreInaccessibleMemory //
| MiniDumpWithHandleData // | MiniDumpWithHandleData //
| MiniDumpScanMemory // | MiniDumpScanMemory //
| MiniDumpWithProcessThreadData // | MiniDumpWithProcessThreadData //
| MiniDumpWithFullMemoryInfo // | MiniDumpWithFullMemoryInfo //
| MiniDumpWithThreadInfo // | MiniDumpWithThreadInfo //
| MiniDumpWithUnloadedModules; | MiniDumpWithUnloadedModules;
return static_cast<MINIDUMP_TYPE>(type); return static_cast<MINIDUMP_TYPE>(type);
} }
std::string get_temp_filename() std::string get_temp_filename()
{ {
char filename[MAX_PATH] = {0}; char filename[MAX_PATH] = {0};
char pathname[MAX_PATH] = {0}; char pathname[MAX_PATH] = {0};
GetTempPathA(sizeof(pathname), pathname); GetTempPathA(sizeof(pathname), pathname);
GetTempFileNameA(pathname, "boiii-", 0, filename); GetTempFileNameA(pathname, "boiii-", 0, filename);
return filename; return filename;
} }
HANDLE write_dump_to_temp_file(const LPEXCEPTION_POINTERS exceptioninfo) HANDLE write_dump_to_temp_file(const LPEXCEPTION_POINTERS exceptioninfo)
{ {
MINIDUMP_EXCEPTION_INFORMATION minidump_exception_info = {GetCurrentThreadId(), exceptioninfo, FALSE}; MINIDUMP_EXCEPTION_INFORMATION minidump_exception_info = {GetCurrentThreadId(), exceptioninfo, FALSE};
auto* const file_handle = CreateFileA(get_temp_filename().data(), GENERIC_WRITE | GENERIC_READ, auto* const file_handle = CreateFileA(get_temp_filename().data(), GENERIC_WRITE | GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS,
FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
nullptr); nullptr);
if (!MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file_handle, get_minidump_type(), if (!MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file_handle, get_minidump_type(),
&minidump_exception_info, &minidump_exception_info,
nullptr, nullptr,
nullptr)) nullptr))
{ {
MessageBoxA(nullptr, "There was an error creating the minidump! Hit OK to close the program.", MessageBoxA(nullptr, "There was an error creating the minidump! Hit OK to close the program.",
"Minidump Error", MB_OK | MB_ICONERROR); "Minidump Error", MB_OK | MB_ICONERROR);
TerminateProcess(GetCurrentProcess(), 123); TerminateProcess(GetCurrentProcess(), 123);
} }
return file_handle; return file_handle;
} }
std::string read_file(const HANDLE file_handle) std::string read_file(const HANDLE file_handle)
{ {
FlushFileBuffers(file_handle); FlushFileBuffers(file_handle);
SetFilePointer(file_handle, 0, nullptr, FILE_BEGIN); SetFilePointer(file_handle, 0, nullptr, FILE_BEGIN);
std::string buffer{}; std::string buffer{};
DWORD bytes_read = 0; DWORD bytes_read = 0;
char temp_bytes[0x2000]; char temp_bytes[0x2000];
do do
{ {
if (!ReadFile(file_handle, temp_bytes, sizeof(temp_bytes), &bytes_read, nullptr)) if (!ReadFile(file_handle, temp_bytes, sizeof(temp_bytes), &bytes_read, nullptr))
{ {
return {}; return {};
} }
buffer.append(temp_bytes, bytes_read); buffer.append(temp_bytes, bytes_read);
} }
while (bytes_read == sizeof(temp_bytes)); while (bytes_read == sizeof(temp_bytes));
return buffer; return buffer;
} }
} }
std::string create_minidump(const LPEXCEPTION_POINTERS exceptioninfo) std::string create_minidump(const LPEXCEPTION_POINTERS exceptioninfo)
{ {
const utils::nt::handle file_handle = write_dump_to_temp_file(exceptioninfo); const utils::nt::handle file_handle = write_dump_to_temp_file(exceptioninfo);
return read_file(file_handle); return read_file(file_handle);
} }
} }

View File

@ -1,8 +1,8 @@
#pragma once #pragma once
#include "../utils/nt.hpp" #include "../utils/nt.hpp"
namespace exception namespace exception
{ {
std::string create_minidump(LPEXCEPTION_POINTERS exceptioninfo); std::string create_minidump(LPEXCEPTION_POINTERS exceptioninfo);
} }

View File

@ -1,185 +1,185 @@
/* /*
* MinHook - The Minimalistic API Hooking Library for x64/x86 * MinHook - The Minimalistic API Hooking Library for x64/x86
* Copyright (C) 2009-2017 Tsuda Kageyu. * Copyright (C) 2009-2017 Tsuda Kageyu.
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* *
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
#pragma once #pragma once
#if !(defined _M_IX86) && !(defined _M_X64) && !(defined __i386__) && !(defined __x86_64__) #if !(defined _M_IX86) && !(defined _M_X64) && !(defined __i386__) && !(defined __x86_64__)
#error MinHook supports only x86 and x64 systems. #error MinHook supports only x86 and x64 systems.
#endif #endif
#include <windows.h> #include <windows.h>
// MinHook Error Codes. // MinHook Error Codes.
typedef enum MH_STATUS typedef enum MH_STATUS
{ {
// Unknown error. Should not be returned. // Unknown error. Should not be returned.
MH_UNKNOWN = -1, MH_UNKNOWN = -1,
// Successful. // Successful.
MH_OK = 0, MH_OK = 0,
// MinHook is already initialized. // MinHook is already initialized.
MH_ERROR_ALREADY_INITIALIZED, MH_ERROR_ALREADY_INITIALIZED,
// MinHook is not initialized yet, or already uninitialized. // MinHook is not initialized yet, or already uninitialized.
MH_ERROR_NOT_INITIALIZED, MH_ERROR_NOT_INITIALIZED,
// The hook for the specified target function is already created. // The hook for the specified target function is already created.
MH_ERROR_ALREADY_CREATED, MH_ERROR_ALREADY_CREATED,
// The hook for the specified target function is not created yet. // The hook for the specified target function is not created yet.
MH_ERROR_NOT_CREATED, MH_ERROR_NOT_CREATED,
// The hook for the specified target function is already enabled. // The hook for the specified target function is already enabled.
MH_ERROR_ENABLED, MH_ERROR_ENABLED,
// The hook for the specified target function is not enabled yet, or already // The hook for the specified target function is not enabled yet, or already
// disabled. // disabled.
MH_ERROR_DISABLED, MH_ERROR_DISABLED,
// The specified pointer is invalid. It points the address of non-allocated // The specified pointer is invalid. It points the address of non-allocated
// and/or non-executable region. // and/or non-executable region.
MH_ERROR_NOT_EXECUTABLE, MH_ERROR_NOT_EXECUTABLE,
// The specified target function cannot be hooked. // The specified target function cannot be hooked.
MH_ERROR_UNSUPPORTED_FUNCTION, MH_ERROR_UNSUPPORTED_FUNCTION,
// Failed to allocate memory. // Failed to allocate memory.
MH_ERROR_MEMORY_ALLOC, MH_ERROR_MEMORY_ALLOC,
// Failed to change the memory protection. // Failed to change the memory protection.
MH_ERROR_MEMORY_PROTECT, MH_ERROR_MEMORY_PROTECT,
// The specified module is not loaded. // The specified module is not loaded.
MH_ERROR_MODULE_NOT_FOUND, MH_ERROR_MODULE_NOT_FOUND,
// The specified function is not found. // The specified function is not found.
MH_ERROR_FUNCTION_NOT_FOUND MH_ERROR_FUNCTION_NOT_FOUND
} }
MH_STATUS; MH_STATUS;
// Can be passed as a parameter to MH_EnableHook, MH_DisableHook, // Can be passed as a parameter to MH_EnableHook, MH_DisableHook,
// MH_QueueEnableHook or MH_QueueDisableHook. // MH_QueueEnableHook or MH_QueueDisableHook.
#define MH_ALL_HOOKS NULL #define MH_ALL_HOOKS NULL
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
// Initialize the MinHook library. You must call this function EXACTLY ONCE // Initialize the MinHook library. You must call this function EXACTLY ONCE
// at the beginning of your program. // at the beginning of your program.
MH_STATUS WINAPI MH_Initialize(VOID); MH_STATUS WINAPI MH_Initialize(VOID);
// Uninitialize the MinHook library. You must call this function EXACTLY // Uninitialize the MinHook library. You must call this function EXACTLY
// ONCE at the end of your program. // ONCE at the end of your program.
MH_STATUS WINAPI MH_Uninitialize(VOID); MH_STATUS WINAPI MH_Uninitialize(VOID);
// Creates a hook for the specified target function, in disabled state. // Creates a hook for the specified target function, in disabled state.
// Parameters: // Parameters:
// pTarget [in] A pointer to the target function, which will be // pTarget [in] A pointer to the target function, which will be
// overridden by the detour function. // overridden by the detour function.
// pDetour [in] A pointer to the detour function, which will override // pDetour [in] A pointer to the detour function, which will override
// the target function. // the target function.
// ppOriginal [out] A pointer to the trampoline function, which will be // ppOriginal [out] A pointer to the trampoline function, which will be
// used to call the original target function. // used to call the original target function.
// This parameter can be NULL. // This parameter can be NULL.
MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal); MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal);
// Creates a hook for the specified API function, in disabled state. // Creates a hook for the specified API function, in disabled state.
// Parameters: // Parameters:
// pszModule [in] A pointer to the loaded module name which contains the // pszModule [in] A pointer to the loaded module name which contains the
// target function. // target function.
// pszProcName [in] A pointer to the target function name, which will be // pszProcName [in] A pointer to the target function name, which will be
// overridden by the detour function. // overridden by the detour function.
// pDetour [in] A pointer to the detour function, which will override // pDetour [in] A pointer to the detour function, which will override
// the target function. // the target function.
// ppOriginal [out] A pointer to the trampoline function, which will be // ppOriginal [out] A pointer to the trampoline function, which will be
// used to call the original target function. // used to call the original target function.
// This parameter can be NULL. // This parameter can be NULL.
MH_STATUS WINAPI MH_CreateHookApi( MH_STATUS WINAPI MH_CreateHookApi(
LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal); LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal);
// Creates a hook for the specified API function, in disabled state. // Creates a hook for the specified API function, in disabled state.
// Parameters: // Parameters:
// pszModule [in] A pointer to the loaded module name which contains the // pszModule [in] A pointer to the loaded module name which contains the
// target function. // target function.
// pszProcName [in] A pointer to the target function name, which will be // pszProcName [in] A pointer to the target function name, which will be
// overridden by the detour function. // overridden by the detour function.
// pDetour [in] A pointer to the detour function, which will override // pDetour [in] A pointer to the detour function, which will override
// the target function. // the target function.
// ppOriginal [out] A pointer to the trampoline function, which will be // ppOriginal [out] A pointer to the trampoline function, which will be
// used to call the original target function. // used to call the original target function.
// This parameter can be NULL. // This parameter can be NULL.
// ppTarget [out] A pointer to the target function, which will be used // ppTarget [out] A pointer to the target function, which will be used
// with other functions. // with other functions.
// This parameter can be NULL. // This parameter can be NULL.
MH_STATUS WINAPI MH_CreateHookApiEx( MH_STATUS WINAPI MH_CreateHookApiEx(
LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget); LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget);
// Removes an already created hook. // Removes an already created hook.
// Parameters: // Parameters:
// pTarget [in] A pointer to the target function. // pTarget [in] A pointer to the target function.
MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget); MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget);
// Enables an already created hook. // Enables an already created hook.
// Parameters: // Parameters:
// pTarget [in] A pointer to the target function. // pTarget [in] A pointer to the target function.
// If this parameter is MH_ALL_HOOKS, all created hooks are // If this parameter is MH_ALL_HOOKS, all created hooks are
// enabled in one go. // enabled in one go.
MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget); MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget);
// Disables an already created hook. // Disables an already created hook.
// Parameters: // Parameters:
// pTarget [in] A pointer to the target function. // pTarget [in] A pointer to the target function.
// If this parameter is MH_ALL_HOOKS, all created hooks are // If this parameter is MH_ALL_HOOKS, all created hooks are
// disabled in one go. // disabled in one go.
MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget); MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget);
// Queues to enable an already created hook. // Queues to enable an already created hook.
// Parameters: // Parameters:
// pTarget [in] A pointer to the target function. // pTarget [in] A pointer to the target function.
// If this parameter is MH_ALL_HOOKS, all created hooks are // If this parameter is MH_ALL_HOOKS, all created hooks are
// queued to be enabled. // queued to be enabled.
MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget); MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget);
// Queues to disable an already created hook. // Queues to disable an already created hook.
// Parameters: // Parameters:
// pTarget [in] A pointer to the target function. // pTarget [in] A pointer to the target function.
// If this parameter is MH_ALL_HOOKS, all created hooks are // If this parameter is MH_ALL_HOOKS, all created hooks are
// queued to be disabled. // queued to be disabled.
MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget); MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget);
// Applies all queued changes in one go. // Applies all queued changes in one go.
MH_STATUS WINAPI MH_ApplyQueued(VOID); MH_STATUS WINAPI MH_ApplyQueued(VOID);
// Translates the MH_STATUS to its name as a string. // Translates the MH_STATUS to its name as a string.
const char * WINAPI MH_StatusToString(MH_STATUS status); const char * WINAPI MH_StatusToString(MH_STATUS status);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@ -1,75 +1,75 @@
#include "binary_resource.hpp" #include "binary_resource.hpp"
#include <utility> #include <utility>
#include "nt.hpp" #include "nt.hpp"
#include "io.hpp" #include "io.hpp"
namespace utils namespace utils
{ {
namespace namespace
{ {
std::string get_temp_folder() std::string get_temp_folder()
{ {
char path[MAX_PATH] = {0}; char path[MAX_PATH] = {0};
if (!GetTempPathA(sizeof(path), path)) if (!GetTempPathA(sizeof(path), path))
{ {
throw std::runtime_error("Unable to get temp path"); throw std::runtime_error("Unable to get temp path");
} }
return path; return path;
} }
std::string write_existing_temp_file(const std::string& file, const std::string& data, std::string write_existing_temp_file(const std::string& file, const std::string& data,
const bool fatal_if_overwrite_fails) const bool fatal_if_overwrite_fails)
{ {
const auto temp = get_temp_folder(); const auto temp = get_temp_folder();
auto file_path = temp + file; auto file_path = temp + file;
std::string current_data; std::string current_data;
if (!io::read_file(file_path, &current_data)) if (!io::read_file(file_path, &current_data))
{ {
if (!io::write_file(file_path, data)) if (!io::write_file(file_path, data))
{ {
throw std::runtime_error("Failed to write file: " + file_path); throw std::runtime_error("Failed to write file: " + file_path);
} }
return file_path; return file_path;
} }
if (current_data == data || io::write_file(file_path, data) || !fatal_if_overwrite_fails) if (current_data == data || io::write_file(file_path, data) || !fatal_if_overwrite_fails)
{ {
return file_path; return file_path;
} }
throw std::runtime_error( throw std::runtime_error(
"Temporary file was already written, but differs. It can't be overwritten as it's still in use: " + "Temporary file was already written, but differs. It can't be overwritten as it's still in use: " +
file_path); file_path);
} }
} }
binary_resource::binary_resource(const int id, std::string file) binary_resource::binary_resource(const int id, std::string file)
: filename_(std::move(file)) : filename_(std::move(file))
{ {
this->resource_ = nt::load_resource(id); this->resource_ = nt::load_resource(id);
if (this->resource_.empty()) if (this->resource_.empty())
{ {
throw std::runtime_error("Unable to load resource: " + std::to_string(id)); throw std::runtime_error("Unable to load resource: " + std::to_string(id));
} }
} }
std::string binary_resource::get_extracted_file(const bool fatal_if_overwrite_fails) std::string binary_resource::get_extracted_file(const bool fatal_if_overwrite_fails)
{ {
if (this->path_.empty()) if (this->path_.empty())
{ {
this->path_ = write_existing_temp_file(this->filename_, this->resource_, fatal_if_overwrite_fails); this->path_ = write_existing_temp_file(this->filename_, this->resource_, fatal_if_overwrite_fails);
} }
return this->path_; return this->path_;
} }
const std::string& binary_resource::get_data() const const std::string& binary_resource::get_data() const
{ {
return this->resource_; return this->resource_;
} }
} }

View File

@ -1,20 +1,20 @@
#pragma once #pragma once
#include <string> #include <string>
namespace utils namespace utils
{ {
class binary_resource class binary_resource
{ {
public: public:
binary_resource(int id, std::string file); binary_resource(int id, std::string file);
std::string get_extracted_file(bool fatal_if_overwrite_fails = false); std::string get_extracted_file(bool fatal_if_overwrite_fails = false);
const std::string& get_data() const; const std::string& get_data() const;
private: private:
std::string resource_; std::string resource_;
std::string filename_; std::string filename_;
std::string path_; std::string path_;
}; };
} }

View File

@ -1,46 +1,46 @@
#pragma once #pragma once
#include <mutex> #include <mutex>
namespace utils::concurrency namespace utils::concurrency
{ {
template <typename T, typename MutexType = std::mutex> template <typename T, typename MutexType = std::mutex>
class container class container
{ {
public: public:
template <typename R = void, typename F> template <typename R = void, typename F>
R access(F&& accessor) const R access(F&& accessor) const
{ {
std::lock_guard<MutexType> _{mutex_}; std::lock_guard<MutexType> _{mutex_};
return accessor(object_); return accessor(object_);
} }
template <typename R = void, typename F> template <typename R = void, typename F>
R access(F&& accessor) R access(F&& accessor)
{ {
std::lock_guard<MutexType> _{mutex_}; std::lock_guard<MutexType> _{mutex_};
return accessor(object_); return accessor(object_);
} }
template <typename R = void, typename F> template <typename R = void, typename F>
R access_with_lock(F&& accessor) const R access_with_lock(F&& accessor) const
{ {
std::unique_lock<MutexType> lock{mutex_}; std::unique_lock<MutexType> lock{mutex_};
return accessor(object_, lock); return accessor(object_, lock);
} }
template <typename R = void, typename F> template <typename R = void, typename F>
R access_with_lock(F&& accessor) R access_with_lock(F&& accessor)
{ {
std::unique_lock<MutexType> lock{mutex_}; std::unique_lock<MutexType> lock{mutex_};
return accessor(object_, lock); return accessor(object_, lock);
} }
T& get_raw() { return object_; } T& get_raw() { return object_; }
const T& get_raw() const { return object_; } const T& get_raw() const { return object_; }
private: private:
mutable MutexType mutex_{}; mutable MutexType mutex_{};
T object_{}; T object_{};
}; };
} }

View File

@ -1,54 +1,54 @@
#pragma once #pragma once
#include <type_traits> #include <type_traits>
namespace utils namespace utils
{ {
/* /*
* Copied from here: https://github.com/microsoft/GSL/blob/e0880931ae5885eb988d1a8a57acf8bc2b8dacda/include/gsl/util#L57 * Copied from here: https://github.com/microsoft/GSL/blob/e0880931ae5885eb988d1a8a57acf8bc2b8dacda/include/gsl/util#L57
*/ */
template <class F> template <class F>
class final_action class final_action
{ {
public: public:
static_assert(!std::is_reference<F>::value && !std::is_const<F>::value && static_assert(!std::is_reference<F>::value && !std::is_const<F>::value &&
!std::is_volatile<F>::value, !std::is_volatile<F>::value,
"Final_action should store its callable by value"); "Final_action should store its callable by value");
explicit final_action(F f) noexcept : f_(std::move(f)) explicit final_action(F f) noexcept : f_(std::move(f))
{ {
} }
final_action(final_action&& other) noexcept final_action(final_action&& other) noexcept
: f_(std::move(other.f_)), invoke_(std::exchange(other.invoke_, false)) : f_(std::move(other.f_)), invoke_(std::exchange(other.invoke_, false))
{ {
} }
final_action(const final_action&) = delete; final_action(const final_action&) = delete;
final_action& operator=(const final_action&) = delete; final_action& operator=(const final_action&) = delete;
final_action& operator=(final_action&&) = delete; final_action& operator=(final_action&&) = delete;
~final_action() noexcept ~final_action() noexcept
{ {
if (invoke_) f_(); if (invoke_) f_();
} }
// Added by momo5502 // Added by momo5502
void cancel() void cancel()
{ {
invoke_ = false; invoke_ = false;
} }
private: private:
F f_; F f_;
bool invoke_{true}; bool invoke_{true};
}; };
template <class F> template <class F>
final_action<typename std::remove_cv<typename std::remove_reference<F>::type>::type> final_action<typename std::remove_cv<typename std::remove_reference<F>::type>::type>
finally(F&& f) noexcept finally(F&& f) noexcept
{ {
return final_action<typename std::remove_cv<typename std::remove_reference<F>::type>::type>( return final_action<typename std::remove_cv<typename std::remove_reference<F>::type>::type>(
std::forward<F>(f)); std::forward<F>(f));
} }
} }

View File

@ -1,173 +1,173 @@
#include "hardware_breakpoint.hpp" #include "hardware_breakpoint.hpp"
#include "thread.hpp" #include "thread.hpp"
namespace utils::hardware_breakpoint namespace utils::hardware_breakpoint
{ {
namespace namespace
{ {
void set_bits(uintptr_t& value, const uint32_t bit_index, const uint32_t bits, const uintptr_t new_value) void set_bits(uintptr_t& value, const uint32_t bit_index, const uint32_t bits, const uintptr_t new_value)
{ {
const uintptr_t range_mask = (1ull << bits) - 1ull; const uintptr_t range_mask = (1ull << bits) - 1ull;
const uintptr_t full_mask = ~(range_mask << bit_index); const uintptr_t full_mask = ~(range_mask << bit_index);
value = (value & full_mask) | (new_value << bit_index); value = (value & full_mask) | (new_value << bit_index);
} }
void validate_index(const uint32_t index) void validate_index(const uint32_t index)
{ {
if (index >= 4) if (index >= 4)
{ {
throw std::runtime_error("Invalid index"); throw std::runtime_error("Invalid index");
} }
} }
uint32_t translate_length(const uint32_t length) uint32_t translate_length(const uint32_t length)
{ {
if (length != 1 && length != 2 && length != 4) if (length != 1 && length != 2 && length != 4)
{ {
throw std::runtime_error("Invalid length"); throw std::runtime_error("Invalid length");
} }
return length - 1; return length - 1;
} }
class debug_context class debug_context
{ {
public: public:
debug_context(uint32_t thread_id) debug_context(uint32_t thread_id)
: handle_(thread_id, THREAD_SET_CONTEXT | THREAD_GET_CONTEXT) : handle_(thread_id, THREAD_SET_CONTEXT | THREAD_GET_CONTEXT)
{ {
if (!this->handle_) if (!this->handle_)
{ {
throw std::runtime_error("Unable to access thread"); throw std::runtime_error("Unable to access thread");
} }
this->context_.ContextFlags = CONTEXT_DEBUG_REGISTERS; this->context_.ContextFlags = CONTEXT_DEBUG_REGISTERS;
if (!GetThreadContext(this->handle_, &this->context_)) if (!GetThreadContext(this->handle_, &this->context_))
{ {
throw std::runtime_error("Unable to get thread context"); throw std::runtime_error("Unable to get thread context");
} }
} }
~debug_context() ~debug_context()
{ {
SetThreadContext(this->handle_, &this->context_); SetThreadContext(this->handle_, &this->context_);
} }
debug_context(const debug_context&) = delete; debug_context(const debug_context&) = delete;
debug_context& operator=(const debug_context&) = delete; debug_context& operator=(const debug_context&) = delete;
debug_context(debug_context&& obj) noexcept = delete; debug_context(debug_context&& obj) noexcept = delete;
debug_context& operator=(debug_context&& obj) noexcept = delete; debug_context& operator=(debug_context&& obj) noexcept = delete;
CONTEXT* operator->() CONTEXT* operator->()
{ {
return &this->context_; return &this->context_;
} }
operator CONTEXT&() operator CONTEXT&()
{ {
return this->context_; return this->context_;
} }
private: private:
thread::handle handle_; thread::handle handle_;
CONTEXT context_{}; CONTEXT context_{};
}; };
uint32_t find_free_index(const CONTEXT& context) uint32_t find_free_index(const CONTEXT& context)
{ {
for (uint32_t i = 0; i < 4; ++i) for (uint32_t i = 0; i < 4; ++i)
{ {
if ((context.Dr7 & (1ull << (i << 1ull))) == 0) if ((context.Dr7 & (1ull << (i << 1ull))) == 0)
{ {
return i; return i;
} }
} }
throw std::runtime_error("No free index"); throw std::runtime_error("No free index");
} }
} }
void set_branch_tracing(const bool enabled, CONTEXT& context) void set_branch_tracing(const bool enabled, CONTEXT& context)
{ {
set_bits(context.Dr7, 8, 1, enabled ? 1 : 0); set_bits(context.Dr7, 8, 1, enabled ? 1 : 0);
} }
void set_branch_tracing(const bool enabled, const uint32_t thread_id) void set_branch_tracing(const bool enabled, const uint32_t thread_id)
{ {
debug_context context(thread_id); debug_context context(thread_id);
set_branch_tracing(enabled, context); set_branch_tracing(enabled, context);
} }
uint32_t activate(const uintptr_t address, uint32_t length, const condition cond, CONTEXT& context) uint32_t activate(const uintptr_t address, uint32_t length, const condition cond, CONTEXT& context)
{ {
const auto index = find_free_index(context); const auto index = find_free_index(context);
length = translate_length(length); length = translate_length(length);
(&context.Dr0)[index] = address; (&context.Dr0)[index] = address;
set_bits(context.Dr7, 16 + (index << 2ull), 2, cond); set_bits(context.Dr7, 16 + (index << 2ull), 2, cond);
set_bits(context.Dr7, 18 + (index << 2ull), 2, length); set_bits(context.Dr7, 18 + (index << 2ull), 2, length);
set_bits(context.Dr7, index << 1ull, 1, 1); set_bits(context.Dr7, index << 1ull, 1, 1);
return index; return index;
} }
uint32_t activate(void* address, const uint32_t length, const condition cond, const uint32_t thread_id) uint32_t activate(void* address, const uint32_t length, const condition cond, const uint32_t thread_id)
{ {
return activate(reinterpret_cast<uint64_t>(address), length, cond, thread_id); return activate(reinterpret_cast<uint64_t>(address), length, cond, thread_id);
} }
uint32_t activate(const uint64_t address, const uint32_t length, const condition cond, const uint32_t thread_id) uint32_t activate(const uint64_t address, const uint32_t length, const condition cond, const uint32_t thread_id)
{ {
debug_context context(thread_id); debug_context context(thread_id);
return activate(address, length, cond, context); return activate(address, length, cond, context);
} }
void deactivate_address(const uint64_t address, CONTEXT& context) void deactivate_address(const uint64_t address, CONTEXT& context)
{ {
for (auto i = 0; i < 4; ++i) for (auto i = 0; i < 4; ++i)
{ {
if ((&context.Dr0)[i] == address) if ((&context.Dr0)[i] == address)
{ {
deactivate(i, context); deactivate(i, context);
} }
} }
} }
void deactivate_address(void* address, const uint32_t thread_id) void deactivate_address(void* address, const uint32_t thread_id)
{ {
return deactivate_address(reinterpret_cast<uint64_t>(address), thread_id); return deactivate_address(reinterpret_cast<uint64_t>(address), thread_id);
} }
void deactivate_address(const uint64_t address, const uint32_t thread_id) void deactivate_address(const uint64_t address, const uint32_t thread_id)
{ {
debug_context context(thread_id); debug_context context(thread_id);
deactivate_address(address, context); deactivate_address(address, context);
} }
void deactivate(const uint32_t index, CONTEXT& context) void deactivate(const uint32_t index, CONTEXT& context)
{ {
validate_index(index); validate_index(index);
set_bits(context.Dr7, index << 1ull, 1, 0); set_bits(context.Dr7, index << 1ull, 1, 0);
} }
void deactivate(const uint32_t index, const uint32_t thread_id) void deactivate(const uint32_t index, const uint32_t thread_id)
{ {
debug_context context(thread_id); debug_context context(thread_id);
deactivate(index, context); deactivate(index, context);
} }
void deactivate_all(CONTEXT& context) void deactivate_all(CONTEXT& context)
{ {
context.Dr7 = 0; context.Dr7 = 0;
} }
void deactivate_all(const uint32_t thread_id) void deactivate_all(const uint32_t thread_id)
{ {
debug_context context(thread_id); debug_context context(thread_id);
deactivate_all(context); deactivate_all(context);
} }
} }

View File

@ -1,32 +1,32 @@
#pragma once #pragma once
#include <thread> #include <thread>
#include "nt.hpp" #include "nt.hpp"
namespace utils::hardware_breakpoint namespace utils::hardware_breakpoint
{ {
enum condition enum condition
{ {
execute = 0, execute = 0,
write = 1, write = 1,
read_write = 3 read_write = 3
}; };
void set_branch_tracing(bool enabled, CONTEXT& context); void set_branch_tracing(bool enabled, CONTEXT& context);
void set_branch_tracing(bool enabled, uint32_t thread_id = GetCurrentThreadId()); void set_branch_tracing(bool enabled, uint32_t thread_id = GetCurrentThreadId());
uint32_t activate(uint64_t address, uint32_t length, condition cond, CONTEXT& context); uint32_t activate(uint64_t address, uint32_t length, condition cond, CONTEXT& context);
uint32_t activate(void* address, uint32_t length, condition cond, uint32_t thread_id = GetCurrentThreadId()); uint32_t activate(void* address, uint32_t length, condition cond, uint32_t thread_id = GetCurrentThreadId());
uint32_t activate(uint64_t address, uint32_t length, condition cond, uint32_t thread_id = GetCurrentThreadId()); uint32_t activate(uint64_t address, uint32_t length, condition cond, uint32_t thread_id = GetCurrentThreadId());
void deactivate_address(uint64_t address, CONTEXT& context); void deactivate_address(uint64_t address, CONTEXT& context);
void deactivate_address(void* address, uint32_t thread_id = GetCurrentThreadId()); void deactivate_address(void* address, uint32_t thread_id = GetCurrentThreadId());
void deactivate_address(uint64_t address, uint32_t thread_id = GetCurrentThreadId()); void deactivate_address(uint64_t address, uint32_t thread_id = GetCurrentThreadId());
void deactivate(uint32_t index, CONTEXT& context); void deactivate(uint32_t index, CONTEXT& context);
void deactivate(uint32_t index, uint32_t thread_id = GetCurrentThreadId()); void deactivate(uint32_t index, uint32_t thread_id = GetCurrentThreadId());
void deactivate_all(CONTEXT& context); void deactivate_all(CONTEXT& context);
void deactivate_all(uint32_t thread_id = GetCurrentThreadId()); void deactivate_all(uint32_t thread_id = GetCurrentThreadId());
} }

View File

@ -1,484 +1,484 @@
#include "hook.hpp" #include "hook.hpp"
#include <map> #include <map>
#include "MinHook.hpp" #include "MinHook.hpp"
#include "concurrency.hpp" #include "concurrency.hpp"
#include "string.hpp" #include "string.hpp"
#include "nt.hpp" #include "nt.hpp"
#ifdef max #ifdef max
#undef max #undef max
#endif #endif
#ifdef min #ifdef min
#undef min #undef min
#endif #endif
namespace utils::hook namespace utils::hook
{ {
namespace namespace
{ {
uint8_t* allocate_somewhere_near(const void* base_address, const size_t size) uint8_t* allocate_somewhere_near(const void* base_address, const size_t size)
{ {
size_t offset = 0; size_t offset = 0;
while (true) while (true)
{ {
offset += size; offset += size;
auto* target_address = static_cast<const uint8_t*>(base_address) - offset; auto* target_address = static_cast<const uint8_t*>(base_address) - offset;
if (is_relatively_far(base_address, target_address)) if (is_relatively_far(base_address, target_address))
{ {
return nullptr; return nullptr;
} }
const auto res = VirtualAlloc(const_cast<uint8_t*>(target_address), size, MEM_RESERVE | MEM_COMMIT, const auto res = VirtualAlloc(const_cast<uint8_t*>(target_address), size, MEM_RESERVE | MEM_COMMIT,
PAGE_EXECUTE_READWRITE); PAGE_EXECUTE_READWRITE);
if (res) if (res)
{ {
if (is_relatively_far(base_address, target_address)) if (is_relatively_far(base_address, target_address))
{ {
VirtualFree(res, 0, MEM_RELEASE); VirtualFree(res, 0, MEM_RELEASE);
return nullptr; return nullptr;
} }
return static_cast<uint8_t*>(res); return static_cast<uint8_t*>(res);
} }
} }
} }
class memory class memory
{ {
public: public:
memory() = default; memory() = default;
memory(const void* ptr) memory(const void* ptr)
: memory() : memory()
{ {
this->length_ = 0x1000; this->length_ = 0x1000;
this->buffer_ = allocate_somewhere_near(ptr, this->length_); this->buffer_ = allocate_somewhere_near(ptr, this->length_);
if (!this->buffer_) if (!this->buffer_)
{ {
throw std::runtime_error("Failed to allocate"); throw std::runtime_error("Failed to allocate");
} }
} }
~memory() ~memory()
{ {
if (this->buffer_) if (this->buffer_)
{ {
VirtualFree(this->buffer_, 0, MEM_RELEASE); VirtualFree(this->buffer_, 0, MEM_RELEASE);
} }
} }
memory(memory&& obj) noexcept memory(memory&& obj) noexcept
: memory() : memory()
{ {
this->operator=(std::move(obj)); this->operator=(std::move(obj));
} }
memory& operator=(memory&& obj) noexcept memory& operator=(memory&& obj) noexcept
{ {
if (this != &obj) if (this != &obj)
{ {
this->~memory(); this->~memory();
this->buffer_ = obj.buffer_; this->buffer_ = obj.buffer_;
this->length_ = obj.length_; this->length_ = obj.length_;
this->offset_ = obj.offset_; this->offset_ = obj.offset_;
obj.buffer_ = nullptr; obj.buffer_ = nullptr;
obj.length_ = 0; obj.length_ = 0;
obj.offset_ = 0; obj.offset_ = 0;
} }
return *this; return *this;
} }
void* allocate(const size_t length) void* allocate(const size_t length)
{ {
if (!this->buffer_) if (!this->buffer_)
{ {
return nullptr; return nullptr;
} }
if (this->offset_ + length > this->length_) if (this->offset_ + length > this->length_)
{ {
return nullptr; return nullptr;
} }
const auto ptr = this->get_ptr(); const auto ptr = this->get_ptr();
this->offset_ += length; this->offset_ += length;
return ptr; return ptr;
} }
void* get_ptr() const void* get_ptr() const
{ {
return this->buffer_ + this->offset_; return this->buffer_ + this->offset_;
} }
private: private:
uint8_t* buffer_{}; uint8_t* buffer_{};
size_t length_{}; size_t length_{};
size_t offset_{}; size_t offset_{};
}; };
void* get_memory_near(const void* address, const size_t size) void* get_memory_near(const void* address, const size_t size)
{ {
static concurrency::container<std::vector<memory>> memory_container{}; static concurrency::container<std::vector<memory>> memory_container{};
return memory_container.access<void*>([&](std::vector<memory>& memories) return memory_container.access<void*>([&](std::vector<memory>& memories)
{ {
for (auto& memory : memories) for (auto& memory : memories)
{ {
if (!is_relatively_far(address, memory.get_ptr())) if (!is_relatively_far(address, memory.get_ptr()))
{ {
const auto buffer = memory.allocate(size); const auto buffer = memory.allocate(size);
if (buffer) if (buffer)
{ {
return buffer; return buffer;
} }
} }
} }
memories.emplace_back(address); memories.emplace_back(address);
return memories.back().allocate(size); return memories.back().allocate(size);
}); });
} }
void* initialize_min_hook() void* initialize_min_hook()
{ {
static class min_hook_init static class min_hook_init
{ {
public: public:
min_hook_init() min_hook_init()
{ {
if (MH_Initialize() != MH_OK) if (MH_Initialize() != MH_OK)
{ {
throw std::runtime_error("Failed to initialize MinHook"); throw std::runtime_error("Failed to initialize MinHook");
} }
} }
~min_hook_init() ~min_hook_init()
{ {
MH_Uninitialize(); MH_Uninitialize();
} }
} min_hook_init; } min_hook_init;
return &min_hook_init; return &min_hook_init;
} }
} }
detour::detour() detour::detour()
{ {
(void)initialize_min_hook(); (void)initialize_min_hook();
} }
detour::detour(const size_t place, void* target) detour::detour(const size_t place, void* target)
: detour(reinterpret_cast<void*>(place), target) : detour(reinterpret_cast<void*>(place), target)
{ {
} }
detour::detour(void* place, void* target) detour::detour(void* place, void* target)
: detour() : detour()
{ {
this->create(place, target); this->create(place, target);
} }
detour::~detour() detour::~detour()
{ {
this->clear(); this->clear();
} }
void detour::enable() void detour::enable()
{ {
MH_EnableHook(this->place_); MH_EnableHook(this->place_);
if (!this->moved_data_.empty()) if (!this->moved_data_.empty())
{ {
this->move(); this->move();
} }
} }
void detour::disable() void detour::disable()
{ {
this->un_move(); this->un_move();
MH_DisableHook(this->place_); MH_DisableHook(this->place_);
} }
void detour::create(void* place, void* target) void detour::create(void* place, void* target)
{ {
this->clear(); this->clear();
this->place_ = place; this->place_ = place;
if (MH_CreateHook(this->place_, target, &this->original_) != MH_OK) if (MH_CreateHook(this->place_, target, &this->original_) != MH_OK)
{ {
//throw std::runtime_error(string::va("Unable to create hook at location: %p", this->place_)); //throw std::runtime_error(string::va("Unable to create hook at location: %p", this->place_));
} }
this->enable(); this->enable();
} }
void detour::create(const size_t place, void* target) void detour::create(const size_t place, void* target)
{ {
MH_Initialize(); MH_Initialize();
this->create(reinterpret_cast<void*>(place), target); this->create(reinterpret_cast<void*>(place), target);
} }
void detour::clear() void detour::clear()
{ {
if (this->place_) if (this->place_)
{ {
this->un_move(); this->un_move();
MH_RemoveHook(this->place_); MH_RemoveHook(this->place_);
} }
this->place_ = nullptr; this->place_ = nullptr;
this->original_ = nullptr; this->original_ = nullptr;
this->moved_data_ = {}; this->moved_data_ = {};
} }
void detour::move() void detour::move()
{ {
this->moved_data_ = move_hook(this->place_); this->moved_data_ = move_hook(this->place_);
} }
void* detour::get_place() const void* detour::get_place() const
{ {
return this->place_; return this->place_;
} }
void* detour::get_original() const void* detour::get_original() const
{ {
return this->original_; return this->original_;
} }
void detour::un_move() void detour::un_move()
{ {
if (!this->moved_data_.empty()) if (!this->moved_data_.empty())
{ {
copy(this->place_, this->moved_data_.data(), this->moved_data_.size()); copy(this->place_, this->moved_data_.data(), this->moved_data_.size());
} }
} }
std::optional<std::pair<void*, void*>> iat(const nt::library& library, const std::string& target_library, const std::string& process, void* stub) std::optional<std::pair<void*, void*>> iat(const nt::library& library, const std::string& target_library, const std::string& process, void* stub)
{ {
if (!library.is_valid()) return {}; if (!library.is_valid()) return {};
auto* const ptr = library.get_iat_entry(target_library, process); auto* const ptr = library.get_iat_entry(target_library, process);
if (!ptr) return {}; if (!ptr) return {};
DWORD protect; DWORD protect;
VirtualProtect(ptr, sizeof(*ptr), PAGE_EXECUTE_READWRITE, &protect); VirtualProtect(ptr, sizeof(*ptr), PAGE_EXECUTE_READWRITE, &protect);
std::swap(*ptr, stub); std::swap(*ptr, stub);
VirtualProtect(ptr, sizeof(*ptr), protect, &protect); VirtualProtect(ptr, sizeof(*ptr), protect, &protect);
return {{ptr, stub}}; return {{ptr, stub}};
} }
void nop(void* place, const size_t length) void nop(void* place, const size_t length)
{ {
DWORD old_protect{}; DWORD old_protect{};
VirtualProtect(place, length, PAGE_EXECUTE_READWRITE, &old_protect); VirtualProtect(place, length, PAGE_EXECUTE_READWRITE, &old_protect);
std::memset(place, 0x90, length); std::memset(place, 0x90, length);
VirtualProtect(place, length, old_protect, &old_protect); VirtualProtect(place, length, old_protect, &old_protect);
FlushInstructionCache(GetCurrentProcess(), place, length); FlushInstructionCache(GetCurrentProcess(), place, length);
} }
void nop(const size_t place, const size_t length) void nop(const size_t place, const size_t length)
{ {
nop(reinterpret_cast<void*>(place), length); nop(reinterpret_cast<void*>(place), length);
} }
void copy(void* place, const void* data, const size_t length) void copy(void* place, const void* data, const size_t length)
{ {
DWORD old_protect{}; DWORD old_protect{};
VirtualProtect(place, length, PAGE_EXECUTE_READWRITE, &old_protect); VirtualProtect(place, length, PAGE_EXECUTE_READWRITE, &old_protect);
std::memmove(place, data, length); std::memmove(place, data, length);
VirtualProtect(place, length, old_protect, &old_protect); VirtualProtect(place, length, old_protect, &old_protect);
FlushInstructionCache(GetCurrentProcess(), place, length); FlushInstructionCache(GetCurrentProcess(), place, length);
} }
void copy(const size_t place, const void* data, const size_t length) void copy(const size_t place, const void* data, const size_t length)
{ {
copy(reinterpret_cast<void*>(place), data, length); copy(reinterpret_cast<void*>(place), data, length);
} }
void copy_string(void* place, const char* str) void copy_string(void* place, const char* str)
{ {
copy(reinterpret_cast<void*>(place), str, strlen(str) + 1); copy(reinterpret_cast<void*>(place), str, strlen(str) + 1);
} }
void copy_string(const size_t place, const char* str) void copy_string(const size_t place, const char* str)
{ {
copy_string(reinterpret_cast<void*>(place), str); copy_string(reinterpret_cast<void*>(place), str);
} }
bool is_relatively_far(const void* pointer, const void* data, const int offset) bool is_relatively_far(const void* pointer, const void* data, const int offset)
{ {
const int64_t diff = size_t(data) - (size_t(pointer) + offset); const int64_t diff = size_t(data) - (size_t(pointer) + offset);
const auto small_diff = int32_t(diff); const auto small_diff = int32_t(diff);
return diff != int64_t(small_diff); return diff != int64_t(small_diff);
} }
void call(void* pointer, void* data) void call(void* pointer, void* data)
{ {
if (is_relatively_far(pointer, data)) if (is_relatively_far(pointer, data))
{ {
auto* trampoline = get_memory_near(pointer, 14); auto* trampoline = get_memory_near(pointer, 14);
if (!trampoline) if (!trampoline)
{ {
throw std::runtime_error("Too far away to create 32bit relative branch"); throw std::runtime_error("Too far away to create 32bit relative branch");
} }
call(pointer, trampoline); call(pointer, trampoline);
jump(trampoline, data, true, true); jump(trampoline, data, true, true);
return; return;
} }
uint8_t copy_data[5]; uint8_t copy_data[5];
copy_data[0] = 0xE8; copy_data[0] = 0xE8;
*reinterpret_cast<int32_t*>(&copy_data[1]) = int32_t(size_t(data) - (size_t(pointer) + 5)); *reinterpret_cast<int32_t*>(&copy_data[1]) = int32_t(size_t(data) - (size_t(pointer) + 5));
auto* patch_pointer = PBYTE(pointer); auto* patch_pointer = PBYTE(pointer);
copy(patch_pointer, copy_data, sizeof(copy_data)); copy(patch_pointer, copy_data, sizeof(copy_data));
} }
void call(const size_t pointer, void* data) void call(const size_t pointer, void* data)
{ {
return call(reinterpret_cast<void*>(pointer), data); return call(reinterpret_cast<void*>(pointer), data);
} }
void call(const size_t pointer, const size_t data) void call(const size_t pointer, const size_t data)
{ {
return call(pointer, reinterpret_cast<void*>(data)); return call(pointer, reinterpret_cast<void*>(data));
} }
void jump(void* pointer, void* data, const bool use_far, const bool use_safe) void jump(void* pointer, void* data, const bool use_far, const bool use_safe)
{ {
static const unsigned char jump_data[] = { static const unsigned char jump_data[] = {
0x48, 0xb8, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0xff, 0xe0 0x48, 0xb8, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0xff, 0xe0
}; };
static const unsigned char jump_data_safe[] = { static const unsigned char jump_data_safe[] = {
0xFF, 0x25, 0x00, 0x00, 0x00, 0x00 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00
}; };
if (!use_far && is_relatively_far(pointer, data)) if (!use_far && is_relatively_far(pointer, data))
{ {
auto* trampoline = get_memory_near(pointer, 14); auto* trampoline = get_memory_near(pointer, 14);
if (!trampoline) if (!trampoline)
{ {
throw std::runtime_error("Too far away to create 32bit relative branch"); throw std::runtime_error("Too far away to create 32bit relative branch");
} }
jump(pointer, trampoline, false, false); jump(pointer, trampoline, false, false);
jump(trampoline, data, true, true); jump(trampoline, data, true, true);
return; return;
} }
auto* patch_pointer = PBYTE(pointer); auto* patch_pointer = PBYTE(pointer);
if (use_far) if (use_far)
{ {
if (use_safe) if (use_safe)
{ {
uint8_t copy_data[sizeof(jump_data_safe) + sizeof(data)]; uint8_t copy_data[sizeof(jump_data_safe) + sizeof(data)];
memcpy(copy_data, jump_data_safe, sizeof(jump_data_safe)); memcpy(copy_data, jump_data_safe, sizeof(jump_data_safe));
memcpy(copy_data + sizeof(jump_data_safe), &data, sizeof(data)); memcpy(copy_data + sizeof(jump_data_safe), &data, sizeof(data));
copy(patch_pointer, copy_data, sizeof(copy_data)); copy(patch_pointer, copy_data, sizeof(copy_data));
} }
else else
{ {
uint8_t copy_data[sizeof(jump_data)]; uint8_t copy_data[sizeof(jump_data)];
memcpy(copy_data, jump_data, sizeof(jump_data)); memcpy(copy_data, jump_data, sizeof(jump_data));
memcpy(copy_data + 2, &data, sizeof(data)); memcpy(copy_data + 2, &data, sizeof(data));
copy(patch_pointer, copy_data, sizeof(copy_data)); copy(patch_pointer, copy_data, sizeof(copy_data));
} }
} }
else else
{ {
uint8_t copy_data[5]; uint8_t copy_data[5];
copy_data[0] = 0xE9; copy_data[0] = 0xE9;
*reinterpret_cast<int32_t*>(&copy_data[1]) = int32_t(size_t(data) - (size_t(pointer) + 5)); *reinterpret_cast<int32_t*>(&copy_data[1]) = int32_t(size_t(data) - (size_t(pointer) + 5));
copy(patch_pointer, copy_data, sizeof(copy_data)); copy(patch_pointer, copy_data, sizeof(copy_data));
} }
} }
void jump(const size_t pointer, void* data, const bool use_far, const bool use_safe) void jump(const size_t pointer, void* data, const bool use_far, const bool use_safe)
{ {
return jump(reinterpret_cast<void*>(pointer), data, use_far, use_safe); return jump(reinterpret_cast<void*>(pointer), data, use_far, use_safe);
} }
void jump(const size_t pointer, const size_t data, const bool use_far, const bool use_safe) void jump(const size_t pointer, const size_t data, const bool use_far, const bool use_safe)
{ {
return jump(pointer, reinterpret_cast<void*>(data), use_far, use_safe); return jump(pointer, reinterpret_cast<void*>(data), use_far, use_safe);
} }
void inject(void* pointer, const void* data) void inject(void* pointer, const void* data)
{ {
if (is_relatively_far(pointer, data, 4)) if (is_relatively_far(pointer, data, 4))
{ {
throw std::runtime_error("Too far away to create 32bit relative branch"); throw std::runtime_error("Too far away to create 32bit relative branch");
} }
set<int32_t>(pointer, int32_t(size_t(data) - (size_t(pointer) + 4))); set<int32_t>(pointer, int32_t(size_t(data) - (size_t(pointer) + 4)));
} }
void inject(const size_t pointer, const void* data) void inject(const size_t pointer, const void* data)
{ {
return inject(reinterpret_cast<void*>(pointer), data); return inject(reinterpret_cast<void*>(pointer), data);
} }
std::vector<uint8_t> move_hook(void* pointer) std::vector<uint8_t> move_hook(void* pointer)
{ {
std::vector<uint8_t> original_data{}; std::vector<uint8_t> original_data{};
auto* data_ptr = static_cast<uint8_t*>(pointer); auto* data_ptr = static_cast<uint8_t*>(pointer);
if (data_ptr[0] == 0xE9) if (data_ptr[0] == 0xE9)
{ {
original_data.resize(6); original_data.resize(6);
memmove(original_data.data(), pointer, original_data.size()); memmove(original_data.data(), pointer, original_data.size());
auto* target = follow_branch(data_ptr); auto* target = follow_branch(data_ptr);
nop(data_ptr, 1); nop(data_ptr, 1);
jump(data_ptr + 1, target); jump(data_ptr + 1, target);
} }
else if (data_ptr[0] == 0xFF && data_ptr[1] == 0x25) else if (data_ptr[0] == 0xFF && data_ptr[1] == 0x25)
{ {
original_data.resize(15); original_data.resize(15);
memmove(original_data.data(), pointer, original_data.size()); memmove(original_data.data(), pointer, original_data.size());
copy(data_ptr + 1, data_ptr, 14); copy(data_ptr + 1, data_ptr, 14);
nop(data_ptr, 1); nop(data_ptr, 1);
} }
else else
{ {
throw std::runtime_error("No branch instruction found"); throw std::runtime_error("No branch instruction found");
} }
return original_data; return original_data;
} }
std::vector<uint8_t> move_hook(const size_t pointer) std::vector<uint8_t> move_hook(const size_t pointer)
{ {
return move_hook(reinterpret_cast<void*>(pointer)); return move_hook(reinterpret_cast<void*>(pointer));
} }
void* follow_branch(void* address) void* follow_branch(void* address)
{ {
auto* const data = static_cast<uint8_t*>(address); auto* const data = static_cast<uint8_t*>(address);
if (*data != 0xE8 && *data != 0xE9) if (*data != 0xE8 && *data != 0xE9)
{ {
throw std::runtime_error("No branch instruction found"); throw std::runtime_error("No branch instruction found");
} }
return extract<void*>(data + 1); return extract<void*>(data + 1);
} }
} }

View File

@ -1,186 +1,186 @@
#pragma once #pragma once
#include "signature.hpp" #include "signature.hpp"
#pragma comment(lib, "minhook.lib") #pragma comment(lib, "minhook.lib")
namespace utils::hook namespace utils::hook
{ {
namespace detail namespace detail
{ {
template <size_t Entries> template <size_t Entries>
std::vector<size_t(*)()> get_iota_functions() std::vector<size_t(*)()> get_iota_functions()
{ {
if constexpr (Entries == 0) if constexpr (Entries == 0)
{ {
std::vector<size_t(*)()> functions; std::vector<size_t(*)()> functions;
return functions; return functions;
} }
else else
{ {
auto functions = get_iota_functions<Entries - 1>(); auto functions = get_iota_functions<Entries - 1>();
functions.emplace_back([]() functions.emplace_back([]()
{ {
return Entries - 1; return Entries - 1;
}); });
return functions; return functions;
} }
} }
} }
// Gets the pointer to the entry in the v-table. // Gets the pointer to the entry in the v-table.
// It seems otherwise impossible to get this. // It seems otherwise impossible to get this.
// This is ugly as fuck and only safely works on x64 // This is ugly as fuck and only safely works on x64
// Example: // Example:
// ID3D11Device* device = ... // ID3D11Device* device = ...
// auto entry = get_vtable_entry(device, &ID3D11Device::CreateTexture2D); // auto entry = get_vtable_entry(device, &ID3D11Device::CreateTexture2D);
template <size_t Entries = 100, typename Class, typename T, typename... Args> template <size_t Entries = 100, typename Class, typename T, typename... Args>
void** get_vtable_entry(Class* obj, T (Class::* entry)(Args ...)) void** get_vtable_entry(Class* obj, T (Class::* entry)(Args ...))
{ {
union union
{ {
decltype(entry) func; decltype(entry) func;
void* pointer; void* pointer;
}; };
func = entry; func = entry;
auto iota_functions = detail::get_iota_functions<Entries>(); auto iota_functions = detail::get_iota_functions<Entries>();
auto* object = iota_functions.data(); auto* object = iota_functions.data();
using fake_func = size_t(__thiscall*)(void* self); using fake_func = size_t(__thiscall*)(void* self);
auto index = static_cast<fake_func>(pointer)(&object); auto index = static_cast<fake_func>(pointer)(&object);
void** obj_v_table = *reinterpret_cast<void***>(obj); void** obj_v_table = *reinterpret_cast<void***>(obj);
return &obj_v_table[index]; return &obj_v_table[index];
} }
class detour class detour
{ {
public: public:
detour(); detour();
detour(void* place, void* target); detour(void* place, void* target);
detour(size_t place, void* target); detour(size_t place, void* target);
~detour(); ~detour();
detour(detour&& other) noexcept detour(detour&& other) noexcept
{ {
this->operator=(std::move(other)); this->operator=(std::move(other));
} }
detour& operator=(detour&& other) noexcept detour& operator=(detour&& other) noexcept
{ {
if (this != &other) if (this != &other)
{ {
this->clear(); this->clear();
this->place_ = other.place_; this->place_ = other.place_;
this->original_ = other.original_; this->original_ = other.original_;
this->moved_data_ = other.moved_data_; this->moved_data_ = other.moved_data_;
other.place_ = nullptr; other.place_ = nullptr;
other.original_ = nullptr; other.original_ = nullptr;
other.moved_data_ = {}; other.moved_data_ = {};
} }
return *this; return *this;
} }
detour(const detour&) = delete; detour(const detour&) = delete;
detour& operator=(const detour&) = delete; detour& operator=(const detour&) = delete;
void enable(); void enable();
void disable(); void disable();
void create(void* place, void* target); void create(void* place, void* target);
void create(size_t place, void* target); void create(size_t place, void* target);
void clear(); void clear();
void move(); void move();
void* get_place() const; void* get_place() const;
template <typename T> template <typename T>
T* get() const T* get() const
{ {
return static_cast<T*>(this->get_original()); return static_cast<T*>(this->get_original());
} }
template <typename T = void, typename... Args> template <typename T = void, typename... Args>
T stub(Args ... args) T stub(Args ... args)
{ {
return static_cast<T(*)(Args ...)>(this->get_original())(args...); return static_cast<T(*)(Args ...)>(this->get_original())(args...);
} }
[[nodiscard]] void* get_original() const; [[nodiscard]] void* get_original() const;
private: private:
std::vector<uint8_t> moved_data_{}; std::vector<uint8_t> moved_data_{};
void* place_{}; void* place_{};
void* original_{}; void* original_{};
void un_move(); void un_move();
}; };
std::optional<std::pair<void*, void*>> iat(const nt::library& library, const std::string& target_library, std::optional<std::pair<void*, void*>> iat(const nt::library& library, const std::string& target_library,
const std::string& process, void* stub); const std::string& process, void* stub);
void nop(void* place, size_t length); void nop(void* place, size_t length);
void nop(size_t place, size_t length); void nop(size_t place, size_t length);
void copy(void* place, const void* data, size_t length); void copy(void* place, const void* data, size_t length);
void copy(size_t place, const void* data, size_t length); void copy(size_t place, const void* data, size_t length);
void copy_string(void* place, const char* str); void copy_string(void* place, const char* str);
void copy_string(size_t place, const char* str); void copy_string(size_t place, const char* str);
bool is_relatively_far(const void* pointer, const void* data, int offset = 5); bool is_relatively_far(const void* pointer, const void* data, int offset = 5);
void call(void* pointer, void* data); void call(void* pointer, void* data);
void call(size_t pointer, void* data); void call(size_t pointer, void* data);
void call(size_t pointer, size_t data); void call(size_t pointer, size_t data);
void jump(void* pointer, void* data, bool use_far = false, bool use_safe = false); void jump(void* pointer, void* data, bool use_far = false, bool use_safe = false);
void jump(size_t pointer, void* data, bool use_far = false, bool use_safe = false); void jump(size_t pointer, void* data, bool use_far = false, bool use_safe = false);
void jump(size_t pointer, size_t data, bool use_far = false, bool use_safe = false); void jump(size_t pointer, size_t data, bool use_far = false, bool use_safe = false);
void inject(void* pointer, const void* data); void inject(void* pointer, const void* data);
void inject(size_t pointer, const void* data); void inject(size_t pointer, const void* data);
std::vector<uint8_t> move_hook(void* pointer); std::vector<uint8_t> move_hook(void* pointer);
std::vector<uint8_t> move_hook(size_t pointer); std::vector<uint8_t> move_hook(size_t pointer);
template <typename T> template <typename T>
T extract(void* address) T extract(void* address)
{ {
auto* const data = static_cast<uint8_t*>(address); auto* const data = static_cast<uint8_t*>(address);
const auto offset = *reinterpret_cast<int32_t*>(data); const auto offset = *reinterpret_cast<int32_t*>(data);
return reinterpret_cast<T>(data + offset + 4); return reinterpret_cast<T>(data + offset + 4);
} }
void* follow_branch(void* address); void* follow_branch(void* address);
template <typename T> template <typename T>
static void set(void* place, T value = false) static void set(void* place, T value = false)
{ {
copy(place, &value, sizeof(value)); copy(place, &value, sizeof(value));
} }
template <typename T> template <typename T>
static void set(const size_t place, T value = false) static void set(const size_t place, T value = false)
{ {
return set<T>(reinterpret_cast<void*>(place), value); return set<T>(reinterpret_cast<void*>(place), value);
} }
template <typename T, typename... Args> template <typename T, typename... Args>
static T invoke(size_t func, Args ... args) static T invoke(size_t func, Args ... args)
{ {
return reinterpret_cast<T(*)(Args ...)>(func)(args...); return reinterpret_cast<T(*)(Args ...)>(func)(args...);
} }
template <typename T, typename... Args> template <typename T, typename... Args>
static T invoke(void* func, Args ... args) static T invoke(void* func, Args ... args)
{ {
return static_cast<T(*)(Args ...)>(func)(args...); return static_cast<T(*)(Args ...)>(func)(args...);
} }
} }

View File

@ -1,48 +1,48 @@
#include "http.hpp" #include "http.hpp"
#include "nt.hpp" #include "nt.hpp"
#include <atlcomcli.h> #include <atlcomcli.h>
namespace utils::http namespace utils::http
{ {
std::optional<std::string> get_data(const std::string& url) std::optional<std::string> get_data(const std::string& url)
{ {
CComPtr<IStream> stream; CComPtr<IStream> stream;
if (FAILED(URLOpenBlockingStreamA(nullptr, url.data(), &stream, 0, nullptr))) if (FAILED(URLOpenBlockingStreamA(nullptr, url.data(), &stream, 0, nullptr)))
{ {
return {}; return {};
} }
char buffer[0x1000]; char buffer[0x1000];
std::string result; std::string result;
HRESULT status{}; HRESULT status{};
do do
{ {
DWORD bytes_read = 0; DWORD bytes_read = 0;
status = stream->Read(buffer, sizeof(buffer), &bytes_read); status = stream->Read(buffer, sizeof(buffer), &bytes_read);
if (bytes_read > 0) if (bytes_read > 0)
{ {
result.append(buffer, bytes_read); result.append(buffer, bytes_read);
} }
} }
while (SUCCEEDED(status) && status != S_FALSE); while (SUCCEEDED(status) && status != S_FALSE);
if (FAILED(status)) if (FAILED(status))
{ {
return {}; return {};
} }
return {result}; return {result};
} }
std::future<std::optional<std::string>> get_data_async(const std::string& url) std::future<std::optional<std::string>> get_data_async(const std::string& url)
{ {
return std::async(std::launch::async, [url]() return std::async(std::launch::async, [url]()
{ {
return get_data(url); return get_data(url);
}); });
} }
} }

View File

@ -1,13 +1,13 @@
#pragma once #pragma once
#include <string> #include <string>
#include <optional> #include <optional>
#include <future> #include <future>
#pragma comment(lib, "Urlmon.lib") #pragma comment(lib, "Urlmon.lib")
namespace utils::http namespace utils::http
{ {
std::optional<std::string> get_data(const std::string& url); std::optional<std::string> get_data(const std::string& url);
std::future<std::optional<std::string>> get_data_async(const std::string& url); std::future<std::optional<std::string>> get_data_async(const std::string& url);
} }

View File

@ -1,130 +1,130 @@
#include "io.hpp" #include "io.hpp"
#include "nt.hpp" #include "nt.hpp"
#include <fstream> #include <fstream>
namespace utils::io namespace utils::io
{ {
bool remove_file(const std::filesystem::path& file) bool remove_file(const std::filesystem::path& file)
{ {
if(DeleteFileW(file.wstring().data()) != FALSE) if(DeleteFileW(file.wstring().data()) != FALSE)
{ {
return true; return true;
} }
return GetLastError() == ERROR_FILE_NOT_FOUND; return GetLastError() == ERROR_FILE_NOT_FOUND;
} }
bool move_file(const std::filesystem::path& src, const std::filesystem::path& target) bool move_file(const std::filesystem::path& src, const std::filesystem::path& target)
{ {
return MoveFileW(src.wstring().data(), target.wstring().data()) == TRUE; return MoveFileW(src.wstring().data(), target.wstring().data()) == TRUE;
} }
bool file_exists(const std::string& file) bool file_exists(const std::string& file)
{ {
return std::ifstream(file).good(); return std::ifstream(file).good();
} }
bool write_file(const std::string& file, const std::string& data, const bool append) bool write_file(const std::string& file, const std::string& data, const bool append)
{ {
const auto pos = file.find_last_of("/\\"); const auto pos = file.find_last_of("/\\");
if (pos != std::string::npos) if (pos != std::string::npos)
{ {
create_directory(file.substr(0, pos)); create_directory(file.substr(0, pos));
} }
std::ofstream stream( std::ofstream stream(
file, std::ios::binary | std::ofstream::out | (append ? std::ofstream::app : 0)); file, std::ios::binary | std::ofstream::out | (append ? std::ofstream::app : 0));
if (stream.is_open()) if (stream.is_open())
{ {
stream.write(data.data(), static_cast<std::streamsize>(data.size())); stream.write(data.data(), static_cast<std::streamsize>(data.size()));
stream.close(); stream.close();
return true; return true;
} }
return false; return false;
} }
std::string read_file(const std::string& file) std::string read_file(const std::string& file)
{ {
std::string data; std::string data;
read_file(file, &data); read_file(file, &data);
return data; return data;
} }
bool read_file(const std::string& file, std::string* data) bool read_file(const std::string& file, std::string* data)
{ {
if (!data) return false; if (!data) return false;
data->clear(); data->clear();
if (file_exists(file)) if (file_exists(file))
{ {
std::ifstream stream(file, std::ios::binary); std::ifstream stream(file, std::ios::binary);
if (!stream.is_open()) return false; if (!stream.is_open()) return false;
stream.seekg(0, std::ios::end); stream.seekg(0, std::ios::end);
const std::streamsize size = stream.tellg(); const std::streamsize size = stream.tellg();
stream.seekg(0, std::ios::beg); stream.seekg(0, std::ios::beg);
if (size > -1) if (size > -1)
{ {
data->resize(static_cast<std::uint32_t>(size)); data->resize(static_cast<std::uint32_t>(size));
stream.read(data->data(), size); stream.read(data->data(), size);
stream.close(); stream.close();
return true; return true;
} }
} }
return false; return false;
} }
std::size_t file_size(const std::string& file) std::size_t file_size(const std::string& file)
{ {
if (file_exists(file)) if (file_exists(file))
{ {
std::ifstream stream(file, std::ios::binary); std::ifstream stream(file, std::ios::binary);
if (stream.good()) if (stream.good())
{ {
stream.seekg(0, std::ios::end); stream.seekg(0, std::ios::end);
return static_cast<std::size_t>(stream.tellg()); return static_cast<std::size_t>(stream.tellg());
} }
} }
return 0; return 0;
} }
bool create_directory(const std::filesystem::path& directory) bool create_directory(const std::filesystem::path& directory)
{ {
return std::filesystem::create_directories(directory); return std::filesystem::create_directories(directory);
} }
bool directory_exists(const std::filesystem::path& directory) bool directory_exists(const std::filesystem::path& directory)
{ {
return std::filesystem::is_directory(directory); return std::filesystem::is_directory(directory);
} }
bool directory_is_empty(const std::filesystem::path& directory) bool directory_is_empty(const std::filesystem::path& directory)
{ {
return std::filesystem::is_empty(directory); return std::filesystem::is_empty(directory);
} }
std::vector<std::string> list_files(const std::filesystem::path& directory) std::vector<std::string> list_files(const std::filesystem::path& directory)
{ {
std::vector<std::string> files; std::vector<std::string> files;
for (auto& file : std::filesystem::directory_iterator(directory)) for (auto& file : std::filesystem::directory_iterator(directory))
{ {
files.push_back(file.path().generic_string()); files.push_back(file.path().generic_string());
} }
return files; return files;
} }
void copy_folder(const std::filesystem::path& src, const std::filesystem::path& target) void copy_folder(const std::filesystem::path& src, const std::filesystem::path& target)
{ {
std::filesystem::copy(src, target, std::filesystem::copy(src, target,
std::filesystem::copy_options::overwrite_existing | std::filesystem::copy_options::overwrite_existing |
std::filesystem::copy_options::recursive); std::filesystem::copy_options::recursive);
} }
} }

View File

@ -1,21 +1,21 @@
#pragma once #pragma once
#include <string> #include <string>
#include <vector> #include <vector>
#include <filesystem> #include <filesystem>
namespace utils::io namespace utils::io
{ {
bool remove_file(const std::filesystem::path& file); bool remove_file(const std::filesystem::path& file);
bool move_file(const std::filesystem::path& src, const std::filesystem::path& target); bool move_file(const std::filesystem::path& src, const std::filesystem::path& target);
bool file_exists(const std::string& file); bool file_exists(const std::string& file);
bool write_file(const std::string& file, const std::string& data, bool append = false); bool write_file(const std::string& file, const std::string& data, bool append = false);
bool read_file(const std::string& file, std::string* data); bool read_file(const std::string& file, std::string* data);
std::string read_file(const std::string& file); std::string read_file(const std::string& file);
size_t file_size(const std::string& file); size_t file_size(const std::string& file);
bool create_directory(const std::filesystem::path& directory); bool create_directory(const std::filesystem::path& directory);
bool directory_exists(const std::filesystem::path& directory); bool directory_exists(const std::filesystem::path& directory);
bool directory_is_empty(const std::filesystem::path& directory); bool directory_is_empty(const std::filesystem::path& directory);
std::vector<std::string> list_files(const std::filesystem::path& directory); std::vector<std::string> list_files(const std::filesystem::path& directory);
void copy_folder(const std::filesystem::path& src, const std::filesystem::path& target); void copy_folder(const std::filesystem::path& src, const std::filesystem::path& target);
} }

View File

@ -1,170 +1,170 @@
#include "memory.hpp" #include "memory.hpp"
#include "nt.hpp" #include "nt.hpp"
namespace utils namespace utils
{ {
memory::allocator memory::mem_allocator_; memory::allocator memory::mem_allocator_;
memory::allocator::~allocator() memory::allocator::~allocator()
{ {
this->clear(); this->clear();
} }
void memory::allocator::clear() void memory::allocator::clear()
{ {
std::lock_guard _(this->mutex_); std::lock_guard _(this->mutex_);
for (auto& data : this->pool_) for (auto& data : this->pool_)
{ {
memory::free(data); memory::free(data);
} }
this->pool_.clear(); this->pool_.clear();
} }
void memory::allocator::free(void* data) void memory::allocator::free(void* data)
{ {
std::lock_guard _(this->mutex_); std::lock_guard _(this->mutex_);
const auto j = std::find(this->pool_.begin(), this->pool_.end(), data); const auto j = std::find(this->pool_.begin(), this->pool_.end(), data);
if (j != this->pool_.end()) if (j != this->pool_.end())
{ {
memory::free(data); memory::free(data);
this->pool_.erase(j); this->pool_.erase(j);
} }
} }
void memory::allocator::free(const void* data) void memory::allocator::free(const void* data)
{ {
this->free(const_cast<void*>(data)); this->free(const_cast<void*>(data));
} }
void* memory::allocator::allocate(const size_t length) void* memory::allocator::allocate(const size_t length)
{ {
std::lock_guard _(this->mutex_); std::lock_guard _(this->mutex_);
const auto data = memory::allocate(length); const auto data = memory::allocate(length);
this->pool_.push_back(data); this->pool_.push_back(data);
return data; return data;
} }
bool memory::allocator::empty() const bool memory::allocator::empty() const
{ {
return this->pool_.empty(); return this->pool_.empty();
} }
char* memory::allocator::duplicate_string(const std::string& string) char* memory::allocator::duplicate_string(const std::string& string)
{ {
std::lock_guard _(this->mutex_); std::lock_guard _(this->mutex_);
const auto data = memory::duplicate_string(string); const auto data = memory::duplicate_string(string);
this->pool_.push_back(data); this->pool_.push_back(data);
return data; return data;
} }
bool memory::allocator::find(const void* data) bool memory::allocator::find(const void* data)
{ {
std::lock_guard _(this->mutex_); std::lock_guard _(this->mutex_);
const auto j = std::find(this->pool_.begin(), this->pool_.end(), data); const auto j = std::find(this->pool_.begin(), this->pool_.end(), data);
return j != this->pool_.end(); return j != this->pool_.end();
} }
void* memory::allocate(const size_t length) void* memory::allocate(const size_t length)
{ {
return std::calloc(length, 1); return std::calloc(length, 1);
} }
char* memory::duplicate_string(const std::string& string) char* memory::duplicate_string(const std::string& string)
{ {
const auto new_string = allocate_array<char>(string.size() + 1); const auto new_string = allocate_array<char>(string.size() + 1);
std::memcpy(new_string, string.data(), string.size()); std::memcpy(new_string, string.data(), string.size());
return new_string; return new_string;
} }
void memory::free(void* data) void memory::free(void* data)
{ {
std::free(data); std::free(data);
} }
void memory::free(const void* data) void memory::free(const void* data)
{ {
free(const_cast<void*>(data)); free(const_cast<void*>(data));
} }
bool memory::is_set(const void* mem, const char chr, const size_t length) bool memory::is_set(const void* mem, const char chr, const size_t length)
{ {
const auto mem_arr = static_cast<const char*>(mem); const auto mem_arr = static_cast<const char*>(mem);
for (size_t i = 0; i < length; ++i) for (size_t i = 0; i < length; ++i)
{ {
if (mem_arr[i] != chr) if (mem_arr[i] != chr)
{ {
return false; return false;
} }
} }
return true; return true;
} }
bool memory::is_bad_read_ptr(const void* ptr) bool memory::is_bad_read_ptr(const void* ptr)
{ {
MEMORY_BASIC_INFORMATION mbi = {}; MEMORY_BASIC_INFORMATION mbi = {};
if (VirtualQuery(ptr, &mbi, sizeof(mbi))) if (VirtualQuery(ptr, &mbi, sizeof(mbi)))
{ {
const DWORD mask = (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | const DWORD mask = (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY); PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY);
auto b = !(mbi.Protect & mask); auto b = !(mbi.Protect & mask);
// check the page is not a guard page // check the page is not a guard page
if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) b = true; if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) b = true;
return b; return b;
} }
return true; return true;
} }
bool memory::is_bad_code_ptr(const void* ptr) bool memory::is_bad_code_ptr(const void* ptr)
{ {
MEMORY_BASIC_INFORMATION mbi = {}; MEMORY_BASIC_INFORMATION mbi = {};
if (VirtualQuery(ptr, &mbi, sizeof(mbi))) if (VirtualQuery(ptr, &mbi, sizeof(mbi)))
{ {
const DWORD mask = (PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY); const DWORD mask = (PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY);
auto b = !(mbi.Protect & mask); auto b = !(mbi.Protect & mask);
// check the page is not a guard page // check the page is not a guard page
if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) b = true; if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) b = true;
return b; return b;
} }
return true; return true;
} }
bool memory::is_rdata_ptr(void* pointer) bool memory::is_rdata_ptr(void* pointer)
{ {
const std::string rdata = ".rdata"; const std::string rdata = ".rdata";
const auto pointer_lib = utils::nt::library::get_by_address(pointer); const auto pointer_lib = utils::nt::library::get_by_address(pointer);
for (const auto& section : pointer_lib.get_section_headers()) for (const auto& section : pointer_lib.get_section_headers())
{ {
const auto size = sizeof(section->Name); const auto size = sizeof(section->Name);
char name[size + 1]; char name[size + 1];
name[size] = 0; name[size] = 0;
std::memcpy(name, section->Name, size); std::memcpy(name, section->Name, size);
if (name == rdata) if (name == rdata)
{ {
const auto target = size_t(pointer); const auto target = size_t(pointer);
const size_t source_start = size_t(pointer_lib.get_ptr()) + section->PointerToRawData; const size_t source_start = size_t(pointer_lib.get_ptr()) + section->PointerToRawData;
const size_t source_end = source_start + section->SizeOfRawData; const size_t source_end = source_start + section->SizeOfRawData;
return target >= source_start && target <= source_end; return target >= source_start && target <= source_end;
} }
} }
return false; return false;
} }
memory::allocator* memory::get_allocator() memory::allocator* memory::get_allocator()
{ {
return &memory::mem_allocator_; return &memory::mem_allocator_;
} }
} }

View File

@ -1,77 +1,77 @@
#pragma once #pragma once
#include <mutex> #include <mutex>
#include <vector> #include <vector>
namespace utils namespace utils
{ {
class memory final class memory final
{ {
public: public:
class allocator final class allocator final
{ {
public: public:
~allocator(); ~allocator();
void clear(); void clear();
void free(void* data); void free(void* data);
void free(const void* data); void free(const void* data);
void* allocate(size_t length); void* allocate(size_t length);
template <typename T> template <typename T>
T* allocate() T* allocate()
{ {
return this->allocate_array<T>(1); return this->allocate_array<T>(1);
} }
template <typename T> template <typename T>
T* allocate_array(const size_t count = 1) T* allocate_array(const size_t count = 1)
{ {
return static_cast<T*>(this->allocate(count * sizeof(T))); return static_cast<T*>(this->allocate(count * sizeof(T)));
} }
bool empty() const; bool empty() const;
char* duplicate_string(const std::string& string); char* duplicate_string(const std::string& string);
bool find(const void* data); bool find(const void* data);
private: private:
std::mutex mutex_; std::mutex mutex_;
std::vector<void*> pool_; std::vector<void*> pool_;
}; };
static void* allocate(size_t length); static void* allocate(size_t length);
template <typename T> template <typename T>
static T* allocate() static T* allocate()
{ {
return allocate_array<T>(1); return allocate_array<T>(1);
} }
template <typename T> template <typename T>
static T* allocate_array(const size_t count = 1) static T* allocate_array(const size_t count = 1)
{ {
return static_cast<T*>(allocate(count * sizeof(T))); return static_cast<T*>(allocate(count * sizeof(T)));
} }
static char* duplicate_string(const std::string& string); static char* duplicate_string(const std::string& string);
static void free(void* data); static void free(void* data);
static void free(const void* data); static void free(const void* data);
static bool is_set(const void* mem, char chr, size_t length); static bool is_set(const void* mem, char chr, size_t length);
static bool is_bad_read_ptr(const void* ptr); static bool is_bad_read_ptr(const void* ptr);
static bool is_bad_code_ptr(const void* ptr); static bool is_bad_code_ptr(const void* ptr);
static bool is_rdata_ptr(void* ptr); static bool is_rdata_ptr(void* ptr);
static allocator* get_allocator(); static allocator* get_allocator();
private: private:
static allocator mem_allocator_; static allocator mem_allocator_;
}; };
} }

View File

@ -1,291 +1,291 @@
#include "nt.hpp" #include "nt.hpp"
namespace utils::nt namespace utils::nt
{ {
library library::load(const char* name) library library::load(const char* name)
{ {
return library(LoadLibraryA(name)); return library(LoadLibraryA(name));
} }
library library::load(const std::string& name) library library::load(const std::string& name)
{ {
return library::load(name.data()); return library::load(name.data());
} }
library library::load(const std::filesystem::path& path) library library::load(const std::filesystem::path& path)
{ {
return library::load(path.generic_string()); return library::load(path.generic_string());
} }
library library::get_by_address(const void* address) library library::get_by_address(const void* address)
{ {
HMODULE handle = nullptr; HMODULE handle = nullptr;
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
static_cast<LPCSTR>(address), &handle); static_cast<LPCSTR>(address), &handle);
return library(handle); return library(handle);
} }
library::library() library::library()
: module_(GetModuleHandleA(nullptr)) : module_(GetModuleHandleA(nullptr))
{ {
} }
library::library(const std::string& name) library::library(const std::string& name)
: module_(GetModuleHandleA(name.data())) : module_(GetModuleHandleA(name.data()))
{ {
} }
library::library(const HMODULE handle) library::library(const HMODULE handle)
: module_(handle) : module_(handle)
{ {
} }
bool library::operator==(const library& obj) const bool library::operator==(const library& obj) const
{ {
return this->module_ == obj.module_; return this->module_ == obj.module_;
} }
library::operator bool() const library::operator bool() const
{ {
return this->is_valid(); return this->is_valid();
} }
library::operator HMODULE() const library::operator HMODULE() const
{ {
return this->get_handle(); return this->get_handle();
} }
PIMAGE_NT_HEADERS library::get_nt_headers() const PIMAGE_NT_HEADERS library::get_nt_headers() const
{ {
if (!this->is_valid()) return nullptr; if (!this->is_valid()) return nullptr;
return reinterpret_cast<PIMAGE_NT_HEADERS>(this->get_ptr() + this->get_dos_header()->e_lfanew); return reinterpret_cast<PIMAGE_NT_HEADERS>(this->get_ptr() + this->get_dos_header()->e_lfanew);
} }
PIMAGE_DOS_HEADER library::get_dos_header() const PIMAGE_DOS_HEADER library::get_dos_header() const
{ {
return reinterpret_cast<PIMAGE_DOS_HEADER>(this->get_ptr()); return reinterpret_cast<PIMAGE_DOS_HEADER>(this->get_ptr());
} }
PIMAGE_OPTIONAL_HEADER library::get_optional_header() const PIMAGE_OPTIONAL_HEADER library::get_optional_header() const
{ {
if (!this->is_valid()) return nullptr; if (!this->is_valid()) return nullptr;
return &this->get_nt_headers()->OptionalHeader; return &this->get_nt_headers()->OptionalHeader;
} }
std::vector<PIMAGE_SECTION_HEADER> library::get_section_headers() const std::vector<PIMAGE_SECTION_HEADER> library::get_section_headers() const
{ {
std::vector<PIMAGE_SECTION_HEADER> headers; std::vector<PIMAGE_SECTION_HEADER> headers;
auto nt_headers = this->get_nt_headers(); auto nt_headers = this->get_nt_headers();
auto section = IMAGE_FIRST_SECTION(nt_headers); auto section = IMAGE_FIRST_SECTION(nt_headers);
for (uint16_t i = 0; i < nt_headers->FileHeader.NumberOfSections; ++i, ++section) for (uint16_t i = 0; i < nt_headers->FileHeader.NumberOfSections; ++i, ++section)
{ {
if (section) headers.push_back(section); if (section) headers.push_back(section);
else OutputDebugStringA("There was an invalid section :O"); else OutputDebugStringA("There was an invalid section :O");
} }
return headers; return headers;
} }
std::uint8_t* library::get_ptr() const std::uint8_t* library::get_ptr() const
{ {
return reinterpret_cast<std::uint8_t*>(this->module_); return reinterpret_cast<std::uint8_t*>(this->module_);
} }
void library::unprotect() const void library::unprotect() const
{ {
if (!this->is_valid()) return; if (!this->is_valid()) return;
DWORD protection; DWORD protection;
VirtualProtect(this->get_ptr(), this->get_optional_header()->SizeOfImage, PAGE_EXECUTE_READWRITE, VirtualProtect(this->get_ptr(), this->get_optional_header()->SizeOfImage, PAGE_EXECUTE_READWRITE,
&protection); &protection);
} }
size_t library::get_relative_entry_point() const size_t library::get_relative_entry_point() const
{ {
if (!this->is_valid()) return 0; if (!this->is_valid()) return 0;
return this->get_nt_headers()->OptionalHeader.AddressOfEntryPoint; return this->get_nt_headers()->OptionalHeader.AddressOfEntryPoint;
} }
void* library::get_entry_point() const void* library::get_entry_point() const
{ {
if (!this->is_valid()) return nullptr; if (!this->is_valid()) return nullptr;
return this->get_ptr() + this->get_relative_entry_point(); return this->get_ptr() + this->get_relative_entry_point();
} }
bool library::is_valid() const bool library::is_valid() const
{ {
return this->module_ != nullptr && this->get_dos_header()->e_magic == IMAGE_DOS_SIGNATURE; return this->module_ != nullptr && this->get_dos_header()->e_magic == IMAGE_DOS_SIGNATURE;
} }
std::string library::get_name() const std::string library::get_name() const
{ {
if (!this->is_valid()) return {}; if (!this->is_valid()) return {};
const auto path = this->get_path(); const auto path = this->get_path();
const auto pos = path.generic_string().find_last_of("/\\"); const auto pos = path.generic_string().find_last_of("/\\");
if (pos == std::string::npos) return path.generic_string(); if (pos == std::string::npos) return path.generic_string();
return path.generic_string().substr(pos + 1); return path.generic_string().substr(pos + 1);
} }
std::filesystem::path library::get_path() const std::filesystem::path library::get_path() const
{ {
if (!this->is_valid()) return {}; if (!this->is_valid()) return {};
wchar_t name[MAX_PATH] = {0}; wchar_t name[MAX_PATH] = {0};
GetModuleFileNameW(this->module_, name, MAX_PATH); GetModuleFileNameW(this->module_, name, MAX_PATH);
return {name}; return {name};
} }
std::filesystem::path library::get_folder() const std::filesystem::path library::get_folder() const
{ {
if (!this->is_valid()) return {}; if (!this->is_valid()) return {};
const auto path = std::filesystem::path(this->get_path()); const auto path = std::filesystem::path(this->get_path());
return path.parent_path().generic_string(); return path.parent_path().generic_string();
} }
void library::free() void library::free()
{ {
if (this->is_valid()) if (this->is_valid())
{ {
FreeLibrary(this->module_); FreeLibrary(this->module_);
this->module_ = nullptr; this->module_ = nullptr;
} }
} }
HMODULE library::get_handle() const HMODULE library::get_handle() const
{ {
return this->module_; return this->module_;
} }
void** library::get_iat_entry(const std::string& module_name, const std::string& proc_name) const void** library::get_iat_entry(const std::string& module_name, const std::string& proc_name) const
{ {
if (!this->is_valid()) return nullptr; if (!this->is_valid()) return nullptr;
const library other_module(module_name); const library other_module(module_name);
if (!other_module.is_valid()) return nullptr; if (!other_module.is_valid()) return nullptr;
auto* const target_function = other_module.get_proc<void*>(proc_name); auto* const target_function = other_module.get_proc<void*>(proc_name);
if (!target_function) return nullptr; if (!target_function) return nullptr;
auto* header = this->get_optional_header(); auto* header = this->get_optional_header();
if (!header) return nullptr; if (!header) return nullptr;
auto* import_descriptor = reinterpret_cast<PIMAGE_IMPORT_DESCRIPTOR>(this->get_ptr() + header->DataDirectory auto* import_descriptor = reinterpret_cast<PIMAGE_IMPORT_DESCRIPTOR>(this->get_ptr() + header->DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); [IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
while (import_descriptor->Name) while (import_descriptor->Name)
{ {
if (!_stricmp(reinterpret_cast<char*>(this->get_ptr() + import_descriptor->Name), module_name.data())) if (!_stricmp(reinterpret_cast<char*>(this->get_ptr() + import_descriptor->Name), module_name.data()))
{ {
auto* original_thunk_data = reinterpret_cast<PIMAGE_THUNK_DATA>(import_descriptor-> auto* original_thunk_data = reinterpret_cast<PIMAGE_THUNK_DATA>(import_descriptor->
OriginalFirstThunk + this->get_ptr()); OriginalFirstThunk + this->get_ptr());
auto* thunk_data = reinterpret_cast<PIMAGE_THUNK_DATA>(import_descriptor->FirstThunk + this-> auto* thunk_data = reinterpret_cast<PIMAGE_THUNK_DATA>(import_descriptor->FirstThunk + this->
get_ptr()); get_ptr());
while (original_thunk_data->u1.AddressOfData) while (original_thunk_data->u1.AddressOfData)
{ {
if (thunk_data->u1.Function == reinterpret_cast<uint64_t>(target_function)) if (thunk_data->u1.Function == reinterpret_cast<uint64_t>(target_function))
{ {
return reinterpret_cast<void**>(&thunk_data->u1.Function); return reinterpret_cast<void**>(&thunk_data->u1.Function);
} }
const size_t ordinal_number = original_thunk_data->u1.AddressOfData & 0xFFFFFFF; const size_t ordinal_number = original_thunk_data->u1.AddressOfData & 0xFFFFFFF;
if (ordinal_number <= 0xFFFF) if (ordinal_number <= 0xFFFF)
{ {
auto* proc = GetProcAddress(other_module.module_, reinterpret_cast<char*>(ordinal_number)); auto* proc = GetProcAddress(other_module.module_, reinterpret_cast<char*>(ordinal_number));
if (reinterpret_cast<void*>(proc) == target_function) if (reinterpret_cast<void*>(proc) == target_function)
{ {
return reinterpret_cast<void**>(&thunk_data->u1.Function); return reinterpret_cast<void**>(&thunk_data->u1.Function);
} }
} }
++original_thunk_data; ++original_thunk_data;
++thunk_data; ++thunk_data;
} }
//break; //break;
} }
++import_descriptor; ++import_descriptor;
} }
return nullptr; return nullptr;
} }
bool is_wine() bool is_wine()
{ {
static const auto has_wine_export = []() -> bool static const auto has_wine_export = []() -> bool
{ {
const library ntdll("ntdll.dll"); const library ntdll("ntdll.dll");
return ntdll.get_proc<void*>("wine_get_version"); return ntdll.get_proc<void*>("wine_get_version");
}(); }();
return has_wine_export; return has_wine_export;
} }
bool is_shutdown_in_progress() bool is_shutdown_in_progress()
{ {
static auto* shutdown_in_progress = [] static auto* shutdown_in_progress = []
{ {
const library ntdll("ntdll.dll"); const library ntdll("ntdll.dll");
return ntdll.get_proc<BOOLEAN(*)()>("RtlDllShutdownInProgress"); return ntdll.get_proc<BOOLEAN(*)()>("RtlDllShutdownInProgress");
}(); }();
return shutdown_in_progress(); return shutdown_in_progress();
} }
void raise_hard_exception() void raise_hard_exception()
{ {
int data = false; int data = false;
const library ntdll("ntdll.dll"); const library ntdll("ntdll.dll");
ntdll.invoke_pascal<void>("RtlAdjustPrivilege", 19, true, false, &data); ntdll.invoke_pascal<void>("RtlAdjustPrivilege", 19, true, false, &data);
ntdll.invoke_pascal<void>("NtRaiseHardError", 0xC000007B, 0, nullptr, nullptr, 6, &data); ntdll.invoke_pascal<void>("NtRaiseHardError", 0xC000007B, 0, nullptr, nullptr, 6, &data);
_Exit(0); _Exit(0);
} }
std::string load_resource(const int id) std::string load_resource(const int id)
{ {
const auto lib = library::get_by_address(load_resource); const auto lib = library::get_by_address(load_resource);
auto* const res = FindResource(lib, MAKEINTRESOURCE(id), RT_RCDATA); auto* const res = FindResource(lib, MAKEINTRESOURCE(id), RT_RCDATA);
if (!res) return {}; if (!res) return {};
auto* const handle = LoadResource(lib, res); auto* const handle = LoadResource(lib, res);
if (!handle) return {}; if (!handle) return {};
return std::string(LPSTR(LockResource(handle)), SizeofResource(lib, res)); return std::string(LPSTR(LockResource(handle)), SizeofResource(lib, res));
} }
void relaunch_self() void relaunch_self()
{ {
const auto self = utils::nt::library::get_by_address(relaunch_self); const auto self = utils::nt::library::get_by_address(relaunch_self);
STARTUPINFOA startup_info; STARTUPINFOA startup_info;
PROCESS_INFORMATION process_info; PROCESS_INFORMATION process_info;
ZeroMemory(&startup_info, sizeof(startup_info)); ZeroMemory(&startup_info, sizeof(startup_info));
ZeroMemory(&process_info, sizeof(process_info)); ZeroMemory(&process_info, sizeof(process_info));
startup_info.cb = sizeof(startup_info); startup_info.cb = sizeof(startup_info);
char current_dir[MAX_PATH]; char current_dir[MAX_PATH];
GetCurrentDirectoryA(sizeof(current_dir), current_dir); GetCurrentDirectoryA(sizeof(current_dir), current_dir);
auto* const command_line = GetCommandLineA(); auto* const command_line = GetCommandLineA();
CreateProcessA(self.get_path().generic_string().data(), command_line, nullptr, nullptr, false, NULL, nullptr, current_dir, CreateProcessA(self.get_path().generic_string().data(), command_line, nullptr, nullptr, false, NULL, nullptr, current_dir,
&startup_info, &process_info); &startup_info, &process_info);
if (process_info.hThread && process_info.hThread != INVALID_HANDLE_VALUE) CloseHandle(process_info.hThread); if (process_info.hThread && process_info.hThread != INVALID_HANDLE_VALUE) CloseHandle(process_info.hThread);
if (process_info.hProcess && process_info.hProcess != INVALID_HANDLE_VALUE) CloseHandle(process_info.hProcess); if (process_info.hProcess && process_info.hProcess != INVALID_HANDLE_VALUE) CloseHandle(process_info.hProcess);
} }
void terminate(const uint32_t code) void terminate(const uint32_t code)
{ {
TerminateProcess(GetCurrentProcess(), code); TerminateProcess(GetCurrentProcess(), code);
_Exit(code); _Exit(code);
} }
} }

View File

@ -1,177 +1,177 @@
#pragma once #pragma once
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include <Windows.h> #include <Windows.h>
// min and max is required by gdi, therefore NOMINMAX won't work // min and max is required by gdi, therefore NOMINMAX won't work
#ifdef max #ifdef max
#undef max #undef max
#endif #endif
#ifdef min #ifdef min
#undef min #undef min
#endif #endif
#include <string> #include <string>
#include <functional> #include <functional>
#include <filesystem> #include <filesystem>
namespace utils::nt namespace utils::nt
{ {
class library final class library final
{ {
public: public:
static library load(const char* name); static library load(const char* name);
static library load(const std::string& name); static library load(const std::string& name);
static library load(const std::filesystem::path& path); static library load(const std::filesystem::path& path);
static library get_by_address(const void* address); static library get_by_address(const void* address);
library(); library();
explicit library(const std::string& name); explicit library(const std::string& name);
explicit library(HMODULE handle); explicit library(HMODULE handle);
library(const library& a) : module_(a.module_) library(const library& a) : module_(a.module_)
{ {
} }
bool operator!=(const library& obj) const { return !(*this == obj); }; bool operator!=(const library& obj) const { return !(*this == obj); };
bool operator==(const library& obj) const; bool operator==(const library& obj) const;
operator bool() const; operator bool() const;
operator HMODULE() const; operator HMODULE() const;
void unprotect() const; void unprotect() const;
[[nodiscard]] void* get_entry_point() const; [[nodiscard]] void* get_entry_point() const;
[[nodiscard]] size_t get_relative_entry_point() const; [[nodiscard]] size_t get_relative_entry_point() const;
[[nodiscard]] bool is_valid() const; [[nodiscard]] bool is_valid() const;
[[nodiscard]] std::string get_name() const; [[nodiscard]] std::string get_name() const;
[[nodiscard]] std::filesystem::path get_path() const; [[nodiscard]] std::filesystem::path get_path() const;
[[nodiscard]] std::filesystem::path get_folder() const; [[nodiscard]] std::filesystem::path get_folder() const;
[[nodiscard]] std::uint8_t* get_ptr() const; [[nodiscard]] std::uint8_t* get_ptr() const;
void free(); void free();
[[nodiscard]] HMODULE get_handle() const; [[nodiscard]] HMODULE get_handle() const;
template <typename T> template <typename T>
[[nodiscard]] T get_proc(const std::string& process) const [[nodiscard]] T get_proc(const std::string& process) const
{ {
if (!this->is_valid()) T{}; if (!this->is_valid()) T{};
return reinterpret_cast<T>(GetProcAddress(this->module_, process.data())); return reinterpret_cast<T>(GetProcAddress(this->module_, process.data()));
} }
template <typename T> template <typename T>
[[nodiscard]] std::function<T> get(const std::string& process) const [[nodiscard]] std::function<T> get(const std::string& process) const
{ {
if (!this->is_valid()) return std::function<T>(); if (!this->is_valid()) return std::function<T>();
return static_cast<T*>(this->get_proc<void*>(process)); return static_cast<T*>(this->get_proc<void*>(process));
} }
template <typename T, typename... Args> template <typename T, typename... Args>
T invoke(const std::string& process, Args ... args) const T invoke(const std::string& process, Args ... args) const
{ {
auto method = this->get<T(__cdecl)(Args ...)>(process); auto method = this->get<T(__cdecl)(Args ...)>(process);
if (method) return method(args...); if (method) return method(args...);
return T(); return T();
} }
template <typename T, typename... Args> template <typename T, typename... Args>
T invoke_pascal(const std::string& process, Args ... args) const T invoke_pascal(const std::string& process, Args ... args) const
{ {
auto method = this->get<T(__stdcall)(Args ...)>(process); auto method = this->get<T(__stdcall)(Args ...)>(process);
if (method) return method(args...); if (method) return method(args...);
return T(); return T();
} }
template <typename T, typename... Args> template <typename T, typename... Args>
T invoke_this(const std::string& process, void* this_ptr, Args ... args) const T invoke_this(const std::string& process, void* this_ptr, Args ... args) const
{ {
auto method = this->get<T(__thiscall)(void*, Args ...)>(this_ptr, process); auto method = this->get<T(__thiscall)(void*, Args ...)>(this_ptr, process);
if (method) return method(args...); if (method) return method(args...);
return T(); return T();
} }
[[nodiscard]] std::vector<PIMAGE_SECTION_HEADER> get_section_headers() const; [[nodiscard]] std::vector<PIMAGE_SECTION_HEADER> get_section_headers() const;
[[nodiscard]] PIMAGE_NT_HEADERS get_nt_headers() const; [[nodiscard]] PIMAGE_NT_HEADERS get_nt_headers() const;
[[nodiscard]] PIMAGE_DOS_HEADER get_dos_header() const; [[nodiscard]] PIMAGE_DOS_HEADER get_dos_header() const;
[[nodiscard]] PIMAGE_OPTIONAL_HEADER get_optional_header() const; [[nodiscard]] PIMAGE_OPTIONAL_HEADER get_optional_header() const;
[[nodiscard]] void** get_iat_entry(const std::string& module_name, const std::string& proc_name) const; [[nodiscard]] void** get_iat_entry(const std::string& module_name, const std::string& proc_name) const;
private: private:
HMODULE module_; HMODULE module_;
}; };
template <HANDLE InvalidHandle = nullptr> template <HANDLE InvalidHandle = nullptr>
class handle class handle
{ {
public: public:
handle() = default; handle() = default;
handle(const HANDLE h) handle(const HANDLE h)
: handle_(h) : handle_(h)
{ {
} }
~handle() ~handle()
{ {
if (*this) if (*this)
{ {
CloseHandle(this->handle_); CloseHandle(this->handle_);
this->handle_ = InvalidHandle; this->handle_ = InvalidHandle;
} }
} }
handle(const handle&) = delete; handle(const handle&) = delete;
handle& operator=(const handle&) = delete; handle& operator=(const handle&) = delete;
handle(handle&& obj) noexcept handle(handle&& obj) noexcept
: handle() : handle()
{ {
this->operator=(std::move(obj)); this->operator=(std::move(obj));
} }
handle& operator=(handle&& obj) noexcept handle& operator=(handle&& obj) noexcept
{ {
if (this != &obj) if (this != &obj)
{ {
this->~handle(); this->~handle();
this->handle_ = obj.handle_; this->handle_ = obj.handle_;
obj.handle_ = InvalidHandle; obj.handle_ = InvalidHandle;
} }
return *this; return *this;
} }
handle& operator=(HANDLE h) noexcept handle& operator=(HANDLE h) noexcept
{ {
this->~handle(); this->~handle();
this->handle_ = h; this->handle_ = h;
return *this; return *this;
} }
operator bool() const operator bool() const
{ {
return this->handle_ != InvalidHandle; return this->handle_ != InvalidHandle;
} }
operator HANDLE() const operator HANDLE() const
{ {
return this->handle_; return this->handle_;
} }
private: private:
HANDLE handle_{InvalidHandle}; HANDLE handle_{InvalidHandle};
}; };
bool is_wine(); bool is_wine();
bool is_shutdown_in_progress(); bool is_shutdown_in_progress();
__declspec(noreturn) void raise_hard_exception(); __declspec(noreturn) void raise_hard_exception();
std::string load_resource(int id); std::string load_resource(int id);
void relaunch_self(); void relaunch_self();
__declspec(noreturn) void terminate(uint32_t code = 0); __declspec(noreturn) void terminate(uint32_t code = 0);
} }

View File

@ -1,220 +1,220 @@
#include "signature.hpp" #include "signature.hpp"
#include <thread> #include <thread>
#include <mutex> #include <mutex>
#include <intrin.h> #include <intrin.h>
#ifdef max #ifdef max
#undef max #undef max
#endif #endif
#ifdef min #ifdef min
#undef min #undef min
#endif #endif
namespace utils::hook namespace utils::hook
{ {
void signature::load_pattern(const std::string& pattern) void signature::load_pattern(const std::string& pattern)
{ {
this->mask_.clear(); this->mask_.clear();
this->pattern_.clear(); this->pattern_.clear();
uint8_t nibble = 0; uint8_t nibble = 0;
auto has_nibble = false; auto has_nibble = false;
for (auto val : pattern) for (auto val : pattern)
{ {
if (val == ' ') continue; if (val == ' ') continue;
if (val == '?') if (val == '?')
{ {
this->mask_.push_back(val); this->mask_.push_back(val);
this->pattern_.push_back(0); this->pattern_.push_back(0);
} }
else else
{ {
if ((val < '0' || val > '9') && (val < 'A' || val > 'F') && (val < 'a' || val > 'f')) if ((val < '0' || val > '9') && (val < 'A' || val > 'F') && (val < 'a' || val > 'f'))
{ {
throw std::runtime_error("Invalid pattern"); throw std::runtime_error("Invalid pattern");
} }
char str[] = {val, 0}; char str[] = {val, 0};
const auto current_nibble = static_cast<uint8_t>(strtol(str, nullptr, 16)); const auto current_nibble = static_cast<uint8_t>(strtol(str, nullptr, 16));
if (!has_nibble) if (!has_nibble)
{ {
has_nibble = true; has_nibble = true;
nibble = current_nibble; nibble = current_nibble;
} }
else else
{ {
has_nibble = false; has_nibble = false;
const uint8_t byte = current_nibble | (nibble << 4); const uint8_t byte = current_nibble | (nibble << 4);
this->mask_.push_back('x'); this->mask_.push_back('x');
this->pattern_.push_back(byte); this->pattern_.push_back(byte);
} }
} }
} }
while (!this->mask_.empty() && this->mask_.back() == '?') while (!this->mask_.empty() && this->mask_.back() == '?')
{ {
this->mask_.pop_back(); this->mask_.pop_back();
this->pattern_.pop_back(); this->pattern_.pop_back();
} }
if (this->has_sse_support()) if (this->has_sse_support())
{ {
while (this->pattern_.size() < 16) while (this->pattern_.size() < 16)
{ {
this->pattern_.push_back(0); this->pattern_.push_back(0);
} }
} }
if (has_nibble) if (has_nibble)
{ {
throw std::runtime_error("Invalid pattern"); throw std::runtime_error("Invalid pattern");
} }
} }
signature::signature_result signature::process_range(uint8_t* start, const size_t length) const signature::signature_result signature::process_range(uint8_t* start, const size_t length) const
{ {
if (this->has_sse_support()) return this->process_range_vectorized(start, length); if (this->has_sse_support()) return this->process_range_vectorized(start, length);
return this->process_range_linear(start, length); return this->process_range_linear(start, length);
} }
signature::signature_result signature::process_range_linear(uint8_t* start, const size_t length) const signature::signature_result signature::process_range_linear(uint8_t* start, const size_t length) const
{ {
std::vector<uint8_t*> result; std::vector<uint8_t*> result;
for (size_t i = 0; i < length; ++i) for (size_t i = 0; i < length; ++i)
{ {
const auto address = start + i; const auto address = start + i;
size_t j = 0; size_t j = 0;
for (; j < this->mask_.size(); ++j) for (; j < this->mask_.size(); ++j)
{ {
if (this->mask_[j] != '?' && this->pattern_[j] != address[j]) if (this->mask_[j] != '?' && this->pattern_[j] != address[j])
{ {
break; break;
} }
} }
if (j == this->mask_.size()) if (j == this->mask_.size())
{ {
result.push_back(address); result.push_back(address);
} }
} }
return result; return result;
} }
signature::signature_result signature::process_range_vectorized(uint8_t* start, const size_t length) const signature::signature_result signature::process_range_vectorized(uint8_t* start, const size_t length) const
{ {
std::vector<uint8_t*> result; std::vector<uint8_t*> result;
__declspec(align(16)) char desired_mask[16] = {0}; __declspec(align(16)) char desired_mask[16] = {0};
for (size_t i = 0; i < this->mask_.size(); i++) for (size_t i = 0; i < this->mask_.size(); i++)
{ {
desired_mask[i / 8] |= (this->mask_[i] == '?' ? 0 : 1) << i % 8; desired_mask[i / 8] |= (this->mask_[i] == '?' ? 0 : 1) << i % 8;
} }
const auto mask = _mm_load_si128(reinterpret_cast<const __m128i*>(desired_mask)); const auto mask = _mm_load_si128(reinterpret_cast<const __m128i*>(desired_mask));
const auto comparand = _mm_loadu_si128(reinterpret_cast<const __m128i*>(this->pattern_.data())); const auto comparand = _mm_loadu_si128(reinterpret_cast<const __m128i*>(this->pattern_.data()));
for (size_t i = 0; i < length; ++i) for (size_t i = 0; i < length; ++i)
{ {
const auto address = start + i; const auto address = start + i;
const auto value = _mm_loadu_si128(reinterpret_cast<const __m128i*>(address)); const auto value = _mm_loadu_si128(reinterpret_cast<const __m128i*>(address));
const auto comparison = _mm_cmpestrm(value, 16, comparand, static_cast<int>(this->mask_.size()), const auto comparison = _mm_cmpestrm(value, 16, comparand, static_cast<int>(this->mask_.size()),
_SIDD_CMP_EQUAL_EACH); _SIDD_CMP_EQUAL_EACH);
const auto matches = _mm_and_si128(mask, comparison); const auto matches = _mm_and_si128(mask, comparison);
const auto equivalence = _mm_xor_si128(mask, matches); const auto equivalence = _mm_xor_si128(mask, matches);
if (_mm_test_all_zeros(equivalence, equivalence)) if (_mm_test_all_zeros(equivalence, equivalence))
{ {
result.push_back(address); result.push_back(address);
} }
} }
return result; return result;
} }
signature::signature_result signature::process() const signature::signature_result signature::process() const
{ {
const auto range = this->length_ - this->mask_.size(); const auto range = this->length_ - this->mask_.size();
const auto cores = std::max(1u, std::thread::hardware_concurrency()); const auto cores = std::max(1u, std::thread::hardware_concurrency());
if (range <= cores * 10ull) return this->process_serial(); if (range <= cores * 10ull) return this->process_serial();
return this->process_parallel(); return this->process_parallel();
} }
signature::signature_result signature::process_serial() const signature::signature_result signature::process_serial() const
{ {
const auto sub = this->has_sse_support() ? 16 : this->mask_.size(); const auto sub = this->has_sse_support() ? 16 : this->mask_.size();
return {this->process_range(this->start_, this->length_ - sub)}; return {this->process_range(this->start_, this->length_ - sub)};
} }
signature::signature_result signature::process_parallel() const signature::signature_result signature::process_parallel() const
{ {
const auto sub = this->has_sse_support() ? 16 : this->mask_.size(); const auto sub = this->has_sse_support() ? 16 : this->mask_.size();
const auto range = this->length_ - sub; const auto range = this->length_ - sub;
const auto cores = std::max(1u, std::thread::hardware_concurrency() / 2); const auto cores = std::max(1u, std::thread::hardware_concurrency() / 2);
// Only use half of the available cores // Only use half of the available cores
const auto grid = range / cores; const auto grid = range / cores;
std::mutex mutex; std::mutex mutex;
std::vector<uint8_t*> result; std::vector<uint8_t*> result;
std::vector<std::thread> threads; std::vector<std::thread> threads;
for (auto i = 0u; i < cores; ++i) for (auto i = 0u; i < cores; ++i)
{ {
const auto start = this->start_ + (grid * i); const auto start = this->start_ + (grid * i);
const auto length = (i + 1 == cores) ? (this->start_ + this->length_ - sub) - start : grid; const auto length = (i + 1 == cores) ? (this->start_ + this->length_ - sub) - start : grid;
threads.emplace_back([&, start, length]() threads.emplace_back([&, start, length]()
{ {
const auto local_result = this->process_range(start, length); const auto local_result = this->process_range(start, length);
if (local_result.empty()) return; if (local_result.empty()) return;
std::lock_guard _(mutex); std::lock_guard _(mutex);
for (const auto& address : local_result) for (const auto& address : local_result)
{ {
result.push_back(address); result.push_back(address);
} }
}); });
} }
for (auto& t : threads) for (auto& t : threads)
{ {
if (t.joinable()) if (t.joinable())
{ {
t.join(); t.join();
} }
} }
std::sort(result.begin(), result.end()); std::sort(result.begin(), result.end());
return {std::move(result)}; return {std::move(result)};
} }
bool signature::has_sse_support() const bool signature::has_sse_support() const
{ {
if (this->mask_.size() <= 16) if (this->mask_.size() <= 16)
{ {
int cpu_id[4]; int cpu_id[4];
__cpuid(cpu_id, 0); __cpuid(cpu_id, 0);
if (cpu_id[0] >= 1) if (cpu_id[0] >= 1)
{ {
__cpuidex(cpu_id, 1, 0); __cpuidex(cpu_id, 1, 0);
return (cpu_id[2] & (1 << 20)) != 0; return (cpu_id[2] & (1 << 20)) != 0;
} }
} }
return false; return false;
} }
} }
utils::hook::signature::signature_result operator"" _sig(const char* str, const size_t len) utils::hook::signature::signature_result operator"" _sig(const char* str, const size_t len)
{ {
return utils::hook::signature(std::string(str, len)).process(); return utils::hook::signature(std::string(str, len)).process();
} }

View File

@ -1,49 +1,49 @@
#pragma once #pragma once
#include "nt.hpp" #include "nt.hpp"
#include <cstdint> #include <cstdint>
namespace utils::hook namespace utils::hook
{ {
class signature final class signature final
{ {
public: public:
using signature_result = std::vector<uint8_t*>; using signature_result = std::vector<uint8_t*>;
explicit signature(const std::string& pattern, const nt::library& library = {}) explicit signature(const std::string& pattern, const nt::library& library = {})
: signature(pattern, library.get_ptr(), library.get_optional_header()->SizeOfImage) : signature(pattern, library.get_ptr(), library.get_optional_header()->SizeOfImage)
{ {
} }
signature(const std::string& pattern, void* start, void* end) signature(const std::string& pattern, void* start, void* end)
: signature(pattern, start, size_t(end) - size_t(start)) : signature(pattern, start, size_t(end) - size_t(start))
{ {
} }
signature(const std::string& pattern, void* start, const size_t length) signature(const std::string& pattern, void* start, const size_t length)
: start_(static_cast<uint8_t*>(start)), length_(length) : start_(static_cast<uint8_t*>(start)), length_(length)
{ {
this->load_pattern(pattern); this->load_pattern(pattern);
} }
signature_result process() const; signature_result process() const;
private: private:
std::string mask_; std::string mask_;
std::basic_string<uint8_t> pattern_; std::basic_string<uint8_t> pattern_;
uint8_t* start_; uint8_t* start_;
size_t length_; size_t length_;
void load_pattern(const std::string& pattern); void load_pattern(const std::string& pattern);
signature_result process_parallel() const; signature_result process_parallel() const;
signature_result process_serial() const; signature_result process_serial() const;
signature_result process_range(uint8_t* start, size_t length) const; signature_result process_range(uint8_t* start, size_t length) const;
signature_result process_range_linear(uint8_t* start, size_t length) const; signature_result process_range_linear(uint8_t* start, size_t length) const;
signature_result process_range_vectorized(uint8_t* start, size_t length) const; signature_result process_range_vectorized(uint8_t* start, size_t length) const;
bool has_sse_support() const; bool has_sse_support() const;
}; };
} }
utils::hook::signature::signature_result operator"" _sig(const char* str, size_t len); utils::hook::signature::signature_result operator"" _sig(const char* str, size_t len);

View File

@ -1,94 +1,94 @@
#include "smbios.hpp" #include "smbios.hpp"
#include "memory.hpp" #include "memory.hpp"
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include <Windows.h> #include <Windows.h>
#include <intrin.h> #include <intrin.h>
namespace utils::smbios namespace utils::smbios
{ {
namespace namespace
{ {
#pragma warning(push) #pragma warning(push)
#pragma warning(disable: 4200) #pragma warning(disable: 4200)
struct RawSMBIOSData struct RawSMBIOSData
{ {
BYTE Used20CallingMethod; BYTE Used20CallingMethod;
BYTE SMBIOSMajorVersion; BYTE SMBIOSMajorVersion;
BYTE SMBIOSMinorVersion; BYTE SMBIOSMinorVersion;
BYTE DmiRevision; BYTE DmiRevision;
DWORD Length; DWORD Length;
BYTE SMBIOSTableData[]; BYTE SMBIOSTableData[];
}; };
typedef struct typedef struct
{ {
BYTE type; BYTE type;
BYTE length; BYTE length;
WORD handle; WORD handle;
} dmi_header; } dmi_header;
#pragma warning(pop) #pragma warning(pop)
std::vector<uint8_t> get_smbios_data() std::vector<uint8_t> get_smbios_data()
{ {
DWORD size = 0; DWORD size = 0;
std::vector<uint8_t> data{}; std::vector<uint8_t> data{};
size = GetSystemFirmwareTable('RSMB', 0, nullptr, size); size = GetSystemFirmwareTable('RSMB', 0, nullptr, size);
data.resize(size); data.resize(size);
GetSystemFirmwareTable('RSMB', 0, data.data(), size); GetSystemFirmwareTable('RSMB', 0, data.data(), size);
return data; return data;
} }
std::string parse_uuid(const uint8_t* data) std::string parse_uuid(const uint8_t* data)
{ {
if (utils::memory::is_set(data, 0, 16) || utils::memory::is_set(data, -1, 16)) if (utils::memory::is_set(data, 0, 16) || utils::memory::is_set(data, -1, 16))
{ {
return {}; return {};
} }
char uuid[16] = {0}; char uuid[16] = {0};
*reinterpret_cast<unsigned long*>(uuid + 0) = *reinterpret_cast<unsigned long*>(uuid + 0) =
_byteswap_ulong(*reinterpret_cast<const unsigned long*>(data + 0)); _byteswap_ulong(*reinterpret_cast<const unsigned long*>(data + 0));
*reinterpret_cast<unsigned short*>(uuid + 4) = *reinterpret_cast<unsigned short*>(uuid + 4) =
_byteswap_ushort(*reinterpret_cast<const unsigned short*>(data + 4)); _byteswap_ushort(*reinterpret_cast<const unsigned short*>(data + 4));
*reinterpret_cast<unsigned short*>(uuid + 6) = *reinterpret_cast<unsigned short*>(uuid + 6) =
_byteswap_ushort(*reinterpret_cast<const unsigned short*>(data + 6)); _byteswap_ushort(*reinterpret_cast<const unsigned short*>(data + 6));
memcpy(uuid + 8, data + 8, 8); memcpy(uuid + 8, data + 8, 8);
return std::string(uuid, sizeof(uuid)); return std::string(uuid, sizeof(uuid));
} }
} }
std::string get_uuid() std::string get_uuid()
{ {
auto smbios_data = get_smbios_data(); auto smbios_data = get_smbios_data();
auto* raw_data = reinterpret_cast<RawSMBIOSData*>(smbios_data.data()); auto* raw_data = reinterpret_cast<RawSMBIOSData*>(smbios_data.data());
auto* data = raw_data->SMBIOSTableData; auto* data = raw_data->SMBIOSTableData;
for (DWORD i = 0; i + sizeof(dmi_header) < raw_data->Length;) for (DWORD i = 0; i + sizeof(dmi_header) < raw_data->Length;)
{ {
auto* header = reinterpret_cast<dmi_header*>(data + i); auto* header = reinterpret_cast<dmi_header*>(data + i);
if (header->length < 4) if (header->length < 4)
{ {
return {}; return {};
} }
if (header->type == 0x01 && header->length >= 0x19) if (header->type == 0x01 && header->length >= 0x19)
{ {
return parse_uuid(data + i + 0x8); return parse_uuid(data + i + 0x8);
} }
i += header->length; i += header->length;
while ((i + 1) < raw_data->Length && *reinterpret_cast<uint16_t*>(data + i) != 0) while ((i + 1) < raw_data->Length && *reinterpret_cast<uint16_t*>(data + i) != 0)
{ {
++i; ++i;
} }
i += 2; i += 2;
} }
return {}; return {};
} }
} }

View File

@ -1,8 +1,8 @@
#pragma once #pragma once
#include <string> #include <string>
namespace utils::smbios namespace utils::smbios
{ {
std::string get_uuid(); std::string get_uuid();
} }

View File

@ -1,177 +1,177 @@
#include "string.hpp" #include "string.hpp"
#include <sstream> #include <sstream>
#include <cstdarg> #include <cstdarg>
#include <algorithm> #include <algorithm>
#include "nt.hpp" #include "nt.hpp"
namespace utils::string namespace utils::string
{ {
const char* va(const char* fmt, ...) const char* va(const char* fmt, ...)
{ {
static thread_local va_provider<8, 256> provider; static thread_local va_provider<8, 256> provider;
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);
const char* result = provider.get(fmt, ap); const char* result = provider.get(fmt, ap);
va_end(ap); va_end(ap);
return result; return result;
} }
std::vector<std::string> split(const std::string& s, const char delim) std::vector<std::string> split(const std::string& s, const char delim)
{ {
std::stringstream ss(s); std::stringstream ss(s);
std::string item; std::string item;
std::vector<std::string> elems; std::vector<std::string> elems;
while (std::getline(ss, item, delim)) while (std::getline(ss, item, delim))
{ {
elems.push_back(item); // elems.push_back(std::move(item)); // if C++11 (based on comment from @mchiasson) elems.push_back(item); // elems.push_back(std::move(item)); // if C++11 (based on comment from @mchiasson)
} }
return elems; return elems;
} }
std::string to_lower(std::string text) std::string to_lower(std::string text)
{ {
std::transform(text.begin(), text.end(), text.begin(), [](const unsigned char input) std::transform(text.begin(), text.end(), text.begin(), [](const unsigned char input)
{ {
return static_cast<char>(std::tolower(input)); return static_cast<char>(std::tolower(input));
}); });
return text; return text;
} }
std::string to_upper(std::string text) std::string to_upper(std::string text)
{ {
std::transform(text.begin(), text.end(), text.begin(), [](const unsigned char input) std::transform(text.begin(), text.end(), text.begin(), [](const unsigned char input)
{ {
return static_cast<char>(std::toupper(input)); return static_cast<char>(std::toupper(input));
}); });
return text; return text;
} }
bool starts_with(const std::string& text, const std::string& substring) bool starts_with(const std::string& text, const std::string& substring)
{ {
return text.find(substring) == 0; return text.find(substring) == 0;
} }
bool ends_with(const std::string& text, const std::string& substring) bool ends_with(const std::string& text, const std::string& substring)
{ {
if (substring.size() > text.size()) return false; if (substring.size() > text.size()) return false;
return std::equal(substring.rbegin(), substring.rend(), text.rbegin()); return std::equal(substring.rbegin(), substring.rend(), text.rbegin());
} }
std::string dump_hex(const std::string& data, const std::string& separator) std::string dump_hex(const std::string& data, const std::string& separator)
{ {
std::string result; std::string result;
for (unsigned int i = 0; i < data.size(); ++i) for (unsigned int i = 0; i < data.size(); ++i)
{ {
if (i > 0) if (i > 0)
{ {
result.append(separator); result.append(separator);
} }
result.append(va("%02X", data[i] & 0xFF)); result.append(va("%02X", data[i] & 0xFF));
} }
return result; return result;
} }
std::string get_clipboard_data() std::string get_clipboard_data()
{ {
if (OpenClipboard(nullptr)) if (OpenClipboard(nullptr))
{ {
std::string data; std::string data;
auto* const clipboard_data = GetClipboardData(1u); auto* const clipboard_data = GetClipboardData(1u);
if (clipboard_data) if (clipboard_data)
{ {
auto* const cliptext = static_cast<char*>(GlobalLock(clipboard_data)); auto* const cliptext = static_cast<char*>(GlobalLock(clipboard_data));
if (cliptext) if (cliptext)
{ {
data.append(cliptext); data.append(cliptext);
GlobalUnlock(clipboard_data); GlobalUnlock(clipboard_data);
} }
} }
CloseClipboard(); CloseClipboard();
return data; return data;
} }
return {}; return {};
} }
void strip(const char* in, char* out, size_t max) void strip(const char* in, char* out, size_t max)
{ {
if (!in || !out) return; if (!in || !out) return;
max--; max--;
size_t current = 0; size_t current = 0;
while (*in != 0 && current < max) while (*in != 0 && current < max)
{ {
const auto color_index = (*(in + 1) - 48) >= 0xC ? 7 : (*(in + 1) - 48); const auto color_index = (*(in + 1) - 48) >= 0xC ? 7 : (*(in + 1) - 48);
if (*in == '^' && (color_index != 7 || *(in + 1) == '7')) if (*in == '^' && (color_index != 7 || *(in + 1) == '7'))
{ {
++in; ++in;
} }
else else
{ {
*out = *in; *out = *in;
++out; ++out;
++current; ++current;
} }
++in; ++in;
} }
*out = '\0'; *out = '\0';
} }
std::string convert(const std::wstring& wstr) std::string convert(const std::wstring& wstr)
{ {
std::string result; std::string result;
result.reserve(wstr.size()); result.reserve(wstr.size());
for (const auto& chr : wstr) for (const auto& chr : wstr)
{ {
result.push_back(static_cast<char>(chr)); result.push_back(static_cast<char>(chr));
} }
return result; return result;
} }
std::wstring convert(const std::string& str) std::wstring convert(const std::string& str)
{ {
std::wstring result; std::wstring result;
result.reserve(str.size()); result.reserve(str.size());
for (const auto& chr : str) for (const auto& chr : str)
{ {
result.push_back(static_cast<wchar_t>(chr)); result.push_back(static_cast<wchar_t>(chr));
} }
return result; return result;
} }
std::string replace(std::string str, const std::string& from, const std::string& to) std::string replace(std::string str, const std::string& from, const std::string& to)
{ {
if (from.empty()) if (from.empty())
{ {
return str; return str;
} }
size_t start_pos = 0; size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) while ((start_pos = str.find(from, start_pos)) != std::string::npos)
{ {
str.replace(start_pos, from.length(), to); str.replace(start_pos, from.length(), to);
start_pos += to.length(); start_pos += to.length();
} }
return str; return str;
} }
} }

View File

@ -1,97 +1,97 @@
#pragma once #pragma once
#include "memory.hpp" #include "memory.hpp"
template <class Type, size_t n> template <class Type, size_t n>
constexpr auto ARRAY_COUNT(Type (&)[n]) { return n; } constexpr auto ARRAY_COUNT(Type (&)[n]) { return n; }
namespace utils::string namespace utils::string
{ {
template <size_t Buffers, size_t MinBufferSize> template <size_t Buffers, size_t MinBufferSize>
class va_provider final class va_provider final
{ {
public: public:
static_assert(Buffers != 0 && MinBufferSize != 0, "Buffers and MinBufferSize mustn't be 0"); static_assert(Buffers != 0 && MinBufferSize != 0, "Buffers and MinBufferSize mustn't be 0");
va_provider() : current_buffer_(0) va_provider() : current_buffer_(0)
{ {
} }
char* get(const char* format, const va_list ap) char* get(const char* format, const va_list ap)
{ {
++this->current_buffer_ %= ARRAY_COUNT(this->string_pool_); ++this->current_buffer_ %= ARRAY_COUNT(this->string_pool_);
auto entry = &this->string_pool_[this->current_buffer_]; auto entry = &this->string_pool_[this->current_buffer_];
if (!entry->size || !entry->buffer) if (!entry->size || !entry->buffer)
{ {
throw std::runtime_error("String pool not initialized"); throw std::runtime_error("String pool not initialized");
} }
while (true) while (true)
{ {
const int res = vsnprintf_s(entry->buffer, entry->size, _TRUNCATE, format, ap); const int res = vsnprintf_s(entry->buffer, entry->size, _TRUNCATE, format, ap);
if (res > 0) break; // Success if (res > 0) break; // Success
if (res == 0) return nullptr; // Error if (res == 0) return nullptr; // Error
entry->double_size(); entry->double_size();
} }
return entry->buffer; return entry->buffer;
} }
private: private:
class entry final class entry final
{ {
public: public:
entry(const size_t _size = MinBufferSize) : size(_size), buffer(nullptr) entry(const size_t _size = MinBufferSize) : size(_size), buffer(nullptr)
{ {
if (this->size < MinBufferSize) this->size = MinBufferSize; if (this->size < MinBufferSize) this->size = MinBufferSize;
this->allocate(); this->allocate();
} }
~entry() ~entry()
{ {
if (this->buffer) memory::get_allocator()->free(this->buffer); if (this->buffer) memory::get_allocator()->free(this->buffer);
this->size = 0; this->size = 0;
this->buffer = nullptr; this->buffer = nullptr;
} }
void allocate() void allocate()
{ {
if (this->buffer) memory::get_allocator()->free(this->buffer); if (this->buffer) memory::get_allocator()->free(this->buffer);
this->buffer = memory::get_allocator()->allocate_array<char>(this->size + 1); this->buffer = memory::get_allocator()->allocate_array<char>(this->size + 1);
} }
void double_size() void double_size()
{ {
this->size *= 2; this->size *= 2;
this->allocate(); this->allocate();
} }
size_t size{}; size_t size{};
char* buffer{nullptr}; char* buffer{nullptr};
}; };
size_t current_buffer_{}; size_t current_buffer_{};
entry string_pool_[Buffers]{}; entry string_pool_[Buffers]{};
}; };
const char* va(const char* fmt, ...); const char* va(const char* fmt, ...);
std::vector<std::string> split(const std::string& s, char delim); std::vector<std::string> split(const std::string& s, char delim);
std::string to_lower(std::string text); std::string to_lower(std::string text);
std::string to_upper(std::string text); std::string to_upper(std::string text);
bool starts_with(const std::string& text, const std::string& substring); bool starts_with(const std::string& text, const std::string& substring);
bool ends_with(const std::string& text, const std::string& substring); bool ends_with(const std::string& text, const std::string& substring);
std::string dump_hex(const std::string& data, const std::string& separator = " "); std::string dump_hex(const std::string& data, const std::string& separator = " ");
std::string get_clipboard_data(); std::string get_clipboard_data();
void strip(const char* in, char* out, size_t max); void strip(const char* in, char* out, size_t max);
std::string convert(const std::wstring& wstr); std::string convert(const std::wstring& wstr);
std::wstring convert(const std::string& str); std::wstring convert(const std::string& str);
std::string replace(std::string str, const std::string& from, const std::string& to); std::string replace(std::string str, const std::string& from, const std::string& to);
} }

View File

@ -1,116 +1,116 @@
#include "thread.hpp" #include "thread.hpp"
#include "string.hpp" #include "string.hpp"
#include "finally.hpp" #include "finally.hpp"
#include <TlHelp32.h> #include <TlHelp32.h>
namespace utils::thread namespace utils::thread
{ {
/*bool set_name(const HANDLE t, const std::string& name) /*bool set_name(const HANDLE t, const std::string& name)
{ {
const nt::library kernel32("kernel32.dll"); const nt::library kernel32("kernel32.dll");
if (!kernel32) if (!kernel32)
{ {
return false; return false;
} }
const auto set_description = kernel32.get_proc<HRESULT(WINAPI*)(HANDLE, PCWSTR)>("SetThreadDescription"); const auto set_description = kernel32.get_proc<HRESULT(WINAPI*)(HANDLE, PCWSTR)>("SetThreadDescription");
if (!set_description) if (!set_description)
{ {
return false; return false;
} }
return SUCCEEDED(set_description(t, string::convert(name).data())); return SUCCEEDED(set_description(t, string::convert(name).data()));
} }
bool set_name(const DWORD id, const std::string& name) bool set_name(const DWORD id, const std::string& name)
{ {
auto* const t = OpenThread(THREAD_SET_LIMITED_INFORMATION, FALSE, id); auto* const t = OpenThread(THREAD_SET_LIMITED_INFORMATION, FALSE, id);
if (!t) return false; if (!t) return false;
const auto _ = utils::finally([t]() const auto _ = utils::finally([t]()
{ {
CloseHandle(t); CloseHandle(t);
}); });
return set_name(t, name); return set_name(t, name);
} }
bool set_name(std::thread& t, const std::string& name) bool set_name(std::thread& t, const std::string& name)
{ {
return set_name(t.native_handle(), name); return set_name(t.native_handle(), name);
} }
bool set_name(const std::string& name) bool set_name(const std::string& name)
{ {
return set_name(GetCurrentThread(), name); return set_name(GetCurrentThread(), name);
} }
*/ */
std::vector<DWORD> get_thread_ids() std::vector<DWORD> get_thread_ids()
{ {
nt::handle<INVALID_HANDLE_VALUE> h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, GetCurrentProcessId()); nt::handle<INVALID_HANDLE_VALUE> h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, GetCurrentProcessId());
if (!h) if (!h)
{ {
return {}; return {};
} }
THREADENTRY32 entry{}; THREADENTRY32 entry{};
entry.dwSize = sizeof(entry); entry.dwSize = sizeof(entry);
if (!Thread32First(h, &entry)) if (!Thread32First(h, &entry))
{ {
return {}; return {};
} }
std::vector<DWORD> ids{}; std::vector<DWORD> ids{};
do do
{ {
const auto check_size = entry.dwSize < FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) const auto check_size = entry.dwSize < FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID)
+ sizeof(entry.th32OwnerProcessID); + sizeof(entry.th32OwnerProcessID);
entry.dwSize = sizeof(entry); entry.dwSize = sizeof(entry);
if (check_size && entry.th32OwnerProcessID == GetCurrentProcessId()) if (check_size && entry.th32OwnerProcessID == GetCurrentProcessId())
{ {
ids.emplace_back(entry.th32ThreadID); ids.emplace_back(entry.th32ThreadID);
} }
} while (Thread32Next(h, &entry)); } while (Thread32Next(h, &entry));
return ids; return ids;
} }
void for_each_thread(const std::function<void(HANDLE)>& callback, const DWORD access) void for_each_thread(const std::function<void(HANDLE)>& callback, const DWORD access)
{ {
const auto ids = get_thread_ids(); const auto ids = get_thread_ids();
for (const auto& id : ids) for (const auto& id : ids)
{ {
handle thread(id, access); handle thread(id, access);
if (thread) if (thread)
{ {
callback(thread); callback(thread);
} }
} }
} }
void suspend_other_threads() void suspend_other_threads()
{ {
for_each_thread([](const HANDLE thread) for_each_thread([](const HANDLE thread)
{ {
if (GetThreadId(thread) != GetCurrentThreadId()) if (GetThreadId(thread) != GetCurrentThreadId())
{ {
SuspendThread(thread); SuspendThread(thread);
} }
}); });
} }
void resume_other_threads() void resume_other_threads()
{ {
for_each_thread([](const HANDLE thread) for_each_thread([](const HANDLE thread)
{ {
if (GetThreadId(thread) != GetCurrentThreadId()) if (GetThreadId(thread) != GetCurrentThreadId())
{ {
ResumeThread(thread); ResumeThread(thread);
} }
}); });
} }
} }

View File

@ -1,47 +1,47 @@
#pragma once #pragma once
#include <thread> #include <thread>
#include "nt.hpp" #include "nt.hpp"
namespace utils::thread namespace utils::thread
{ {
//bool set_name(HANDLE t, const std::string& name); //bool set_name(HANDLE t, const std::string& name);
//bool set_name(DWORD id, const std::string& name); //bool set_name(DWORD id, const std::string& name);
//bool set_name(std::thread& t, const std::string& name); //bool set_name(std::thread& t, const std::string& name);
//bool set_name(const std::string& name); //bool set_name(const std::string& name);
template <typename ...Args> template <typename ...Args>
std::thread create_named_thread(const std::string& name, Args&&... args) std::thread create_named_thread(const std::string& name, Args&&... args)
{ {
auto t = std::thread(std::forward<Args>(args)...); auto t = std::thread(std::forward<Args>(args)...);
set_name(t, name); set_name(t, name);
return t; return t;
} }
class handle class handle
{ {
public: public:
handle(const DWORD thread_id, const DWORD access = THREAD_ALL_ACCESS) handle(const DWORD thread_id, const DWORD access = THREAD_ALL_ACCESS)
: handle_(OpenThread(access, FALSE, thread_id)) : handle_(OpenThread(access, FALSE, thread_id))
{ {
} }
operator bool() const operator bool() const
{ {
return this->handle_; return this->handle_;
} }
operator HANDLE() const operator HANDLE() const
{ {
return this->handle_; return this->handle_;
} }
private: private:
nt::handle<> handle_{}; nt::handle<> handle_{};
}; };
std::vector<DWORD> get_thread_ids(); std::vector<DWORD> get_thread_ids();
void for_each_thread(const std::function<void(HANDLE)>& callback, DWORD access = THREAD_ALL_ACCESS); void for_each_thread(const std::function<void(HANDLE)>& callback, DWORD access = THREAD_ALL_ACCESS);
void suspend_other_threads(); void suspend_other_threads();
void resume_other_threads(); void resume_other_threads();
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,379 +1,406 @@
#include "functions.hpp" #include "functions.hpp"
void* RtlAddVectoredExceptionHandler(LONG First, PVECTORED_EXCEPTION_HANDLER Handler) { void* RtlAddVectoredExceptionHandler(LONG First, PVECTORED_EXCEPTION_HANDLER Handler) {
utils::nt::library ntdll("ntdll.dll"); utils::nt::library ntdll("ntdll.dll");
ntdll.invoke<void*>("RtlAddVectoredExceptionHandler", First, Handler); ntdll.invoke<void*>("RtlAddVectoredExceptionHandler", First, Handler);
return nullptr; return nullptr;
} }
NTSTATUS NtContinue(PCONTEXT threadContext, BOOLEAN raiseAlert) { NTSTATUS NtContinue(PCONTEXT threadContext, BOOLEAN raiseAlert) {
utils::nt::library ntdll("ntdll.dll"); utils::nt::library ntdll("ntdll.dll");
return ntdll.invoke<NTSTATUS>("NtContinue", threadContext, raiseAlert); return ntdll.invoke<NTSTATUS>("NtContinue", threadContext, raiseAlert);
} }
#pragma region //game functions #pragma region //game functions
const char* (*va)(const char* fmt, ...); const char* (*va)(const char* fmt, ...);
void Live_FakeUserSignIn(int controllerIndex, const char* gamertag) { void Live_FakeUserSignIn(int controllerIndex, const char* gamertag) {
auto func = reinterpret_cast<void(*)(int, const char*)>(0x1413FDA40_g); auto func = reinterpret_cast<void(*)(int, const char*)>(0x1413FDA40_g);
func(controllerIndex, gamertag); func(controllerIndex, gamertag);
} }
void R_AddCmdDrawText(const char* text, int maxChars, void /* GfxFont */* font, int fontHeight, float x, float y, float xScale, float yScale, float rotation, const float* color, const void /* FontGlowStyle */* glowStyle, bool usePost) { void R_AddCmdDrawText(const char* text, int maxChars, void /* GfxFont */* font, int fontHeight, float x, float y, float xScale, float yScale, float rotation, const float* color, const void /* FontGlowStyle */* glowStyle, bool usePost) {
auto func = reinterpret_cast<void(*)(const char* text, int maxChars, void /* GfxFont */* font, int fontHeight, float x, float y, float xScale, float yScale, float rotation, const float* color, const void /* FontGlowStyle */* glowStyle, bool usePost)>(0x00000001419653E0_g); auto func = reinterpret_cast<void(*)(const char* text, int maxChars, void /* GfxFont */* font, int fontHeight, float x, float y, float xScale, float yScale, float rotation, const float* color, const void /* FontGlowStyle */* glowStyle, bool usePost)>(0x00000001419653E0_g);
func(text, maxChars, font, fontHeight, x, y, xScale, yScale, rotation, color, glowStyle, usePost); func(text, maxChars, font, fontHeight, x, y, xScale, yScale, rotation, color, glowStyle, usePost);
} }
bool CG_WorldPosToScreenPosReal(int localClientNum, const uintptr_t scrPlace, const float* worldPos, float* outScreenPos) { bool CG_WorldPosToScreenPosReal(int localClientNum, const uintptr_t scrPlace, const float* worldPos, float* outScreenPos) {
auto func = reinterpret_cast<bool(*)(int, const uintptr_t, const float*, float*)>(0x141696AA0_g); auto func = reinterpret_cast<bool(*)(int, const uintptr_t, const float*, float*)>(0x141696AA0_g);
return func(localClientNum, scrPlace, worldPos, outScreenPos); return func(localClientNum, scrPlace, worldPos, outScreenPos);
} }
void CG_DrawRotatedPicPhysical(uintptr_t scrPlace, float x, float y, float width, float height, float angle, const float* color, uintptr_t material) { void CG_DrawRotatedPicPhysical(uintptr_t scrPlace, float x, float y, float width, float height, float angle, const float* color, uintptr_t material) {
auto func = reinterpret_cast<void(*)(uintptr_t scrPlace, float x, float y, float width, float height, float angle, const float* color, uintptr_t material)>(0x141695B20_g); auto func = reinterpret_cast<void(*)(uintptr_t scrPlace, float x, float y, float width, float height, float angle, const float* color, uintptr_t material)>(0x141695B20_g);
func(scrPlace, x, y, width, height, angle, color, material); func(scrPlace, x, y, width, height, angle, color, material);
} }
uintptr_t FS_ReadFile(const char* qpath, const char** buffer) { uintptr_t FS_ReadFile(const char* qpath, const char** buffer) {
auto func = reinterpret_cast<uintptr_t(*)(const char* qpath, const char** buffer)>(0x1413DA530_g); auto func = reinterpret_cast<uintptr_t(*)(const char* qpath, const char** buffer)>(0x1413DA530_g);
return func(qpath, buffer); return func(qpath, buffer);
} }
const char* Dvar_GetStringSafe(const char* dvar) { const char* Dvar_GetStringSafe(const char* dvar) {
auto func = reinterpret_cast<const char* (*)(const char*)>(0x1413E69B0_g); auto func = reinterpret_cast<const char* (*)(const char*)>(0x1413E69B0_g);
return func(dvar); return func(dvar);
} }
unsigned int* GetRandSeed() { bool Dvar_GetBoolSafe(const char* dvar)
auto func = reinterpret_cast<unsigned int* (*)()>(0x1413DD630_g); {
return func(); auto func = reinterpret_cast<bool(*)(const char*)>(0x1413E6820_g);
} return func(dvar);
}
unsigned __int64 Sys_Microseconds() {
auto func = reinterpret_cast<unsigned __int64(*)()>(0x14148FC10_g); int Dvar_GetIntSafe(const char* dvar)
return func(); {
} auto func = reinterpret_cast<int(*)(const char* path)>(0x1413E6960_g);
return func(dvar);
int I_irand(int min, int max) { }
auto func = reinterpret_cast<int(*)(int, int)>(0x1413DD8B0_g);
return func(min, max); unsigned int* GetRandSeed() {
} auto func = reinterpret_cast<unsigned int* (*)()>(0x1413DD630_g);
return func();
unsigned __int64 I_atoui64_hex(const char* str) { }
auto func = reinterpret_cast<unsigned __int64(*)(const char*)>(0x1413F3310_g);
return func(str); unsigned __int64 Sys_Microseconds() {
} auto func = reinterpret_cast<unsigned __int64(*)()>(0x14148FC10_g);
return func();
unsigned __int64 I_atoui64(const char* str) { }
auto func = reinterpret_cast<unsigned __int64(*)(const char*)>(0x1413F3300_g);
return func(str); int I_irand(int min, int max) {
} auto func = reinterpret_cast<int(*)(int, int)>(0x1413DD8B0_g);
return func(min, max);
uintptr_t Dvar_FindVarByName(const char* dvarName) { }
auto func = reinterpret_cast<uintptr_t(*)(const char*)>(0x1413E63A0_g);
return func(dvarName); unsigned __int64 I_atoui64_hex(const char* str) {
} auto func = reinterpret_cast<unsigned __int64(*)(const char*)>(0x1413F3310_g);
return func(str);
void CL_DrawText(const uintptr_t scrPlace, const char* text, int maxChars, uintptr_t font, float x, float y, int horzAlign, int vertAlign, float xScale, float yScale, const float* color, int style) { }
auto func = reinterpret_cast<void(*)(const uintptr_t scrPlace, const char* text, int maxChars, uintptr_t font, float x, float y, int horzAlign, int vertAlign, float xScale, float yScale, const float* color, int style)>(0x1415AAAA0_g);
func(scrPlace, text, maxChars, font, x, y, horzAlign, vertAlign, xScale, yScale, color, style); unsigned __int64 I_atoui64(const char* str) {
} auto func = reinterpret_cast<unsigned __int64(*)(const char*)>(0x1413F3300_g);
return func(str);
dvar_t* Dvar_RegisterString(const char* dvarName, const char* value, unsigned int flags, const char* description) { }
auto func = reinterpret_cast<dvar_t * (*)(const char* dvarName, const char* value, unsigned int flags, const char* description)>(0x1413E7A70_g);
return func(dvarName, value, flags, description); uintptr_t Dvar_FindVarByName(const char* dvarName) {
} auto func = reinterpret_cast<uintptr_t(*)(const char*)>(0x1413E63A0_g);
return func(dvarName);
dvar_t* Dvar_RegisterBool(const char* dvarName, bool value, unsigned int flags, const char* description) { }
auto func = reinterpret_cast<dvar_t * (*)(const char* dvarName, bool value, unsigned int flags, const char* description)>(0x1413E7670_g);
return func(dvarName, value, flags, description); void CL_DrawText(const uintptr_t scrPlace, const char* text, int maxChars, uintptr_t font, float x, float y, int horzAlign, int vertAlign, float xScale, float yScale, const float* color, int style) {
} auto func = reinterpret_cast<void(*)(const uintptr_t scrPlace, const char* text, int maxChars, uintptr_t font, float x, float y, int horzAlign, int vertAlign, float xScale, float yScale, const float* color, int style)>(0x1415AAAA0_g);
func(scrPlace, text, maxChars, font, x, y, horzAlign, vertAlign, xScale, yScale, color, style);
void LUI_CoD_LuaCall_ExecNow(uintptr_t luaVM, const char* str) { }
lua_getfield(luaVM, -10002, "Engine");
lua_getfield(luaVM, -1, "DAGFFDGFII"); dvar_t* Dvar_RegisterString(const char* dvarName, const char* value, unsigned int flags, const char* description) {
lua_remove(luaVM, -2); auto func = reinterpret_cast<dvar_t * (*)(const char* dvarName, const char* value, unsigned int flags, const char* description)>(0x1413E7A70_g);
lua_pushstring(luaVM, str); return func(dvarName, value, flags, description);
LuaShared_PCall(luaVM, 1, 1); }
}
dvar_t* Dvar_RegisterBool(const char* dvarName, bool value, unsigned int flags, const char* description) {
bool LUI_LuaCall_Game_IsEntityAlive(uintptr_t luaVM, int entityNum) { auto func = reinterpret_cast<dvar_t * (*)(const char* dvarName, bool value, unsigned int flags, const char* description)>(0x1413E7670_g);
lua_getfield(luaVM, -10002, "Game"); return func(dvarName, value, flags, description);
lua_getfield(luaVM, -1, "JDAIJCDEB"); }
lua_remove(luaVM, -2);
lua_pushinteger(luaVM, 0); void LUI_CoD_LuaCall_ExecNow(uintptr_t luaVM, const char* str) {
lua_pushinteger(luaVM, entityNum); lua_getfield(luaVM, -10002, "Engine");
LuaShared_PCall(luaVM, 2, 1); lua_getfield(luaVM, -1, "DAGFFDGFII");
return lua_toboolean(luaVM, 0); lua_remove(luaVM, -2);
} lua_pushstring(luaVM, str);
LuaShared_PCall(luaVM, 1, 1);
void Cbuf_AddText(const char* cmd) { }
uintptr_t luaVM = *reinterpret_cast<uintptr_t*>(0x151868880_g);
if (luaVM) { bool LUI_LuaCall_Game_IsEntityAlive(uintptr_t luaVM, int entityNum) {
LUI_CoD_LuaCall_ExecNow(luaVM, cmd); lua_getfield(luaVM, -10002, "Game");
} lua_getfield(luaVM, -1, "JDAIJCDEB");
} lua_remove(luaVM, -2);
lua_pushinteger(luaVM, 0);
bool lua_toboolean(uintptr_t L, int idx) { lua_pushinteger(luaVM, entityNum);
auto func = reinterpret_cast<bool(*)(uintptr_t, int)>(0x1420848D0_g); LuaShared_PCall(luaVM, 2, 1);
return func(L, idx); return lua_toboolean(luaVM, 0);
} }
void lua_pushboolean(uintptr_t L, int b) { void Cbuf_AddText(const char* cmd) {
auto func = reinterpret_cast<void(*)(uintptr_t, int)>(0x142083E80_g); uintptr_t luaVM = *reinterpret_cast<uintptr_t*>(0x151868880_g);
func(L, b); if (luaVM) {
} LUI_CoD_LuaCall_ExecNow(luaVM, cmd);
}
void lua_remove(uintptr_t L, int idx) { }
auto func = reinterpret_cast<void(*)(uintptr_t, int)>(0x142084420_g);
func(L, idx); bool lua_toboolean(uintptr_t L, int idx) {
} auto func = reinterpret_cast<bool(*)(uintptr_t, int)>(0x1420848D0_g);
return func(L, idx);
void lua_call(uintptr_t L, int nargs, int nresults) { }
auto func = reinterpret_cast<void(*)(uintptr_t, int, int)>(0x1420831D0_g);
func(L, nargs, nresults); void lua_pushboolean(uintptr_t L, int b) {
} auto func = reinterpret_cast<void(*)(uintptr_t, int)>(0x142083E80_g);
func(L, b);
void lua_getfield(uintptr_t L, int idx, const char* k) { }
auto func = reinterpret_cast<void(*)(uintptr_t, int, const char*)>(0x1420836E0_g);
func(L, idx, k); void lua_remove(uintptr_t L, int idx) {
} auto func = reinterpret_cast<void(*)(uintptr_t, int)>(0x142084420_g);
func(L, idx);
void lua_pushvalue(uintptr_t L, int idx) { }
auto func = reinterpret_cast<void(*)(uintptr_t, int)>(0x142084200_g);
func(L, idx); void lua_call(uintptr_t L, int nargs, int nresults) {
} auto func = reinterpret_cast<void(*)(uintptr_t, int, int)>(0x1420831D0_g);
func(L, nargs, nresults);
void lua_pushstring(uintptr_t L, const char* str) { }
auto func = reinterpret_cast<void(*)(uintptr_t, const char*)>(0x142084120_g);
func(L, str); void lua_getfield(uintptr_t L, int idx, const char* k) {
} auto func = reinterpret_cast<void(*)(uintptr_t, int, const char*)>(0x1420836E0_g);
func(L, idx, k);
void lua_pushinteger(uintptr_t L, int n) { }
auto func = reinterpret_cast<void(*)(uintptr_t, int)>(0x142083FE0_g);
func(L, n); void lua_pushvalue(uintptr_t L, int idx) {
} auto func = reinterpret_cast<void(*)(uintptr_t, int)>(0x142084200_g);
func(L, idx);
void lua_settop(uintptr_t L, int idx) { }
auto func = reinterpret_cast<void(*)(uintptr_t, int)>(0x142084790_g);
func(L, idx); void lua_pushstring(uintptr_t L, const char* str) {
} auto func = reinterpret_cast<void(*)(uintptr_t, const char*)>(0x142084120_g);
func(L, str);
int LuaShared_PCall(uintptr_t luaVM, int nargs, int nresults) { }
auto func = reinterpret_cast<int(*)(uintptr_t, int, int)>(0x1419B7570_g);
return func(luaVM, nargs, nresults); void lua_pushinteger(uintptr_t L, int n) {
} auto func = reinterpret_cast<void(*)(uintptr_t, int)>(0x142083FE0_g);
func(L, n);
bool CG_DObjGetWorldBoneMatrix(uintptr_t pose, uintptr_t obj, int boneIndex, uintptr_t outTagMat, float* outOrigin) { }
auto func = reinterpret_cast<bool(*)(uintptr_t pose, uintptr_t obj, int boneIndex, uintptr_t outTagMat, float* outOrigin)>(0x1416A59D0_g);
return func(pose, obj, boneIndex, outTagMat, outOrigin); void lua_settop(uintptr_t L, int idx) {
} auto func = reinterpret_cast<void(*)(uintptr_t, int)>(0x142084790_g);
func(L, idx);
void CG_DrawLine(float X1, float Y1, float X2, float Y2, const float* color, float Width) { }
float X, Y, Angle, L1, L2, H1;
H1 = Y2 - Y1; int LuaShared_PCall(uintptr_t luaVM, int nargs, int nresults) {
L1 = X2 - X1; auto func = reinterpret_cast<int(*)(uintptr_t, int, int)>(0x1419B7570_g);
L2 = sqrtf(L1 * L1 + H1 * H1); return func(luaVM, nargs, nresults);
X = X1 + ((L1 - L2) / 2); }
Y = Y1 + (H1 / 2);
Angle = atan(H1 / L1) * (180 / 3.14159265358979323846); bool CG_DObjGetWorldBoneMatrix(uintptr_t pose, uintptr_t obj, int boneIndex, uintptr_t outTagMat, float* outOrigin) {
CG_DrawRotatedPicPhysical(0x14EF2DEA0_g, X, Y, L2, Width, Angle, color, *reinterpret_cast<uintptr_t*>(0x152C465A0_g)); auto func = reinterpret_cast<bool(*)(uintptr_t pose, uintptr_t obj, int boneIndex, uintptr_t outTagMat, float* outOrigin)>(0x1416A59D0_g);
} return func(pose, obj, boneIndex, outTagMat, outOrigin);
}
void CG_DrawBone(int entIndex, uintptr_t ent, int from, int to, const float* color) {
float bone1[3], bone2[3]; void CG_DrawLine(float X1, float Y1, float X2, float Y2, const float* color, float Width) {
float fromPos[2], toPos[2]; float X, Y, Angle, L1, L2, H1;
char tmat33[0x24]; H1 = Y2 - Y1;
short* clientObjMap = (short*)(0x14D45EC60_g); L1 = X2 - X1;
uintptr_t s_objBuf = *reinterpret_cast<uintptr_t*>(0x14D45EC50_g); L2 = sqrtf(L1 * L1 + H1 * H1);
uintptr_t dobj = s_objBuf + (0x150 * clientObjMap[entIndex]); X = X1 + ((L1 - L2) / 2);
if (CG_DObjGetWorldBoneMatrix(ent, dobj, from, (uintptr_t)&tmat33, bone1) && CG_DObjGetWorldBoneMatrix(ent, dobj, to, (uintptr_t)&tmat33, bone2)) { Y = Y1 + (H1 / 2);
if (CG_WorldPosToScreenPosReal(0, 0x14EF2DEA0_g, bone1, fromPos) && CG_WorldPosToScreenPosReal(0, 0x14EF2DEA0_g, bone2, toPos)) { Angle = atan(H1 / L1) * (180 / 3.14159265358979323846);
CG_DrawLine(fromPos[0], fromPos[1], toPos[0], toPos[1], color, 1); CG_DrawRotatedPicPhysical(0x14EF2DEA0_g, X, Y, L2, Width, Angle, color, *reinterpret_cast<uintptr_t*>(0x152C465A0_g));
} }
}
} void CG_DrawBone(int entIndex, uintptr_t ent, int from, int to, const float* color) {
float bone1[3], bone2[3];
void CG_DrawBones(int entIndex, uintptr_t ent, const float* color) { float fromPos[2], toPos[2];
//spine char tmat33[0x24];
CG_DrawBone(entIndex, ent, 41, 35, color); short* clientObjMap = (short*)(0x14D45EC60_g);
CG_DrawBone(entIndex, ent, 35, 7, color); uintptr_t s_objBuf = *reinterpret_cast<uintptr_t*>(0x14D45EC50_g);
CG_DrawBone(entIndex, ent, 7, 6, color); uintptr_t dobj = s_objBuf + (0x150 * clientObjMap[entIndex]);
CG_DrawBone(entIndex, ent, 6, 30, color); if (CG_DObjGetWorldBoneMatrix(ent, dobj, from, (uintptr_t)&tmat33, bone1) && CG_DObjGetWorldBoneMatrix(ent, dobj, to, (uintptr_t)&tmat33, bone2)) {
CG_DrawBone(entIndex, ent, 30, 55, color); if (CG_WorldPosToScreenPosReal(0, 0x14EF2DEA0_g, bone1, fromPos) && CG_WorldPosToScreenPosReal(0, 0x14EF2DEA0_g, bone2, toPos)) {
CG_DrawBone(entIndex, ent, 55, 54, color); CG_DrawLine(fromPos[0], fromPos[1], toPos[0], toPos[1], color, 1);
CG_DrawBone(entIndex, ent, 54, 53, color); }
CG_DrawBone(entIndex, ent, 53, 2, color); }
}
//hips
CG_DrawBone(entIndex, ent, 2, 63, color); void CG_DrawBones(int entIndex, uintptr_t ent, const float* color) {
CG_DrawBone(entIndex, ent, 2, 64, color); //spine
} CG_DrawBone(entIndex, ent, 41, 35, color);
CG_DrawBone(entIndex, ent, 35, 7, color);
bool CheatsOk(int entNum) { CG_DrawBone(entIndex, ent, 7, 6, color);
SvClient* ms_clients = *reinterpret_cast<SvClient**>(0x14E17F690_g + (8 * entNum)); CG_DrawBone(entIndex, ent, 6, 30, color);
uintptr_t client = g_entities[entNum].get<uintptr_t>(0x150); CG_DrawBone(entIndex, ent, 30, 55, color);
if (sv_cheats->current.enabled) { CG_DrawBone(entIndex, ent, 55, 54, color);
return true; CG_DrawBone(entIndex, ent, 54, 53, color);
} CG_DrawBone(entIndex, ent, 53, 2, color);
else {
ms_clients->SendServerCommand(1, "f \"Cheats are not enabled on this server!\""); //hips
return false; CG_DrawBone(entIndex, ent, 2, 63, color);
} CG_DrawBone(entIndex, ent, 2, 64, color);
} }
//ingame removed functions bool CheatsOk(int entNum) {
void Cmd_Noclip_f(int entNum) SvClient* ms_clients = *reinterpret_cast<SvClient**>(0x14E17F690_g + (8 * entNum));
{ uintptr_t client = g_entities[entNum].get<uintptr_t>(0x150);
SvClient* ms_clients = *reinterpret_cast<SvClient**>(0x14E17F690_g + (8 * entNum)); if (sv_cheats->current.enabled) {
uintptr_t client = g_entities[entNum].get<uintptr_t>(0x150); return true;
if (client) { }
int v6 = *reinterpret_cast<int*>(client + 0x5DD0); else {
if ((*reinterpret_cast<int*>(client + 0x5DD0) & 1) != 0) { ms_clients->SendServerCommand(1, "f \"Cheats are not enabled on this server!\"");
v6 = *reinterpret_cast<int*>(client + 0x5DD0) & 0xFFFFFFFE; return false;
ms_clients->SendServerCommand(1, "f \"Noclip: ^1OFF\""); }
} }
else {
v6 = *reinterpret_cast<int*>(client + 0x5DD0) | 1; //ingame removed functions
ms_clients->SendServerCommand(1, "f \"Noclip: ^2ON\""); void Cmd_Noclip_f(int entNum)
} {
*reinterpret_cast<int*>(client + 0x5DD0) = v6; SvClient* ms_clients = *reinterpret_cast<SvClient**>(0x14E17F690_g + (8 * entNum));
} uintptr_t client = g_entities[entNum].get<uintptr_t>(0x150);
} if (client) {
int v6 = *reinterpret_cast<int*>(client + 0x5DD0);
void SV_Cmd_ArgvBuffer(int arg, char* buffer, unsigned __int64 bufferLength) { if ((*reinterpret_cast<int*>(client + 0x5DD0) & 1) != 0) {
auto func = reinterpret_cast<void(*)(int, char*, unsigned __int64)>(0x141298B40_g); v6 = *reinterpret_cast<int*>(client + 0x5DD0) & 0xFFFFFFFE;
func(arg, buffer, bufferLength); ms_clients->SendServerCommand(1, "f \"Noclip: ^1OFF\"");
} }
else {
void Cmd_ArgvBuffer(int arg, char* buffer, int bufferLength) { v6 = *reinterpret_cast<int*>(client + 0x5DD0) | 1;
if (arg >= cmd_args->argc[cmd_args->nesting]) ms_clients->SendServerCommand(1, "f \"Noclip: ^2ON\"");
strcpy_s(buffer, bufferLength, ""); }
else *reinterpret_cast<int*>(client + 0x5DD0) = v6;
strcpy_s(buffer, bufferLength, cmd_args->argv[cmd_args->nesting][arg]); }
} }
int Cmd_Argc() { void Cmd_God_f(int entNum)
return cmd_args->argc[cmd_args->nesting]; {
} SvClient* ms_clients = *reinterpret_cast<SvClient**>(0x14E17F690_g + (8 * entNum));
gentity_s ent = g_entities[entNum];
int SV_Cmd_Argc() { }
auto func = reinterpret_cast<int(*)()>(0x141298AF0_g);
return func(); void SV_Cmd_ArgvBuffer(int arg, char* buffer, unsigned __int64 bufferLength) {
} auto func = reinterpret_cast<void(*)(int, char*, unsigned __int64)>(0x141298B40_g);
func(arg, buffer, bufferLength);
void Cmd_AddCommandInternal(const char* cmdName, void(__fastcall* function)(), cmd_function_s* allocedCmd) { }
auto func = reinterpret_cast<void(*)(const char*, void(__fastcall*)(), cmd_function_s*)>(0x1412965F0_g);
func(cmdName, function, allocedCmd); void Cmd_ArgvBuffer(int arg, char* buffer, int bufferLength) {
} if (arg >= cmd_args->argc[cmd_args->nesting])
strcpy_s(buffer, bufferLength, "");
ClActiveClient* GetClActiveClient() { else
ms_activeClients = *reinterpret_cast<ClActiveClient**>(0x14EE854F8_g); strcpy_s(buffer, bufferLength, cmd_args->argv[cmd_args->nesting][arg]);
return ms_activeClients; }
}
int Cmd_Argc() {
int ClActiveClient_GetCmdNumber(ClActiveClient* activeClient) { return cmd_args->argc[cmd_args->nesting];
return activeClient->cmdNumber ^ ((activeClient->get<int>(0x8700) ^ (activeClient->cmdNumber) * ((activeClient->get<int>(0x8700) ^ activeClient->cmdNumber) + 2))); }
}
int SV_Cmd_Argc() {
usercmd_s* CL_GetUserCmd(int cmdNumber) { auto func = reinterpret_cast<int(*)()>(0x141298AF0_g);
ms_activeClients = *reinterpret_cast<ClActiveClient**>(0x14EE854F8_g); return func();
return &ms_activeClients->cmds[cmdNumber & 0x7F]; }
}
void Cmd_AddCommandInternal(const char* cmdName, void(__fastcall* function)(), cmd_function_s* allocedCmd) {
void AddReliableCommand(uintptr_t _this, const char* commandBuffer, const int reliableCmdSize, int type) { auto func = reinterpret_cast<void(*)(const char*, void(__fastcall*)(), cmd_function_s*)>(0x1412965F0_g);
auto func = reinterpret_cast<void(*)(uintptr_t, const char*, const int, int)>(0x1415E0440_g); func(cmdName, function, allocedCmd);
func(_this, commandBuffer, reliableCmdSize, type); }
}
ClActiveClient* GetClActiveClient() {
unsigned int MSG_WriteReliableCommandToBuffer(const char* pszCommand, char* pszBuffer, unsigned int iBufferSize) { ms_activeClients = *reinterpret_cast<ClActiveClient**>(0x14EE854F8_g);
auto func = reinterpret_cast<unsigned int(*)(const char*, char*, unsigned int)>(0x1412DDBF0_g); return ms_activeClients;
return func(pszCommand, pszBuffer, iBufferSize); }
}
int ClActiveClient_GetCmdNumber(ClActiveClient* activeClient) {
void CL_Main_AddReliableCommand(const char* cmd) { return activeClient->cmdNumber ^ ((activeClient->get<int>(0x8700) ^ (activeClient->cmdNumber) * ((activeClient->get<int>(0x8700) ^ activeClient->cmdNumber) + 2)));
uintptr_t ms_connections = *reinterpret_cast<uintptr_t*>(0x14EE85570_g); }
char buf[1024];
int cmdSize = MSG_WriteReliableCommandToBuffer(cmd, buf, 1024); usercmd_s* CL_GetUserCmd(int cmdNumber) {
AddReliableCommand(ms_connections, buf, cmdSize, 0); ms_activeClients = *reinterpret_cast<ClActiveClient**>(0x14EE854F8_g);
} return &ms_activeClients->cmds[cmdNumber & 0x7F];
}
bool BG_Weapons_GetFullWeaponForName(const char* name, Weapon* outWeapon, Weapon* (*getWeaponFunc)(Weapon* result, const char*)) {
auto func = reinterpret_cast<bool(*)(const char*, Weapon*, Weapon * (*)(Weapon * result, const char*))>(0x141158130_g); void AddReliableCommand(uintptr_t _this, const char* commandBuffer, const int reliableCmdSize, int type) {
return func(name, outWeapon, getWeaponFunc); auto func = reinterpret_cast<void(*)(uintptr_t, const char*, const int, int)>(0x1415E0440_g);
} func(_this, commandBuffer, reliableCmdSize, type);
}
void Scr_AddString(scrContext_t* scrContext, const char* value) {
auto func = reinterpret_cast<void(*)(scrContext_t*, const char*)>(0x141322D90_g); unsigned int MSG_WriteReliableCommandToBuffer(const char* pszCommand, char* pszBuffer, unsigned int iBufferSize) {
func(scrContext, value); auto func = reinterpret_cast<unsigned int(*)(const char*, char*, unsigned int)>(0x1412DDBF0_g);
} return func(pszCommand, pszBuffer, iBufferSize);
}
unsigned int GScr_ExecEntThread(gentity_s* ent, int handle, unsigned int paramcount) {
auto func = reinterpret_cast<unsigned int(*)(gentity_s*, int, unsigned int)>(0x141257D70_g); void CL_Main_AddReliableCommand(const char* cmd) {
return func(ent, handle, paramcount); uintptr_t ms_connections = *reinterpret_cast<uintptr_t*>(0x14EE85570_g);
} char buf[1024];
int cmdSize = MSG_WriteReliableCommandToBuffer(cmd, buf, 1024);
void Scr_FreeThread(scrContext_t* scrContext, unsigned int handle) { AddReliableCommand(ms_connections, buf, cmdSize, 0);
auto func = reinterpret_cast<void(*)(scrContext_t*, unsigned int)>(0x1413242E0_g); }
func(scrContext, handle);
} bool BG_Weapons_GetFullWeaponForName(const char* name, Weapon* outWeapon, Weapon* (*getWeaponFunc)(Weapon* result, const char*)) {
auto func = reinterpret_cast<bool(*)(const char*, Weapon*, Weapon * (*)(Weapon * result, const char*))>(0x141158130_g);
int G_Weapon_GivePlayerWeapon(uintptr_t ps, uintptr_t scrContext, Weapon* weapon, int dualWield, int startInAltMode, int usedBefore) { return func(name, outWeapon, getWeaponFunc);
auto func = reinterpret_cast<int(*)(uintptr_t, uintptr_t, Weapon*, int, int, int)>(0x14127C8B0_g); }
return func(ps, scrContext, weapon, dualWield, startInAltMode, usedBefore);
} void Scr_AddString(scrContext_t* scrContext, const char* value) {
auto func = reinterpret_cast<void(*)(scrContext_t*, const char*)>(0x141322D90_g);
void G_Items_AddAmmo(uintptr_t ps, Weapon* weapon, bool isAlternate, int count, int fillClip) { func(scrContext, value);
auto func = reinterpret_cast<void(*)(uintptr_t, Weapon*, bool, int, int)>(0x141216860_g); }
func(ps, weapon, isAlternate, count, fillClip);
} unsigned int GScr_ExecEntThread(gentity_s* ent, int handle, unsigned int paramcount) {
auto func = reinterpret_cast<unsigned int(*)(gentity_s*, int, unsigned int)>(0x141257D70_g);
void G_Weapon_SelectWeapon(int clientNum, Weapon* weapon) { return func(ent, handle, paramcount);
auto func = reinterpret_cast<void(*)(int, Weapon*)>(0x14127F840_g); }
}
void Scr_FreeThread(scrContext_t* scrContext, unsigned int handle) {
Weapon* BG_FindBaseWeaponForName(Weapon* result, const char* name) { auto func = reinterpret_cast<void(*)(scrContext_t*, unsigned int)>(0x1413242E0_g);
auto func = reinterpret_cast<Weapon * (*)(Weapon*, const char*)>(0x1411570F0_g); func(scrContext, handle);
return func(result, name); }
}
int G_Weapon_GivePlayerWeapon(uintptr_t ps, uintptr_t scrContext, Weapon* weapon, int dualWield, int startInAltMode, int usedBefore) {
scrContext_t* ScriptContext_Server() { auto func = reinterpret_cast<int(*)(uintptr_t, uintptr_t, Weapon*, int, int, int)>(0x14127C8B0_g);
auto func = reinterpret_cast<scrContext_t * (*)()>(0x1412E0E70_g); return func(ps, scrContext, weapon, dualWield, startInAltMode, usedBefore);
return func(); }
}
void G_Items_AddAmmo(uintptr_t ps, Weapon* weapon, bool isAlternate, int count, int fillClip) {
const char* SL_ConvertToString(int id) { auto func = reinterpret_cast<void(*)(uintptr_t, Weapon*, bool, int, int)>(0x141216860_g);
auto func = reinterpret_cast<const char* (*)(int)>(0x14131AA20_g); func(ps, weapon, isAlternate, count, fillClip);
return func(id); }
}
void G_Weapon_SelectWeapon(int clientNum, Weapon* weapon) {
XAssetHeader DB_FindXAssetHeader(XAssetType type, const char* givenName, int allowCreateDefault) { auto func = reinterpret_cast<void(*)(int, Weapon*)>(0x14127F840_g);
auto func = reinterpret_cast<XAssetHeader(*)(XAssetType, const char*, int)>(0x1411AA890_g); }
return func(type, givenName, allowCreateDefault);
} Weapon* BG_FindBaseWeaponForName(Weapon* result, const char* name) {
auto func = reinterpret_cast<Weapon * (*)(Weapon*, const char*)>(0x1411570F0_g);
#pragma endregion return func(result, name);
}
dvar_t* player_name;
dvar_t* sv_cheats; scrContext_t* ScriptContext_Server() {
dvar_t* spawn_br_gas; auto func = reinterpret_cast<scrContext_t * (*)()>(0x1412E0E70_g);
dvar_t* show_watermark; return func();
dvar_t* player_sustainammo; }
cmd_function_s set_byte_f_VAR; const char* SL_ConvertToString(int id) {
cmd_function_s set_short_f_VAR; auto func = reinterpret_cast<const char* (*)(int)>(0x14131AA20_g);
cmd_function_s set_int_f_VAR; return func(id);
cmd_function_s set_pointer_f_VAR; }
cmd_function_s quit_f_VAR;
cmd_function_s openmenu_f_VAR; XAssetHeader DB_FindXAssetHeader(XAssetType type, const char* givenName, int allowCreateDefault) {
cmd_function_s addbot_f_VAR; auto func = reinterpret_cast<XAssetHeader(*)(XAssetType, const char*, int)>(0x1411AA890_g);
cmd_function_s ddldump_f_VAR; return func(type, givenName, allowCreateDefault);
cmd_function_s weapondefdump_f_VAR; }
cmd_function_s view_vehicle_ents_f_VAR;
cmd_function_s loadout_save_f_VAR; void Com_SetErrorMessage(const char* errorMessage) {
cmd_function_s FastRestart_f_VAR; auto func = reinterpret_cast<void(*)(const char*)>(0x1412B3710_g);
return func(errorMessage);
CmdArgs* cmd_args; }
#pragma endregion
dvar_t* player_name;
dvar_t* sv_cheats;
dvar_t* spawn_br_gas;
dvar_t* show_watermark;
dvar_t* player_sustainammo;
cmd_function_s set_byte_f_VAR;
cmd_function_s set_short_f_VAR;
cmd_function_s set_int_f_VAR;
cmd_function_s set_float_f_VAR;
cmd_function_s set_pointer_f_VAR;
cmd_function_s quit_f_VAR;
cmd_function_s openmenu_f_VAR;
cmd_function_s addbot_f_VAR;
cmd_function_s ddldump_f_VAR;
cmd_function_s weapondefdump_f_VAR;
cmd_function_s view_vehicle_ents_f_VAR;
cmd_function_s loadout_save_f_VAR;
cmd_function_s FastRestart_f_VAR;
cmd_function_s MapRestart_f_VAR;
cmd_function_s omnvar_set_f_VAR;
cmd_function_s omnvar_dump_f_VAR;
CmdArgs* cmd_args;
Addresses g_Addrs; Addresses g_Addrs;

View File

@ -1,224 +1,234 @@
#pragma once #pragma once
#include "Main.hpp" #include "Main.hpp"
struct gentity_s; struct gentity_s;
struct CmdArgs; struct CmdArgs;
struct Addresses { struct Addresses {
uintptr_t ModuleBase; uintptr_t ModuleBase;
uintptr_t jmp_rbx; uintptr_t jmp_rbx;
}; };
union DvarValue union DvarValue
{ {
bool enabled; bool enabled;
int integer; int integer;
unsigned int unsignedInt; unsigned int unsignedInt;
__int64 integer64; __int64 integer64;
unsigned __int64 unsignedInt64; unsigned __int64 unsignedInt64;
float value; float value;
float vector[4]; float vector[4];
const char* string; const char* string;
unsigned __int8 color[4]; unsigned __int8 color[4];
}; };
struct BbConstUsageFlags struct BbConstUsageFlags
{ {
bool initialized; bool initialized;
DvarValue codeValue; DvarValue codeValue;
}; };
struct netadr_t; struct netadr_t;
struct dvar_t struct dvar_t
{ {
const char* name; const char* name;
unsigned int checksum; unsigned int checksum;
const char* description; const char* description;
unsigned int flags; unsigned int flags;
char level[1]; char level[1];
unsigned __int8 type; unsigned __int8 type;
bool modified; bool modified;
unsigned __int16 hashNext; unsigned __int16 hashNext;
DvarValue current; DvarValue current;
DvarValue latched; DvarValue latched;
DvarValue reset; DvarValue reset;
char domain[0x10]; char domain[0x10];
BbConstUsageFlags BbConstUsageFlags; BbConstUsageFlags BbConstUsageFlags;
}; };
struct EncryptionHeader struct EncryptionHeader
{ {
unsigned int isEncrypted; unsigned int isEncrypted;
unsigned __int8 IV[16]; unsigned __int8 IV[16];
}; };
struct __declspec(align(8)) XFile struct __declspec(align(8)) XFile
{ {
unsigned __int64 size; unsigned __int64 size;
unsigned __int64 preloadWalkSize; unsigned __int64 preloadWalkSize;
unsigned __int64 blockSize[11]; unsigned __int64 blockSize[11];
EncryptionHeader encryption; EncryptionHeader encryption;
}; };
struct DB_FFHeader struct DB_FFHeader
{ {
unsigned __int64 magic; unsigned __int64 magic;
unsigned int headerVersion; unsigned int headerVersion;
unsigned int xfileVersion; unsigned int xfileVersion;
bool dashCompressBuild; bool dashCompressBuild;
bool dashEncryptBuild; bool dashEncryptBuild;
unsigned __int8 transientFileType[1]; unsigned __int8 transientFileType[1];
unsigned int residentPartSize; unsigned int residentPartSize;
unsigned int residentHash; unsigned int residentHash;
unsigned int alwaysLoadedPartSize; unsigned int alwaysLoadedPartSize;
XFile xfileHeader; XFile xfileHeader;
}; };
struct EncryptionInfo struct EncryptionInfo
{ {
EncryptionHeader header; EncryptionHeader header;
unsigned __int8 privateKey[32]; unsigned __int8 privateKey[32];
}; };
struct DBFileHandle struct DBFileHandle
{ {
unsigned __int8 fileID[4]; unsigned __int8 fileID[4];
unsigned __int64 dcacheFileID; unsigned __int64 dcacheFileID;
}; };
struct cmd_function_s struct cmd_function_s
{ {
cmd_function_s* next; cmd_function_s* next;
const char* name; const char* name;
const char** autoCompleteList; const char** autoCompleteList;
unsigned int autoCompleteListCount; unsigned int autoCompleteListCount;
void(__fastcall* function)(); void(__fastcall* function)();
}; };
struct DBFile struct DBFile
{ {
char name[64]; char name[64];
DBFileHandle dbFileHandle; DBFileHandle dbFileHandle;
bool isSecured; bool isSecured;
EncryptionInfo encryption; EncryptionInfo encryption;
}; };
struct Weapon; struct Weapon;
struct scrContext_t; struct scrContext_t;
extern dvar_t* player_name; extern dvar_t* player_name;
extern dvar_t* sv_cheats; extern dvar_t* sv_cheats;
extern dvar_t* spawn_br_gas; extern dvar_t* spawn_br_gas;
extern dvar_t* show_watermark; extern dvar_t* show_watermark;
extern dvar_t* player_sustainammo; extern dvar_t* player_sustainammo;
extern cmd_function_s set_byte_f_VAR; extern cmd_function_s set_byte_f_VAR;
extern cmd_function_s set_short_f_VAR; extern cmd_function_s set_short_f_VAR;
extern cmd_function_s set_int_f_VAR; extern cmd_function_s set_int_f_VAR;
extern cmd_function_s set_pointer_f_VAR; extern cmd_function_s set_float_f_VAR;
extern cmd_function_s quit_f_VAR; extern cmd_function_s set_pointer_f_VAR;
extern cmd_function_s openmenu_f_VAR; extern cmd_function_s quit_f_VAR;
extern cmd_function_s addbot_f_VAR; extern cmd_function_s openmenu_f_VAR;
extern cmd_function_s ddldump_f_VAR; extern cmd_function_s addbot_f_VAR;
extern cmd_function_s weapondefdump_f_VAR; extern cmd_function_s ddldump_f_VAR;
extern cmd_function_s view_vehicle_ents_f_VAR; extern cmd_function_s weapondefdump_f_VAR;
extern cmd_function_s loadout_save_f_VAR; extern cmd_function_s view_vehicle_ents_f_VAR;
extern cmd_function_s FastRestart_f_VAR; extern cmd_function_s loadout_save_f_VAR;
extern CmdArgs* cmd_args; extern cmd_function_s FastRestart_f_VAR;
extern cmd_function_s MapRestart_f_VAR;
void* RtlAddVectoredExceptionHandler(LONG First, PVECTORED_EXCEPTION_HANDLER Handler); extern cmd_function_s omnvar_set_f_VAR;
NTSTATUS NtContinue(PCONTEXT threadContext, BOOLEAN raiseAlert); extern cmd_function_s omnvar_dump_f_VAR;
extern CmdArgs* cmd_args;
#pragma region //game functions
void* RtlAddVectoredExceptionHandler(LONG First, PVECTORED_EXCEPTION_HANDLER Handler);
extern const char* (*va)(const char* fmt, ...); NTSTATUS NtContinue(PCONTEXT threadContext, BOOLEAN raiseAlert);
void Live_FakeUserSignIn(int controllerIndex, const char* gamertag); #pragma region //game functions
void R_AddCmdDrawText(const char* text, int maxChars, void /* GfxFont */* font, int fontHeight, float x, float y, float xScale, float yScale, float rotation, const float* color, const void /* FontGlowStyle */* glowStyle, bool usePost); extern const char* (*va)(const char* fmt, ...);
bool CG_WorldPosToScreenPosReal(int localClientNum, const uintptr_t scrPlace, const float* worldPos, float* outScreenPos); void Live_FakeUserSignIn(int controllerIndex, const char* gamertag);
void CG_DrawRotatedPicPhysical(uintptr_t scrPlace, float x, float y, float width, float height, float angle, const float* color, uintptr_t material); void R_AddCmdDrawText(const char* text, int maxChars, void /* GfxFont */* font, int fontHeight, float x, float y, float xScale, float yScale, float rotation, const float* color, const void /* FontGlowStyle */* glowStyle, bool usePost);
inline bool file_exists(const char* name) { bool CG_WorldPosToScreenPosReal(int localClientNum, const uintptr_t scrPlace, const float* worldPos, float* outScreenPos);
struct stat buffer;
return (stat(name, &buffer) == 0); void CG_DrawRotatedPicPhysical(uintptr_t scrPlace, float x, float y, float width, float height, float angle, const float* color, uintptr_t material);
}
inline bool file_exists(const char* name) {
uintptr_t FS_ReadFile(const char* qpath, const char** buffer); struct stat buffer;
const char* Dvar_GetStringSafe(const char* dvar); return (stat(name, &buffer) == 0);
}
unsigned int* GetRandSeed();
unsigned __int64 Sys_Microseconds(); uintptr_t FS_ReadFile(const char* qpath, const char** buffer);
int I_irand(int min, int max); const char* Dvar_GetStringSafe(const char* dvar);
unsigned __int64 I_atoui64_hex(const char* str); bool Dvar_GetBoolSafe(const char* dvar);
unsigned __int64 I_atoui64(const char* str); int Dvar_GetIntSafe(const char* dvar);
uintptr_t Dvar_FindVarByName(const char* dvarName);
unsigned int* GetRandSeed();
void CL_DrawText(const uintptr_t scrPlace, const char* text, int maxChars, uintptr_t font, float x, float y, int horzAlign, int vertAlign, float xScale, float yScale, const float* color, int style); unsigned __int64 Sys_Microseconds();
dvar_t* Dvar_RegisterString(const char* dvarName, const char* value, unsigned int flags, const char* description); int I_irand(int min, int max);
dvar_t* Dvar_RegisterBool(const char* dvarName, bool value, unsigned int flags, const char* description); unsigned __int64 I_atoui64_hex(const char* str);
unsigned __int64 I_atoui64(const char* str);
void LUI_CoD_LuaCall_ExecNow(uintptr_t luaVM, const char* str); uintptr_t Dvar_FindVarByName(const char* dvarName);
bool LUI_LuaCall_Game_IsEntityAlive(uintptr_t luaVM, int entityNum);
void CL_DrawText(const uintptr_t scrPlace, const char* text, int maxChars, uintptr_t font, float x, float y, int horzAlign, int vertAlign, float xScale, float yScale, const float* color, int style);
void Cbuf_AddText(const char* cmd); dvar_t* Dvar_RegisterString(const char* dvarName, const char* value, unsigned int flags, const char* description);
dvar_t* Dvar_RegisterBool(const char* dvarName, bool value, unsigned int flags, const char* description);
bool lua_toboolean(uintptr_t L, int idx);
void LUI_CoD_LuaCall_ExecNow(uintptr_t luaVM, const char* str);
void lua_pushboolean(uintptr_t L, int b); bool LUI_LuaCall_Game_IsEntityAlive(uintptr_t luaVM, int entityNum);
void lua_remove(uintptr_t L, int idx);
void lua_call(uintptr_t L, int nargs, int nresults); void Cbuf_AddText(const char* cmd);
void lua_getfield(uintptr_t L, int idx, const char* k);
void lua_pushvalue(uintptr_t L, int idx); bool lua_toboolean(uintptr_t L, int idx);
void lua_pushstring(uintptr_t L, const char* str);
void lua_pushinteger(uintptr_t L, int n); void lua_pushboolean(uintptr_t L, int b);
void lua_settop(uintptr_t L, int idx); void lua_remove(uintptr_t L, int idx);
int LuaShared_PCall(uintptr_t luaVM, int nargs, int nresults); void lua_call(uintptr_t L, int nargs, int nresults);
void lua_getfield(uintptr_t L, int idx, const char* k);
bool CG_DObjGetWorldBoneMatrix(uintptr_t pose, uintptr_t obj, int boneIndex, uintptr_t outTagMat, float* outOrigin); void lua_pushvalue(uintptr_t L, int idx);
void lua_pushstring(uintptr_t L, const char* str);
void CG_DrawLine(float X1, float Y1, float X2, float Y2, const float* color, float Width); void lua_pushinteger(uintptr_t L, int n);
void CG_DrawBone(int entIndex, uintptr_t ent, int from, int to, const float* color); void lua_settop(uintptr_t L, int idx);
void CG_DrawBones(int entIndex, uintptr_t ent, const float* color); int LuaShared_PCall(uintptr_t luaVM, int nargs, int nresults);
bool CheatsOk(int entNum); bool CG_DObjGetWorldBoneMatrix(uintptr_t pose, uintptr_t obj, int boneIndex, uintptr_t outTagMat, float* outOrigin);
void Cmd_Noclip_f(int entNum); void CG_DrawLine(float X1, float Y1, float X2, float Y2, const float* color, float Width);
void CG_DrawBone(int entIndex, uintptr_t ent, int from, int to, const float* color);
void SV_Cmd_ArgvBuffer(int arg, char* buffer, unsigned __int64 bufferLength); void CG_DrawBones(int entIndex, uintptr_t ent, const float* color);
void Cmd_ArgvBuffer(int arg, char* buffer, int bufferLength);
int Cmd_Argc(); bool CheatsOk(int entNum);
int SV_Cmd_Argc();
void Cmd_Noclip_f(int entNum);
void Cmd_AddCommandInternal(const char* cmdName, void(__fastcall* function)(), cmd_function_s* allocedCmd);
void Cmd_God_f(int entNum);
void AddReliableCommand(uintptr_t _this, const char* commandBuffer, const int reliableCmdSize, int type);
unsigned int MSG_WriteReliableCommandToBuffer(const char* pszCommand, char* pszBuffer, unsigned int iBufferSize); void SV_Cmd_ArgvBuffer(int arg, char* buffer, unsigned __int64 bufferLength);
void Cmd_ArgvBuffer(int arg, char* buffer, int bufferLength);
void CL_Main_AddReliableCommand(const char* cmd); int Cmd_Argc();
int SV_Cmd_Argc();
bool BG_Weapons_GetFullWeaponForName(const char* name, Weapon* outWeapon, Weapon* (__fastcall* getWeaponFunc)(Weapon* result, const char*));
void Cmd_AddCommandInternal(const char* cmdName, void(__fastcall* function)(), cmd_function_s* allocedCmd);
void Scr_AddString(scrContext_t* scrContext, const char* value);
unsigned int GScr_ExecEntThread(gentity_s* ent, int handle, unsigned int paramcount); void AddReliableCommand(uintptr_t _this, const char* commandBuffer, const int reliableCmdSize, int type);
void Scr_FreeThread(scrContext_t* scrContext, unsigned int handle); unsigned int MSG_WriteReliableCommandToBuffer(const char* pszCommand, char* pszBuffer, unsigned int iBufferSize);
int G_Weapon_GivePlayerWeapon(uintptr_t ps, uintptr_t scrContext, Weapon* weapon, int dualWield, int startInAltMode, int usedBefore); void CL_Main_AddReliableCommand(const char* cmd);
void G_Items_AddAmmo(uintptr_t ps, Weapon* weapon, bool isAlternate, int count, int fillClip);
bool BG_Weapons_GetFullWeaponForName(const char* name, Weapon* outWeapon, Weapon* (__fastcall* getWeaponFunc)(Weapon* result, const char*));
void G_Weapon_SelectWeapon(int clientNum, Weapon* weapon);
Weapon* BG_FindBaseWeaponForName(Weapon* result, const char* name); void Scr_AddString(scrContext_t* scrContext, const char* value);
unsigned int GScr_ExecEntThread(gentity_s* ent, int handle, unsigned int paramcount);
scrContext_t* ScriptContext_Server(); void Scr_FreeThread(scrContext_t* scrContext, unsigned int handle);
const char* SL_ConvertToString(int id); int G_Weapon_GivePlayerWeapon(uintptr_t ps, uintptr_t scrContext, Weapon* weapon, int dualWield, int startInAltMode, int usedBefore);
void G_Items_AddAmmo(uintptr_t ps, Weapon* weapon, bool isAlternate, int count, int fillClip);
union XAssetHeader DB_FindXAssetHeader(enum XAssetType type, const char* givenName, int allowCreateDefault);
void G_Weapon_SelectWeapon(int clientNum, Weapon* weapon);
#pragma endregion Weapon* BG_FindBaseWeaponForName(Weapon* result, const char* name);
scrContext_t* ScriptContext_Server();
const char* SL_ConvertToString(int id);
union XAssetHeader DB_FindXAssetHeader(enum XAssetType type, const char* givenName, int allowCreateDefault);
void Com_SetErrorMessage(const char* errorMessage);
#pragma endregion
extern Addresses g_Addrs; extern Addresses g_Addrs;

View File

@ -48,7 +48,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType> <ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries> <UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset> <PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization> <WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet> <CharacterSet>MultiByte</CharacterSet>
<UseOfMfc>false</UseOfMfc> <UseOfMfc>false</UseOfMfc>
@ -81,10 +81,12 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental> <LinkIncremental>true</LinkIncremental>
<TargetName>discord_game_sdk</TargetName> <TargetName>discord_game_sdk</TargetName>
<LibraryPath>D:\Dokumente\CoDMW19\codUPLOADER\mw19-of-main\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental> <LinkIncremental>false</LinkIncremental>
<TargetName>discord_game_sdk</TargetName> <TargetName>discord_game_sdk</TargetName>
<LibraryPath>D:\Dokumente\CoDMW19\codUPLOADER\mw19-of-main\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup> </PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile> <ClCompile>
@ -136,13 +138,13 @@
<SDLCheck>true</SDLCheck> <SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NOMINMAX;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>NOMINMAX;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode> <ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpplatest</LanguageStandard> <LanguageStandard>stdcpp20</LanguageStandard>
</ClCompile> </ClCompile>
<Link> <Link>
<SubSystem>Console</SubSystem> <SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding> <EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences> <OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation> <GenerateDebugInformation>false</GenerateDebugInformation>
<AdditionalDependencies>minhook.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>minhook.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)</AdditionalDependencies>
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>
@ -181,7 +183,6 @@
<ClInclude Include="common\utils\smbios.hpp" /> <ClInclude Include="common\utils\smbios.hpp" />
<ClInclude Include="common\utils\string.hpp" /> <ClInclude Include="common\utils\string.hpp" />
<ClInclude Include="common\utils\thread.hpp" /> <ClInclude Include="common\utils\thread.hpp" />
<ClInclude Include="csv.hpp" />
<ClInclude Include="functions.hpp" /> <ClInclude Include="functions.hpp" />
<ClInclude Include="ini.h" /> <ClInclude Include="ini.h" />
<ClInclude Include="json.hpp" /> <ClInclude Include="json.hpp" />

View File

@ -1,143 +1,142 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup> <ItemGroup>
<Filter Include="Resource Files"> <Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter> </Filter>
<Filter Include="common"> <Filter Include="common">
<UniqueIdentifier>{9ba1aab7-3c29-4043-88a2-0733bdba52af}</UniqueIdentifier> <UniqueIdentifier>{9ba1aab7-3c29-4043-88a2-0733bdba52af}</UniqueIdentifier>
</Filter> </Filter>
<Filter Include="common\exception"> <Filter Include="common\exception">
<UniqueIdentifier>{67571f10-529c-4ebd-94b6-2cebbbb62a35}</UniqueIdentifier> <UniqueIdentifier>{67571f10-529c-4ebd-94b6-2cebbbb62a35}</UniqueIdentifier>
</Filter> </Filter>
<Filter Include="common\utils"> <Filter Include="common\utils">
<UniqueIdentifier>{03fd645c-a59f-4d26-950c-b411df71f725}</UniqueIdentifier> <UniqueIdentifier>{03fd645c-a59f-4d26-950c-b411df71f725}</UniqueIdentifier>
</Filter> </Filter>
<Filter Include="hook_lib"> <Filter Include="hook_lib">
<UniqueIdentifier>{997a4fac-6cde-43a6-84df-2e0e58b4b7fc}</UniqueIdentifier> <UniqueIdentifier>{997a4fac-6cde-43a6-84df-2e0e58b4b7fc}</UniqueIdentifier>
</Filter> </Filter>
<Filter Include="hook_lib\game"> <Filter Include="hook_lib\game">
<UniqueIdentifier>{0999b80b-b47c-4d8e-8776-f5c778bcac9f}</UniqueIdentifier> <UniqueIdentifier>{0999b80b-b47c-4d8e-8776-f5c778bcac9f}</UniqueIdentifier>
</Filter> </Filter>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="common\utils\binary_resource.cpp"> <ClCompile Include="common\utils\binary_resource.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\utils\hardware_breakpoint.cpp"> <ClCompile Include="common\utils\hardware_breakpoint.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\utils\hook.cpp"> <ClCompile Include="common\utils\hook.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\utils\http.cpp"> <ClCompile Include="common\utils\http.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\utils\io.cpp"> <ClCompile Include="common\utils\io.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\utils\memory.cpp"> <ClCompile Include="common\utils\memory.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\utils\nt.cpp"> <ClCompile Include="common\utils\nt.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\utils\signature.cpp"> <ClCompile Include="common\utils\signature.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\utils\smbios.cpp"> <ClCompile Include="common\utils\smbios.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\utils\string.cpp"> <ClCompile Include="common\utils\string.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\exception\minidump.cpp"> <ClCompile Include="common\exception\minidump.cpp">
<Filter>common\exception</Filter> <Filter>common\exception</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="Main.cpp"> <ClCompile Include="Main.cpp">
<Filter>hook_lib</Filter> <Filter>hook_lib</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="functions.cpp"> <ClCompile Include="functions.cpp">
<Filter>hook_lib\game</Filter> <Filter>hook_lib\game</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="common\utils\thread.cpp"> <ClCompile Include="common\utils\thread.cpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="structs.cpp"> <ClCompile Include="structs.cpp">
<Filter>hook_lib\game</Filter> <Filter>hook_lib\game</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="assets.cpp"> <ClCompile Include="assets.cpp">
<Filter>hook_lib\game</Filter> <Filter>hook_lib\game</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="splashscreen.cpp"> <ClCompile Include="splashscreen.cpp">
<Filter>hook_lib\game</Filter> <Filter>hook_lib\game</Filter>
</ClCompile> </ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="common\utils\binary_resource.hpp"> <ClInclude Include="common\utils\binary_resource.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\concurrency.hpp"> <ClInclude Include="common\utils\concurrency.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\finally.hpp"> <ClInclude Include="common\utils\finally.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\hardware_breakpoint.hpp"> <ClInclude Include="common\utils\hardware_breakpoint.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\hook.hpp"> <ClInclude Include="common\utils\hook.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\http.hpp"> <ClInclude Include="common\utils\http.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\io.hpp"> <ClInclude Include="common\utils\io.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\memory.hpp"> <ClInclude Include="common\utils\memory.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\nt.hpp"> <ClInclude Include="common\utils\nt.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\signature.hpp"> <ClInclude Include="common\utils\signature.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\smbios.hpp"> <ClInclude Include="common\utils\smbios.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\string.hpp"> <ClInclude Include="common\utils\string.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\exception\minidump.hpp"> <ClInclude Include="common\exception\minidump.hpp">
<Filter>common\exception</Filter> <Filter>common\exception</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="Main.hpp"> <ClInclude Include="Main.hpp">
<Filter>hook_lib</Filter> <Filter>hook_lib</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="MinHook.hpp"> <ClInclude Include="MinHook.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="functions.hpp"> <ClInclude Include="functions.hpp">
<Filter>hook_lib\game</Filter> <Filter>hook_lib\game</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="common\utils\thread.hpp"> <ClInclude Include="common\utils\thread.hpp">
<Filter>common\utils</Filter> <Filter>common\utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="structs.h"> <ClInclude Include="structs.h">
<Filter>hook_lib\game</Filter> <Filter>hook_lib\game</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="assets.h"> <ClInclude Include="assets.h">
<Filter>hook_lib\game</Filter> <Filter>hook_lib\game</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="ini.h"> <ClInclude Include="ini.h">
<Filter>hook_lib\game</Filter> <Filter>hook_lib\game</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="json.hpp"> <ClInclude Include="json.hpp">
<Filter>hook_lib\game</Filter> <Filter>hook_lib\game</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="csv.hpp" /> </ItemGroup>
</ItemGroup>
</Project> </Project>

View File

@ -1,15 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup />
<ShowAllFiles>true</ShowAllFiles>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LocalDebuggerCommand>D:\Games\CODMWDebug\Call of Duty Modern Warfare %282019%29\game_dx12_ship_replay.exe</LocalDebuggerCommand>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerCommand>D:\Games\CODMWDebug\Call of Duty Modern Warfare %282019%29\game_dx12_ship_replay.exe</LocalDebuggerCommand>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
<LocalDebuggerWorkingDirectory>..\..\..\..\Games\CODMWDebug\Call of Duty Modern Warfare %282019%29</LocalDebuggerWorkingDirectory>
</PropertyGroup>
</Project> </Project>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

View File

@ -1,8 +0,0 @@
Base Address: 00007FF7D0550000
dvar registered!
dvar registered!
registering lui dvars
Base Address: 00007FF7D0550000
dvar registered!
dvar registered!
registering lui dvars

View File

@ -1 +1 @@
#pragma once #pragma once

File diff suppressed because one or more lines are too long

View File

@ -1,15 +1,15 @@
#pragma once #pragma once
#include "Main.hpp" #include "Main.hpp"
typedef unsigned char byte; typedef unsigned char byte;
size_t operator"" _b(size_t val); size_t operator"" _b(size_t val);
size_t reverse_b(size_t val); size_t reverse_b(size_t val);
size_t reverse_b(const void* val); size_t reverse_b(const void* val);
size_t operator"" _g(size_t val); size_t operator"" _g(size_t val);
size_t reverse_g(size_t val); size_t reverse_g(size_t val);
size_t reverse_g(const void* val); size_t reverse_g(const void* val);
extern byte data_buf[0x12856B]; extern byte data_buf[1];
void set_splashscreen(); void set_splashscreen();

View File

@ -1,116 +1,116 @@
#include "structs.h" #include "structs.h"
#pragma region //msg_t #pragma region //msg_t
unsigned __int64 MSG_ReadInt64(const msg_t* msg) { unsigned __int64 MSG_ReadInt64(const msg_t* msg) {
auto func = reinterpret_cast<unsigned __int64(*)(const msg_t*)>(0x1412B9270_g); auto func = reinterpret_cast<unsigned __int64(*)(const msg_t*)>(0x1412B9270_g);
return func(msg); return func(msg);
} }
void MSG_WriteInt64(const msg_t* msg, const unsigned __int64 value) { void MSG_WriteInt64(const msg_t* msg, const unsigned __int64 value) {
auto func = reinterpret_cast<void(*)(const msg_t*, const unsigned __int64)>(0x1412BA7F0_g); auto func = reinterpret_cast<void(*)(const msg_t*, const unsigned __int64)>(0x1412BA7F0_g);
func(msg, value); func(msg, value);
} }
#pragma endregion #pragma endregion
#pragma region //XUID #pragma region //XUID
void XUID::Deserialize(const msg_t* msg) { void XUID::Deserialize(const msg_t* msg) {
this->m_id = MSG_ReadInt64(msg); this->m_id = MSG_ReadInt64(msg);
} }
void XUID::Serialize(const msg_t* msg) { void XUID::Serialize(const msg_t* msg) {
MSG_WriteInt64(msg, this->m_id); MSG_WriteInt64(msg, this->m_id);
} }
XUID* XUID::FromHexString(const char* xuidString) { XUID* XUID::FromHexString(const char* xuidString) {
this->m_id = I_atoui64_hex(xuidString); this->m_id = I_atoui64_hex(xuidString);
return this; return this;
} }
XUID* XUID::FromMsg(const msg_t* msg) { XUID* XUID::FromMsg(const msg_t* msg) {
this->m_id = MSG_ReadInt64(msg); this->m_id = MSG_ReadInt64(msg);
return this; return this;
} }
XUID* XUID::FromString(const char* xuidString) { XUID* XUID::FromString(const char* xuidString) {
this->m_id = I_atoui64(xuidString); this->m_id = I_atoui64(xuidString);
return this; return this;
} }
XUID* XUID::FromUInt64(unsigned __int64 id) { XUID* XUID::FromUInt64(unsigned __int64 id) {
this->m_id = id; this->m_id = id;
return this; return this;
} }
XUID* XUID::FromUniversalId(unsigned __int64 id) { XUID* XUID::FromUniversalId(unsigned __int64 id) {
this->m_id = id; this->m_id = id;
return this; return this;
} }
unsigned __int64 XUID::GetUniversalId() { unsigned __int64 XUID::GetUniversalId() {
return this->m_id; return this->m_id;
} }
bool XUID::IsNull() { bool XUID::IsNull() {
return this->m_id == 0; return this->m_id == 0;
} }
bool XUID::IsValid() { bool XUID::IsValid() {
return this->m_id != 0; return this->m_id != 0;
} }
XUID* XUID::NullXUID() { XUID* XUID::NullXUID() {
this->m_id = 0; this->m_id = 0;
return this; return this;
} }
XUID* XUID::RandomXUID() { XUID* XUID::RandomXUID() {
unsigned int* RandSeed; unsigned int* RandSeed;
unsigned int BackupRandSeed; unsigned int BackupRandSeed;
this->m_id = 0; this->m_id = 0;
RandSeed = GetRandSeed(); RandSeed = GetRandSeed();
BackupRandSeed = *RandSeed; BackupRandSeed = *RandSeed;
*RandSeed = Sys_Microseconds(); *RandSeed = Sys_Microseconds();
this->m_id = I_irand(1, 0x7FFFFFFF); this->m_id = I_irand(1, 0x7FFFFFFF);
*RandSeed = BackupRandSeed; *RandSeed = BackupRandSeed;
return this; return this;
} }
const char* XUID::ToDevString() { const char* XUID::ToDevString() {
return va("%zu", this->m_id); return va("%zu", this->m_id);
} }
const char* XUID::ToHexString() { const char* XUID::ToHexString() {
return va("%zx", this->m_id); return va("%zx", this->m_id);
} }
const char* XUID::ToString() { const char* XUID::ToString() {
return va("%zu", this->m_id); return va("%zu", this->m_id);
} }
bool XUID::operator !=(const XUID* xuid) { bool XUID::operator !=(const XUID* xuid) {
return this->m_id != xuid->m_id; return this->m_id != xuid->m_id;
} }
XUID* XUID::operator =(const XUID* xuid) { XUID* XUID::operator =(const XUID* xuid) {
this->m_id = xuid->m_id; this->m_id = xuid->m_id;
return this; return this;
} }
bool XUID::operator ==(const XUID* xuid) { bool XUID::operator ==(const XUID* xuid) {
return this->m_id == xuid->m_id; return this->m_id == xuid->m_id;
} }
#pragma endregion #pragma endregion
ClActiveClient* ms_activeClients; ClActiveClient* ms_activeClients;
clientUIActive_t* clientUIActives; clientUIActive_t* clientUIActives;
gentity_s* g_entities; gentity_s* g_entities;

File diff suppressed because it is too large Load Diff

BIN
lib/minhook.lib Normal file

Binary file not shown.