├── .gitattributes ├── Libraries ├── ntdll │ ├── ntdll_x64.lib │ └── ntdll_x86.lib ├── cmake.toml ├── MinHook │ ├── hde │ │ ├── pstdint.h │ │ ├── hde32.h │ │ ├── hde64.h │ │ ├── table32.h │ │ ├── table64.h │ │ ├── hde32.c │ │ └── hde64.c │ ├── buffer.h │ ├── trampoline.h │ ├── MinHook.h │ ├── buffer.c │ ├── trampoline.c │ └── hook.c ├── HookDll │ ├── HookDll.hpp │ └── HookDll.cpp ├── CMakeLists.txt └── AppInitDispatcher │ ├── AppInitDispatcher.cpp │ └── Utf8Ini.hpp ├── CMake ├── AppInitHook.ini ├── msvc-static-runtime.cmake ├── cmake.toml ├── register_x64.reg.in ├── register_x86.reg.in ├── msvc-configurations.cmake ├── flatten-build-hierarchy.cmake ├── register_AppInitDLLs.cmake ├── AppInitHook-custom.cmake └── cmkr.cmake ├── .gitignore ├── TestLoader └── TestLoader.cpp ├── Modules ├── ForceQuit │ └── ForceQuit.cpp ├── ExitProcess │ └── ExitProcess.cpp ├── WowUndirect │ └── WowUndirect.cpp ├── AppInitExampleModule │ └── AppInitExampleModule.cpp ├── NoSoftwareInventory │ └── NoSoftwareInventory.cpp ├── HighPriority │ └── HighPriority.cpp ├── TotalCommander │ └── TotalCommander.cpp ├── GitMagic │ └── GitMagic.cpp ├── clang-cl-hacks │ └── clang-cl-hacks.cpp ├── WerfaultMagic │ └── WerfaultMagic.cpp ├── CmdImproved │ └── CmdImproved.cpp ├── cmake.toml ├── ConhostLoader │ └── ConhostLoader.cpp ├── CMakeClean │ └── CMakeClean.cpp └── CMakeLists.txt ├── cmake.toml ├── README.md ├── CMakeLists.txt └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | /CMake/cmkr.cmake linguist-generated 2 | /CMakeLists.txt linguist-generated 3 | -------------------------------------------------------------------------------- /Libraries/ntdll/ntdll_x64.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrexodia/AppInitHook/HEAD/Libraries/ntdll/ntdll_x64.lib -------------------------------------------------------------------------------- /Libraries/ntdll/ntdll_x86.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrexodia/AppInitHook/HEAD/Libraries/ntdll/ntdll_x86.lib -------------------------------------------------------------------------------- /CMake/AppInitHook.ini: -------------------------------------------------------------------------------- 1 | ; The module path is relative to AppInitHook.ini, full paths are allowed 2 | [TestLoader.exe] 3 | Module=ExitProcess.dll -------------------------------------------------------------------------------- /CMake/msvc-static-runtime.cmake: -------------------------------------------------------------------------------- 1 | cmake_policy(SET CMP0091 NEW) 2 | set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" CACHE STRING "") -------------------------------------------------------------------------------- /CMake/cmake.toml: -------------------------------------------------------------------------------- 1 | [target.MyPrivateModule] 2 | type = "shared" 3 | sources = ["MyPrivateModule/*.cpp", "MyPrivateModule/*.hpp"] 4 | link-libraries = ["HookDll"] -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # CMake/IDE artifacts 2 | build*/ 3 | .idea/ 4 | .vs/ 5 | cmake-build-*/ 6 | /CMakeSettings.json 7 | CMakeLists.txt.user 8 | 9 | # Don't push private modules 10 | /Private/ -------------------------------------------------------------------------------- /TestLoader/TestLoader.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | MessageBoxA(0, "Hello world!", "TestLoader", MB_SYSTEMMODAL); 6 | OutputDebugStringA("[AppInitHook] main()"); 7 | } -------------------------------------------------------------------------------- /CMake/register_x64.reg.in: -------------------------------------------------------------------------------- 1 | Windows Registry Editor Version 5.00 2 | 3 | [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows] 4 | "LoadAppInit_DLLs"=dword:00000001 5 | "RequireSignedAppInit_DLLs"=dword:00000000 6 | "AppInit_DLLs"="${APPINITDISPATCHER_PATH}" 7 | 8 | -------------------------------------------------------------------------------- /CMake/register_x86.reg.in: -------------------------------------------------------------------------------- 1 | Windows Registry Editor Version 5.00 2 | 3 | [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\Windows] 4 | "LoadAppInit_DLLs"=dword:00000001 5 | "RequireSignedAppInit_DLLs"=dword:00000000 6 | "AppInit_DLLs"="${APPINITDISPATCHER_PATH}" 7 | 8 | -------------------------------------------------------------------------------- /Modules/ForceQuit/ForceQuit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | BOOL WINAPI DllMain( 4 | _In_ HINSTANCE hinstDLL, 5 | _In_ DWORD fdwReason, 6 | _In_ LPVOID lpvReserved 7 | ) 8 | { 9 | OutputDebugStringA("[AppInitHook] [ForceQuit] ExitProcess(-1)"); 10 | ExitProcess(-1); 11 | return TRUE; 12 | } -------------------------------------------------------------------------------- /Modules/ExitProcess/ExitProcess.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | BOOL WINAPI DllMain( 4 | _In_ HINSTANCE hinstDLL, 5 | _In_ DWORD fdwReason, 6 | _In_ LPVOID lpvReserved 7 | ) 8 | { 9 | if (fdwReason == DLL_PROCESS_ATTACH) 10 | { 11 | dlogp("Fuck this shit, I'm out of here!"); 12 | ExitProcess(0); 13 | } 14 | return TRUE; 15 | } -------------------------------------------------------------------------------- /Modules/WowUndirect/WowUndirect.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | BOOL WINAPI DllMain( 4 | _In_ HINSTANCE hinstDLL, 5 | _In_ DWORD fdwReason, 6 | _In_ LPVOID lpvReserved 7 | ) 8 | { 9 | if (fdwReason == DLL_PROCESS_ATTACH) 10 | { 11 | PVOID oldValue = NULL; 12 | Wow64DisableWow64FsRedirection(&oldValue); 13 | dlogp("Disabled redirects"); 14 | } 15 | return TRUE; 16 | } -------------------------------------------------------------------------------- /Modules/AppInitExampleModule/AppInitExampleModule.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | HOOK(kernelbase.dll, BOOL WINAPI, SetCurrentDirectoryW)( 4 | __in LPCWSTR lpPathName 5 | ) 6 | { 7 | dlogp("'%S'", lpPathName); 8 | return original_SetCurrentDirectoryW(lpPathName); 9 | } 10 | 11 | BOOL WINAPI DllMain( 12 | _In_ HINSTANCE hinstDLL, 13 | _In_ DWORD fdwReason, 14 | _In_ LPVOID lpvReserved 15 | ) 16 | { 17 | return HookDllMain(hinstDLL, fdwReason, lpvReserved); 18 | } -------------------------------------------------------------------------------- /Modules/NoSoftwareInventory/NoSoftwareInventory.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | BOOL WINAPI DllMain( 4 | _In_ HINSTANCE hinstDLL, 5 | _In_ DWORD fdwReason, 6 | _In_ LPVOID lpvReserved 7 | ) 8 | { 9 | if(fdwReason == DLL_PROCESS_ATTACH) 10 | { 11 | if(wcsstr(GetCommandLineW(), L"aeinv.dll,UpdateSoftwareInventory")) 12 | { 13 | OutputDebugStringA("[AppInitHook] [NoSoftwareInventory] ExitProcess(-1)"); 14 | ExitProcess(-1); 15 | } 16 | } 17 | return TRUE; 18 | } -------------------------------------------------------------------------------- /CMake/msvc-configurations.cmake: -------------------------------------------------------------------------------- 1 | # Set up a more familiar Visual Studio configuration 2 | # Override these options with -DCMAKE_OPTION=Value 3 | # 4 | # See: https://cmake.org/cmake/help/latest/command/set.html#set-cache-entry 5 | set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "") 6 | set(CMAKE_EXE_LINKER_FLAGS_RELEASE "/DEBUG:FULL /INCREMENTAL:NO" CACHE STRING "") 7 | set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "/DEBUG:FULL /INCREMENTAL:NO" CACHE STRING "") 8 | set(CMAKE_BUILD_TYPE "Release" CACHE STRING "") -------------------------------------------------------------------------------- /Modules/HighPriority/HighPriority.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | BOOL WINAPI DllMain( 4 | _In_ HINSTANCE hinstDLL, 5 | _In_ DWORD fdwReason, 6 | _In_ LPVOID lpvReserved 7 | ) 8 | { 9 | if (fdwReason == DLL_PROCESS_ATTACH) 10 | { 11 | auto hProcess = OpenProcess(PROCESS_SET_INFORMATION, FALSE, GetCurrentProcessId()); 12 | if (hProcess) 13 | { 14 | SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS); 15 | CloseHandle(hProcess); 16 | dlogp("High priority bois!"); 17 | } 18 | } 19 | return FALSE; 20 | } -------------------------------------------------------------------------------- /CMake/flatten-build-hierarchy.cmake: -------------------------------------------------------------------------------- 1 | # Flatten build hierarchy (see: https://stackoverflow.com/a/51320498/1806760) 2 | if(CMAKE_CONFIGURATION_TYPES) 3 | set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/$") 4 | set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/$") 5 | set(CMAKE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/$") 6 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/$") 7 | else() 8 | set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") 9 | set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") 10 | set(CMAKE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") 11 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") 12 | endif() -------------------------------------------------------------------------------- /cmake.toml: -------------------------------------------------------------------------------- 1 | [cmake] 2 | version = "3.15" 3 | cmkr-include = "CMake/cmkr.cmake" 4 | 5 | [options] 6 | APPINITHOOK_PRIVATE_MODULES = true 7 | APPINITHOOK_UNLOAD_DISPATCHER = true 8 | 9 | [conditions] 10 | private = "APPINITHOOK_PRIVATE_MODULES" 11 | unload-dispatcher = "APPINITHOOK_UNLOAD_DISPATCHER" 12 | 13 | [project] 14 | name = "AppInitHook" 15 | version = "0.1.0" 16 | subdirs = ["Libraries", "Modules"] 17 | private.subdirs = ["Private"] 18 | include-before = [ 19 | "CMake/msvc-static-runtime.cmake", 20 | "CMake/msvc-configurations.cmake", 21 | ] 22 | include-after = [ 23 | "CMake/flatten-build-hierarchy.cmake", 24 | "CMake/AppInitHook-custom.cmake", 25 | ] 26 | 27 | [target.TestLoader] 28 | type = "executable" 29 | sources = ["TestLoader/*.cpp", "TestLoader/*.hpp"] 30 | -------------------------------------------------------------------------------- /Libraries/cmake.toml: -------------------------------------------------------------------------------- 1 | [conditions] 2 | x86 = "CMAKE_SIZEOF_VOID_P EQUAL 4" 3 | x64 = "CMAKE_SIZEOF_VOID_P EQUAL 8" 4 | 5 | [target.ntdll] 6 | type = "interface" 7 | include-directories = ["${CMAKE_CURRENT_SOURCE_DIR}"] 8 | link-directories = ["ntdll"] 9 | x86.link-libraries = ["ntdll_x86"] 10 | x64.link-libraries = ["ntdll_x64"] 11 | 12 | [target.MinHook] 13 | type = "static" 14 | sources = ["MinHook/**.c", "MinHook/**.h"] 15 | include-directories = ["${CMAKE_CURRENT_SOURCE_DIR}"] 16 | 17 | [target.HookDll] 18 | type = "static" 19 | sources = ["HookDll/*.cpp", "HookDll/*.hpp", "ntdll/ntdll.h"] 20 | include-directories = ["HookDll"] 21 | link-libraries = ["ntdll", "MinHook"] 22 | 23 | [target.AppInitDispatcher] 24 | type = "shared" 25 | sources = ["AppInitDispatcher/*.cpp", "AppInitDispatcher/*.hpp"] 26 | link-libraries = ["HookDll"] 27 | properties = { EXCLUDE_FROM_DEFAULT_BUILD = "TRUE" } 28 | unload-dispatcher.compile-definitions = ["UNLOAD_DISPATCHER"] -------------------------------------------------------------------------------- /CMake/register_AppInitDLLs.cmake: -------------------------------------------------------------------------------- 1 | if(NOT APPINITDISPATCHER_PATH) 2 | message(FATAL_ERROR "You need -DAPPINITDISPATCHER_PATH=...") 3 | endif() 4 | 5 | get_filename_component(APPINITDISPATCHER_DIR "${APPINITDISPATCHER_PATH}" DIRECTORY) 6 | file(TO_NATIVE_PATH "${APPINITDISPATCHER_PATH}" APPINITDISPATCHER_PATH) 7 | string(REPLACE "\\" "\\\\" APPINITDISPATCHER_PATH "${APPINITDISPATCHER_PATH}") 8 | 9 | set(INSTALL_REG "${APPINITDISPATCHER_DIR}/register_AppInitDLL.reg") 10 | if(CMAKE_SIZEOF_VOID_P EQUAL 8) 11 | configure_file("${CMAKE_CURRENT_LIST_DIR}/register_x64.reg.in" "${INSTALL_REG}") 12 | else() 13 | configure_file("${CMAKE_CURRENT_LIST_DIR}/register_x86.reg.in" "${INSTALL_REG}") 14 | endif() 15 | file(TO_NATIVE_PATH "${INSTALL_REG}" INSTALL_REG) 16 | 17 | if(NOT EXISTS "${APPINITDISPATCHER_DIR}/AppInitHook.ini") 18 | message(STATUS "Creating AppInitHook.ini...") 19 | file( 20 | COPY "${CMAKE_CURRENT_LIST_DIR}/AppInitHook.ini" 21 | DESTINATION "${APPINITDISPATCHER_DIR}" 22 | ) 23 | endif() 24 | 25 | message(STATUS "Importing ${INSTALL_REG} into the registry...") 26 | execute_process(COMMAND cmd /C start "${INSTALL_REG}") 27 | -------------------------------------------------------------------------------- /Modules/TotalCommander/TotalCommander.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | #include 3 | 4 | HOOK(user32.dll, BOOL WINAPI, SetWindowTextW)( 5 | __in HWND hWnd, 6 | __in_opt LPCWSTR lpString 7 | ) 8 | { 9 | if (lpString) 10 | { 11 | #ifdef _WIN64 12 | auto totalCommander = L"Total Commander (x64) "; 13 | #else 14 | auto totalCommander = L"Total Commander "; 15 | #endif //_WIN64 16 | if (wcsstr(lpString, totalCommander)) 17 | { 18 | wchar_t szClassName[64] = L""; 19 | GetClassNameW(hWnd, szClassName, _countof(szClassName)); 20 | if (wcscmp(szClassName, L"TTOTAL_CMD") == 0) 21 | { 22 | dlogp("Fixed title!"); 23 | std::wstring newText = lpString; 24 | auto dashIdx = newText.find(L"Total Commander"); 25 | if (dashIdx != std::wstring::npos) 26 | newText.resize(dashIdx + 15); 27 | return original_SetWindowTextW(hWnd, newText.c_str()); 28 | } 29 | } 30 | } 31 | return original_SetWindowTextW(hWnd, lpString); 32 | } 33 | 34 | BOOL WINAPI DllMain( 35 | _In_ HINSTANCE hinstDLL, 36 | _In_ DWORD fdwReason, 37 | _In_ LPVOID lpvReserved 38 | ) 39 | { 40 | return HookDllMain(hinstDLL, fdwReason, lpvReserved); 41 | } -------------------------------------------------------------------------------- /Modules/GitMagic/GitMagic.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | BOOL WINAPI DllMain( 4 | _In_ HINSTANCE hinstDLL, 5 | _In_ DWORD fdwReason, 6 | _In_ LPVOID lpvReserved 7 | ) 8 | { 9 | if (fdwReason == DLL_PROCESS_ATTACH) 10 | { 11 | char currentDir[MAX_PATH] = ""; 12 | GetCurrentDirectoryA(_countof(currentDir), currentDir); 13 | dlogp("currentDir: '%s'", currentDir); 14 | auto commandLine = GetCommandLineA(); 15 | dlogp("commandLine: '%s'", commandLine); 16 | if (false && strstr(commandLine, "submodule sync --recursive") && strstr(commandLine, "git.exe")) 17 | //if (strstr(commandLine, "\"fetch\"") && strstr(commandLine, "git.exe")) 18 | { 19 | dlogp("FETCH! Sleeping 20 seconds..."); 20 | char lockfile[MAX_PATH] = ""; 21 | strcpy_s(lockfile, currentDir); 22 | strcat_s(lockfile, "\\.git\\index.lock"); 23 | auto hFile = CreateFileA(lockfile, GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); 24 | dlogp("hFile: %p", hFile); 25 | if (hFile != INVALID_HANDLE_VALUE) 26 | CloseHandle(hFile); 27 | Sleep(20000); 28 | DeleteFileA(lockfile); 29 | dlogp("done waiting"); 30 | } 31 | } 32 | return TRUE; 33 | } -------------------------------------------------------------------------------- /Modules/clang-cl-hacks/clang-cl-hacks.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | #include 4 | #include 5 | 6 | BOOL WINAPI DllMain( 7 | _In_ HINSTANCE hinstDLL, 8 | _In_ DWORD fdwReason, 9 | _In_ LPVOID lpvReserved 10 | ) 11 | { 12 | dlog(); 13 | if (fdwReason == DLL_PROCESS_ATTACH) 14 | { 15 | int argc = 0; 16 | auto argv = CommandLineToArgvW(GetCommandLineW(), &argc); 17 | for (int i = 0; i < argc; i++) 18 | { 19 | auto arg = argv[i]; 20 | if (*arg == '@') 21 | { 22 | dlogp("kurwa: %S", arg + 1); 23 | auto hFile = CreateFileW(arg + 1, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); 24 | if (hFile != INVALID_HANDLE_VALUE) 25 | { 26 | auto sz = GetFileSize(hFile, nullptr); 27 | dlogp("size: %u", sz); 28 | std::vector s(sz / 2 + 1); 29 | DWORD read = 0; 30 | if (ReadFile(hFile, s.data(), s.size() * 2 - 1, &read, nullptr)) 31 | { 32 | //MessageBoxW(0, s.data(), 0, MB_SYSTEMMODAL); 33 | dlogp("%S", s.data() + 1); 34 | } 35 | CloseHandle(hFile); 36 | } 37 | } 38 | } 39 | LocalFree(argv); 40 | } 41 | return HookDllMain(hinstDLL, fdwReason, lpvReserved); 42 | } -------------------------------------------------------------------------------- /Modules/WerfaultMagic/WerfaultMagic.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | #include 4 | 5 | HOOK(ntdll.dll, NTSTATUS NTAPI, NtQueryValueKey)( 6 | _In_ HANDLE KeyHandle, 7 | _In_ PUNICODE_STRING ValueName, 8 | _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, 9 | _Out_ PVOID KeyValueInformation, 10 | _In_ ULONG Length, 11 | _Out_ PULONG ResultLength 12 | ) 13 | { 14 | __try 15 | { 16 | UNICODE_STRING DebuggerStr; 17 | RtlInitUnicodeString(&DebuggerStr, L"Debugger"); 18 | if (RtlCompareUnicodeString(&DebuggerStr, ValueName, TRUE) == 0) 19 | { 20 | UNICODE_STRING ValueNameMagic; 21 | RtlInitUnicodeString(&ValueNameMagic, L"DebuggerMagic"); 22 | auto magicStatus = original_NtQueryValueKey(KeyHandle, &ValueNameMagic, KeyValueInformationClass, KeyValueInformation, Length, ResultLength); 23 | if (NT_SUCCESS(magicStatus)) 24 | return magicStatus; 25 | } 26 | } 27 | __except (EXCEPTION_EXECUTE_HANDLER) 28 | { 29 | } 30 | return original_NtQueryValueKey(KeyHandle, ValueName, KeyValueInformationClass, KeyValueInformation, Length, ResultLength); 31 | } 32 | 33 | BOOL WINAPI DllMain( 34 | _In_ HINSTANCE hinstDLL, 35 | _In_ DWORD fdwReason, 36 | _In_ LPVOID lpvReserved 37 | ) 38 | { 39 | return HookDllMain(hinstDLL, fdwReason, lpvReserved); 40 | } -------------------------------------------------------------------------------- /Modules/CmdImproved/CmdImproved.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | static bool titleCommandCalled = false; 4 | static wchar_t overrideTitle[65536]; 5 | static wchar_t currentDirectory[65536]; 6 | 7 | HOOK(kernelbase.dll, BOOL WINAPI, SetCurrentDirectoryW)(__in LPCWSTR lpPathName) 8 | { 9 | dlogp("'%S' %d", lpPathName, titleCommandCalled); 10 | if (!titleCommandCalled) 11 | { 12 | auto newTitle = wcsrchr(lpPathName, L'\\'); 13 | newTitle = newTitle ? newTitle + 1 : lpPathName; 14 | wcsncpy_s(overrideTitle, newTitle, _TRUNCATE); 15 | dlogp("override title '%S'", newTitle); 16 | SetConsoleTitleW(overrideTitle); 17 | } 18 | return original_SetCurrentDirectoryW(lpPathName); 19 | } 20 | 21 | HOOK(kernelbase.dll, BOOL WINAPI, SetConsoleTitleW)(_In_ LPCWSTR lpConsoleTitle) 22 | { 23 | dlogp("old title '%S'", lpConsoleTitle); 24 | if (wcsstr(lpConsoleTitle, L" - title ")) 25 | titleCommandCalled = true; 26 | if (!titleCommandCalled) 27 | lpConsoleTitle = overrideTitle; 28 | dlogp("final title '%S'", lpConsoleTitle); 29 | return original_SetConsoleTitleW(lpConsoleTitle); 30 | } 31 | 32 | BOOL WINAPI DllMain( 33 | _In_ HINSTANCE hinstDLL, 34 | _In_ DWORD fdwReason, 35 | _In_ LPVOID lpvReserved 36 | ) 37 | { 38 | if (fdwReason == DLL_PROCESS_ATTACH) 39 | { 40 | dlogp("setting initial title"); 41 | if (GetCurrentDirectoryW(_countof(currentDirectory), currentDirectory)) 42 | SetCurrentDirectoryW(currentDirectory); 43 | } 44 | return HookDllMain(hinstDLL, fdwReason, lpvReserved); 45 | } -------------------------------------------------------------------------------- /CMake/AppInitHook-custom.cmake: -------------------------------------------------------------------------------- 1 | # Check if we're compiling with MSVC 2 | if(NOT MSVC) 3 | message(FATAL_ERROR "Non-MSVC compilers are not supported!") 4 | endif() 5 | 6 | # Fail when trying to compile to a path that contains spaces 7 | string(FIND "${PROJECT_BINARY_DIR}" " " SPACE_INDEX) 8 | if(NOT SPACE_INDEX STREQUAL "-1") 9 | message(FATAL_ERROR "Compiling in a path that contains spaces is not supported!") 10 | endif() 11 | 12 | # Build the register_AppInitDLL to register AppInitDispatcher.dll 13 | add_custom_target(register_AppInitDLLs 14 | COMMAND 15 | "${CMAKE_COMMAND}" --build "${PROJECT_BINARY_DIR}" --target AppInitDispatcher --config $ 16 | COMMAND 17 | "${CMAKE_COMMAND}" "-DAPPINITDISPATCHER_PATH=$" -DCMAKE_SIZEOF_VOID_P=${CMAKE_SIZEOF_VOID_P} -P "${CMAKE_CURRENT_SOURCE_DIR}/CMake/register_AppInitDLLs.cmake" 18 | SOURCES 19 | CMake/register_x64.reg.in 20 | CMake/register_x86.reg.in 21 | ) 22 | 23 | # Create a skeleton private module 24 | if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/Private") 25 | file( 26 | COPY "${CMAKE_CURRENT_SOURCE_DIR}/CMake/cmake.toml" 27 | DESTINATION "${CMAKE_CURRENT_SOURCE_DIR}/Private" 28 | ) 29 | file( 30 | COPY "${CMAKE_CURRENT_SOURCE_DIR}/Modules/AppInitExampleModule/AppInitExampleModule.cpp" 31 | DESTINATION "${CMAKE_CURRENT_SOURCE_DIR}/Private/MyPrivateModule" 32 | ) 33 | file(RENAME 34 | "${CMAKE_CURRENT_SOURCE_DIR}/Private/MyPrivateModule/AppInitExampleModule.cpp" 35 | "${CMAKE_CURRENT_SOURCE_DIR}/Private/MyPrivateModule/MyPrivateModule.cpp" 36 | ) 37 | endif() -------------------------------------------------------------------------------- /Libraries/MinHook/hde/pstdint.h: -------------------------------------------------------------------------------- 1 | /* 2 | * MinHook - The Minimalistic API Hooking Library for x64/x86 3 | * Copyright (C) 2009-2017 Tsuda Kageyu. All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions 7 | * are met: 8 | * 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR 16 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 17 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 18 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 19 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 20 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 21 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 22 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 24 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | */ 26 | 27 | #pragma once 28 | 29 | #include 30 | 31 | // Integer types for HDE. 32 | typedef INT8 int8_t; 33 | typedef INT16 int16_t; 34 | typedef INT32 int32_t; 35 | typedef INT64 int64_t; 36 | typedef UINT8 uint8_t; 37 | typedef UINT16 uint16_t; 38 | typedef UINT32 uint32_t; 39 | typedef UINT64 uint64_t; 40 | -------------------------------------------------------------------------------- /Modules/cmake.toml: -------------------------------------------------------------------------------- 1 | [target.AppInitExampleModule] 2 | type = "shared" 3 | sources = ["AppInitExampleModule/*.cpp", "AppInitExampleModule/*.hpp"] 4 | link-libraries = ["HookDll"] 5 | 6 | [target.clang-cl-hacks] 7 | type = "shared" 8 | sources = ["clang-cl-hacks/*.cpp", "clang-cl-hacks/*.hpp"] 9 | link-libraries = ["HookDll"] 10 | 11 | [target.CMakeClean] 12 | type = "shared" 13 | sources = ["CMakeClean/*.cpp", "CMakeClean/*.hpp"] 14 | link-libraries = ["HookDll"] 15 | 16 | [target.CmdImproved] 17 | type = "shared" 18 | sources = ["CmdImproved/*.cpp", "CmdImproved/*.hpp"] 19 | link-libraries = ["HookDll"] 20 | 21 | [target.ConhostLoader] 22 | type = "shared" 23 | sources = ["ConhostLoader/*.cpp", "ConhostLoader/*.hpp"] 24 | link-libraries = ["HookDll"] 25 | 26 | [target.ExitProcess] 27 | type = "shared" 28 | sources = ["ExitProcess/*.cpp", "ExitProcess/*.hpp"] 29 | link-libraries = ["HookDll"] 30 | 31 | [target.ForceQuit] 32 | type = "shared" 33 | sources = ["ForceQuit/*.cpp", "ForceQuit/*.hpp"] 34 | link-libraries = ["HookDll"] 35 | 36 | [target.GitMagic] 37 | type = "shared" 38 | sources = ["GitMagic/*.cpp", "GitMagic/*.hpp"] 39 | link-libraries = ["HookDll"] 40 | 41 | [target.HighPriority] 42 | type = "shared" 43 | sources = ["HighPriority/*.cpp", "HighPriority/*.hpp"] 44 | link-libraries = ["HookDll"] 45 | 46 | [target.NoSoftwareInventory] 47 | type = "shared" 48 | sources = ["NoSoftwareInventory/*.cpp", "NoSoftwareInventory/*.hpp"] 49 | link-libraries = ["HookDll"] 50 | 51 | [target.TotalCommander] 52 | type = "shared" 53 | sources = ["TotalCommander/*.cpp", "TotalCommander/*.hpp"] 54 | link-libraries = ["HookDll"] 55 | 56 | [target.WerfaultMagic] 57 | type = "shared" 58 | sources = ["WerfaultMagic/*.cpp", "WerfaultMagic/*.hpp"] 59 | link-libraries = ["HookDll"] 60 | 61 | [target.WowUndirect] 62 | type = "shared" 63 | sources = ["WowUndirect/*.cpp", "WowUndirect/*.hpp"] 64 | link-libraries = ["HookDll"] -------------------------------------------------------------------------------- /Libraries/MinHook/buffer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * MinHook - The Minimalistic API Hooking Library for x64/x86 3 | * Copyright (C) 2009-2017 Tsuda Kageyu. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18 | * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19 | * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20 | * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #pragma once 30 | 31 | // Size of each memory slot. 32 | #if defined(_M_X64) || defined(__x86_64__) 33 | #define MEMORY_SLOT_SIZE 64 34 | #else 35 | #define MEMORY_SLOT_SIZE 32 36 | #endif 37 | 38 | VOID InitializeBuffer(VOID); 39 | VOID UninitializeBuffer(VOID); 40 | LPVOID AllocateBuffer(LPVOID pOrigin); 41 | VOID FreeBuffer(LPVOID pBuffer); 42 | BOOL IsExecutableAddress(LPVOID pAddress); 43 | -------------------------------------------------------------------------------- /Libraries/HookDll/HookDll.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "ntdll/ntdll.h" 4 | #include "MinHook/MinHook.h" 5 | 6 | void dprintf(const char* format, ...); 7 | void dputs(const char* text); 8 | const char* modname(); 9 | 10 | // Call this from your DllMain to use the HOOK macros 11 | BOOL WINAPI HookDllMain( 12 | _In_ HINSTANCE hinstDLL, 13 | _In_ DWORD fdwReason, 14 | _In_ LPVOID lpvReserved 15 | ); 16 | 17 | struct Hook 18 | { 19 | const wchar_t* pszModule; 20 | const char* pszProcName; 21 | PVOID pDetour; 22 | PVOID* ppOriginal; 23 | }; 24 | 25 | #pragma section(".hooks$1",long,read) 26 | #pragma section(".hooks$2",long,read) 27 | #pragma section(".hooks$3",long,read) 28 | #pragma comment(linker, "/merge:hooks=.rdata") 29 | 30 | // Can's magic 31 | __declspec(allocate(".hooks$1")) const Hook hooks_begin; 32 | __declspec(allocate(".hooks$3")) const Hook hooks_end; 33 | 34 | // You likely forgot about WINAPI 35 | // error C2373: 'hook_Function': redefinition; different type modifiers 36 | #define HOOK(Dll, ReturnType, Function) \ 37 | static decltype(&Function) original_ ## Function; \ 38 | static decltype(Function) hook_ ## Function; \ 39 | extern "C" __declspec(allocate(".hooks$2")) Hook hookdata_ ## Function = { L ### Dll, #Function, hook_ ## Function, (LPVOID*)&original_ ## Function }; \ 40 | static ReturnType hook_ ## Function 41 | 42 | #define HOOK_ENTRYPOINT() \ 43 | int EntryPoint(); \ 44 | static decltype(&EntryPoint) original_EntryPoint; \ 45 | static decltype(EntryPoint) hook_EntryPoint; \ 46 | extern "C" __declspec(allocate(".hooks$2")) Hook hookdata_EntryPoint = { nullptr, nullptr, hook_ ## EntryPoint, (LPVOID*)&original_ ## EntryPoint }; \ 47 | static int hook_EntryPoint() 48 | 49 | template 50 | static MH_STATUS WINAPI MH_CreateHookApi(const wchar_t* pszModule, const char* pszProcName, Func* pDetour, Func*& ppOriginal) 51 | { 52 | return MH_CreateHookApi(pszModule, pszProcName, pDetour, (LPVOID*)&ppOriginal); 53 | } 54 | 55 | #define dlog() dprintf("[AppInitHook] [%s] [%u] " __FUNCTION__ "\n", modname(), GetCurrentProcessId()) 56 | #define dlogp(fmt, ...) dprintf("[AppInitHook] [%s] [%u] " __FUNCTION__ "(" fmt ")\n", modname(), GetCurrentProcessId(), __VA_ARGS__) -------------------------------------------------------------------------------- /Modules/ConhostLoader/ConhostLoader.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | static DWORD GetParentPid() 4 | { 5 | PROCESS_BASIC_INFORMATION pbi = { 0 }; 6 | ULONG size = 0; 7 | NtQueryInformationProcess(GetCurrentProcess(), ProcessBasicInformation, &pbi, sizeof(pbi), &size); 8 | return (DWORD)(UINT_PTR)pbi.InheritedFromUniqueProcessId; 9 | } 10 | 11 | BOOL WINAPI DllMain( 12 | _In_ HINSTANCE hinstDLL, 13 | _In_ DWORD fdwReason, 14 | _In_ LPVOID lpvReserved 15 | ) 16 | { 17 | if (fdwReason == DLL_PROCESS_ATTACH) 18 | { 19 | auto parentPid = GetParentPid(); 20 | dlogp("parent pid: %u", parentPid); 21 | auto hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, parentPid); 22 | if (hProcess) 23 | { 24 | BOOL wow64 = FALSE; 25 | IsWow64Process(hProcess, &wow64); 26 | dlogp("parent hprocess: %u, wow64: %d", (DWORD)(UINT_PTR)hProcess, wow64); 27 | if (!wow64) 28 | { 29 | auto pDllName = VirtualAllocEx(hProcess, nullptr, 0x1000, MEM_COMMIT, PAGE_READWRITE); 30 | if (pDllName) 31 | { 32 | dlogp("pDllName: 0x%p", pDllName); 33 | #ifdef _WIN64 34 | auto dllName = "AppInitHook_x64.dll"; 35 | #else 36 | auto dllName = "AppInitHook_x86.dll"; 37 | #endif //_WIN64 38 | SIZE_T written = 0; 39 | if (WriteProcessMemory(hProcess, pDllName, dllName, strlen(dllName), &written)) 40 | { 41 | dlogp("wrote dll name in parent"); 42 | auto hThread = CreateRemoteThread(hProcess, nullptr, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryA"), pDllName, 0, nullptr); 43 | if (hThread) 44 | { 45 | dlogp("injected parent"); 46 | CloseHandle(hThread); 47 | } 48 | else 49 | dlogp("failed to create thread in parent"); 50 | } 51 | else 52 | { 53 | dlogp("failed to write memory in parent"); 54 | } 55 | } 56 | else 57 | { 58 | dlogp("failed to allocate memory in parent"); 59 | } 60 | } 61 | else 62 | { 63 | dlogp("wow64 parent is not supported"); 64 | } 65 | CloseHandle(hProcess); 66 | } 67 | else 68 | { 69 | dlogp("failed to open parent process"); 70 | } 71 | } 72 | return FALSE; 73 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AppInitHook 2 | 3 | Global user-mode hooking framework, based on [AppInit_DLLs](https://docs.microsoft.com/en-nz/windows/win32/dlls/secure-boot-and-appinit-dlls). The goal is to allow you to rapidly develop hooks to inject in an arbitrary process. 4 | 5 | ## Building & Usage 6 | 7 | ```sh 8 | cmake -B build 9 | cmake --build build --config Release 10 | ``` 11 | 12 | Alternatively you can open this folder in a CMake-supported IDE (Visual Studio, CLion, Qt Creator, etc). 13 | 14 | The first time you use this framework you need to build and register `AppInitDispatcher.dll` in the `AppInitDLLs` registry key. You can do so by building the `register_AppInitDLLs` target. This will also create `AppInitHook.ini` in your build folder where you can customize which module gets loaded in which process: 15 | 16 | ```ini 17 | [TestLoader.exe] 18 | Module=ExitProcess.dll 19 | ``` 20 | 21 | Now if you run the `TestLoader` target you should see it exits immediately instead of showing a `Hello world!` message box. 22 | 23 | ## Debugging 24 | 25 | You can use [DebugView](https://docs.microsoft.com/en-us/sysinternals/downloads/debugview) with the filter `[AppInitHook]*` to see the `dlog` and `dlogp` messages, or you can break on DLL load of `AppInitDispatcher.dll` in [x64dbg](https://x64dbg.com). 26 | 27 | ## Developing modules 28 | 29 | The `AppInitExampleModule` hooks [SetCurrentDirectoryW](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setcurrentdirectory): 30 | 31 | ```cpp 32 | #include "HookDll.hpp" 33 | 34 | /* MSDN Signature: 35 | BOOL SetCurrentDirectory( 36 | LPCTSTR lpPathName 37 | ); 38 | */ 39 | HOOK(kernelbase.dll, BOOL WINAPI, SetCurrentDirectoryW)( 40 | LPCWSTR lpPathName 41 | ) 42 | { 43 | dlogp("'%S'", lpPathName); 44 | return original_SetCurrentDirectoryW(lpPathName); 45 | } 46 | 47 | BOOL WINAPI DllMain( 48 | _In_ HINSTANCE hinstDLL, 49 | _In_ DWORD fdwReason, 50 | _In_ LPVOID lpvReserved 51 | ) 52 | { 53 | return HookDllMain(hinstDLL, fdwReason, lpvReserved); 54 | } 55 | ``` 56 | 57 | For more examples you can check the `Modules` folder. 58 | 59 | ## Private Modules 60 | 61 | If you enable `-DAPPINITHOOK_PRIVATE_MODULES=ON` it will look for `Private/cmake.toml` where you can add your own modules: 62 | 63 | ```toml 64 | [target.MyPrivateModule] 65 | type = "shared" 66 | sources = ["MyPrivateModule/*.cpp", "MyPrivateModule/*.hpp"] 67 | link-libraries = ["HookDll"] 68 | ``` 69 | 70 | You can set up your own private git repository in this folder if you desire, since the folder is fully ignored by the `.gitignore` of this project. 71 | 72 | ## Credits 73 | 74 | - [MinHook](https://github.com/TsudaKageyu/minhook) by [Tsuda Kageyu](https://github.com/TsudaKageyu) 75 | - `ntdll.h` by [Matthijs Lavrijsen](https://github.com/Mattiwatti) 76 | - [Can Bölük](https://blog.can.ac) for helping with the `HOOK` macro 77 | -------------------------------------------------------------------------------- /Libraries/MinHook/hde/hde32.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Hacker Disassembler Engine 32 3 | * Copyright (c) 2006-2009, Vyacheslav Patkov. 4 | * All rights reserved. 5 | * 6 | * hde32.h: C/C++ header file 7 | * 8 | */ 9 | 10 | #ifndef _HDE32_H_ 11 | #define _HDE32_H_ 12 | 13 | /* stdint.h - C99 standard header 14 | * http://en.wikipedia.org/wiki/stdint.h 15 | * 16 | * if your compiler doesn't contain "stdint.h" header (for 17 | * example, Microsoft Visual C++), you can download file: 18 | * http://www.azillionmonkeys.com/qed/pstdint.h 19 | * and change next line to: 20 | * #include "pstdint.h" 21 | */ 22 | #include "pstdint.h" 23 | 24 | #define F_MODRM 0x00000001 25 | #define F_SIB 0x00000002 26 | #define F_IMM8 0x00000004 27 | #define F_IMM16 0x00000008 28 | #define F_IMM32 0x00000010 29 | #define F_DISP8 0x00000020 30 | #define F_DISP16 0x00000040 31 | #define F_DISP32 0x00000080 32 | #define F_RELATIVE 0x00000100 33 | #define F_2IMM16 0x00000800 34 | #define F_ERROR 0x00001000 35 | #define F_ERROR_OPCODE 0x00002000 36 | #define F_ERROR_LENGTH 0x00004000 37 | #define F_ERROR_LOCK 0x00008000 38 | #define F_ERROR_OPERAND 0x00010000 39 | #define F_PREFIX_REPNZ 0x01000000 40 | #define F_PREFIX_REPX 0x02000000 41 | #define F_PREFIX_REP 0x03000000 42 | #define F_PREFIX_66 0x04000000 43 | #define F_PREFIX_67 0x08000000 44 | #define F_PREFIX_LOCK 0x10000000 45 | #define F_PREFIX_SEG 0x20000000 46 | #define F_PREFIX_ANY 0x3f000000 47 | 48 | #define PREFIX_SEGMENT_CS 0x2e 49 | #define PREFIX_SEGMENT_SS 0x36 50 | #define PREFIX_SEGMENT_DS 0x3e 51 | #define PREFIX_SEGMENT_ES 0x26 52 | #define PREFIX_SEGMENT_FS 0x64 53 | #define PREFIX_SEGMENT_GS 0x65 54 | #define PREFIX_LOCK 0xf0 55 | #define PREFIX_REPNZ 0xf2 56 | #define PREFIX_REPX 0xf3 57 | #define PREFIX_OPERAND_SIZE 0x66 58 | #define PREFIX_ADDRESS_SIZE 0x67 59 | 60 | #pragma pack(push,1) 61 | 62 | typedef struct { 63 | uint8_t len; 64 | uint8_t p_rep; 65 | uint8_t p_lock; 66 | uint8_t p_seg; 67 | uint8_t p_66; 68 | uint8_t p_67; 69 | uint8_t opcode; 70 | uint8_t opcode2; 71 | uint8_t modrm; 72 | uint8_t modrm_mod; 73 | uint8_t modrm_reg; 74 | uint8_t modrm_rm; 75 | uint8_t sib; 76 | uint8_t sib_scale; 77 | uint8_t sib_index; 78 | uint8_t sib_base; 79 | union { 80 | uint8_t imm8; 81 | uint16_t imm16; 82 | uint32_t imm32; 83 | } imm; 84 | union { 85 | uint8_t disp8; 86 | uint16_t disp16; 87 | uint32_t disp32; 88 | } disp; 89 | uint32_t flags; 90 | } hde32s; 91 | 92 | #pragma pack(pop) 93 | 94 | #ifdef __cplusplus 95 | extern "C" { 96 | #endif 97 | 98 | /* __cdecl */ 99 | unsigned int hde32_disasm(const void *code, hde32s *hs); 100 | 101 | #ifdef __cplusplus 102 | } 103 | #endif 104 | 105 | #endif /* _HDE32_H_ */ 106 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file is automatically generated from cmake.toml - DO NOT EDIT 2 | # See https://github.com/build-cpp/cmkr for more information 3 | 4 | cmake_minimum_required(VERSION 3.15) 5 | 6 | if(CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR) 7 | message(FATAL_ERROR "In-tree builds are not supported. Run CMake from a separate directory: cmake -B build") 8 | endif() 9 | 10 | # Regenerate CMakeLists.txt automatically in the root project 11 | set(CMKR_ROOT_PROJECT OFF) 12 | if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) 13 | set(CMKR_ROOT_PROJECT ON) 14 | 15 | # Bootstrap cmkr 16 | include("CMake/cmkr.cmake" OPTIONAL RESULT_VARIABLE CMKR_INCLUDE_RESULT) 17 | if(CMKR_INCLUDE_RESULT) 18 | cmkr() 19 | endif() 20 | 21 | # Enable folder support 22 | set_property(GLOBAL PROPERTY USE_FOLDERS ON) 23 | endif() 24 | 25 | # Create a configure-time dependency on cmake.toml to improve IDE support 26 | if(CMKR_ROOT_PROJECT) 27 | configure_file(cmake.toml cmake.toml COPYONLY) 28 | endif() 29 | 30 | # Options 31 | option(APPINITHOOK_PRIVATE_MODULES "" ON) 32 | option(APPINITHOOK_UNLOAD_DISPATCHER "" ON) 33 | 34 | include("CMake/msvc-static-runtime.cmake") 35 | include("CMake/msvc-configurations.cmake") 36 | 37 | project(AppInitHook 38 | VERSION 39 | 0.1.0 40 | ) 41 | 42 | include("CMake/flatten-build-hierarchy.cmake") 43 | include("CMake/AppInitHook-custom.cmake") 44 | 45 | # Libraries 46 | set(CMKR_CMAKE_FOLDER ${CMAKE_FOLDER}) 47 | if(CMAKE_FOLDER) 48 | set(CMAKE_FOLDER "${CMAKE_FOLDER}/Libraries") 49 | else() 50 | set(CMAKE_FOLDER Libraries) 51 | endif() 52 | add_subdirectory(Libraries) 53 | set(CMAKE_FOLDER ${CMKR_CMAKE_FOLDER}) 54 | 55 | # Modules 56 | set(CMKR_CMAKE_FOLDER ${CMAKE_FOLDER}) 57 | if(CMAKE_FOLDER) 58 | set(CMAKE_FOLDER "${CMAKE_FOLDER}/Modules") 59 | else() 60 | set(CMAKE_FOLDER Modules) 61 | endif() 62 | add_subdirectory(Modules) 63 | set(CMAKE_FOLDER ${CMKR_CMAKE_FOLDER}) 64 | 65 | 66 | if(APPINITHOOK_PRIVATE_MODULES) # private 67 | # Private 68 | set(CMKR_CMAKE_FOLDER ${CMAKE_FOLDER}) 69 | if(CMAKE_FOLDER) 70 | set(CMAKE_FOLDER "${CMAKE_FOLDER}/Private") 71 | else() 72 | set(CMAKE_FOLDER Private) 73 | endif() 74 | add_subdirectory(Private) 75 | set(CMAKE_FOLDER ${CMKR_CMAKE_FOLDER}) 76 | 77 | endif() 78 | 79 | 80 | # Target TestLoader 81 | set(CMKR_TARGET TestLoader) 82 | set(TestLoader_SOURCES "") 83 | 84 | list(APPEND TestLoader_SOURCES 85 | "TestLoader/TestLoader.cpp" 86 | ) 87 | 88 | list(APPEND TestLoader_SOURCES 89 | cmake.toml 90 | ) 91 | 92 | set(CMKR_SOURCES ${TestLoader_SOURCES}) 93 | add_executable(TestLoader) 94 | 95 | if(TestLoader_SOURCES) 96 | target_sources(TestLoader PRIVATE ${TestLoader_SOURCES}) 97 | endif() 98 | 99 | get_directory_property(CMKR_VS_STARTUP_PROJECT DIRECTORY ${PROJECT_SOURCE_DIR} DEFINITION VS_STARTUP_PROJECT) 100 | if(NOT CMKR_VS_STARTUP_PROJECT) 101 | set_property(DIRECTORY ${PROJECT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT TestLoader) 102 | endif() 103 | 104 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${TestLoader_SOURCES}) 105 | 106 | unset(CMKR_TARGET) 107 | unset(CMKR_SOURCES) 108 | 109 | -------------------------------------------------------------------------------- /Libraries/MinHook/hde/hde64.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Hacker Disassembler Engine 64 3 | * Copyright (c) 2008-2009, Vyacheslav Patkov. 4 | * All rights reserved. 5 | * 6 | * hde64.h: C/C++ header file 7 | * 8 | */ 9 | 10 | #ifndef _HDE64_H_ 11 | #define _HDE64_H_ 12 | 13 | /* stdint.h - C99 standard header 14 | * http://en.wikipedia.org/wiki/stdint.h 15 | * 16 | * if your compiler doesn't contain "stdint.h" header (for 17 | * example, Microsoft Visual C++), you can download file: 18 | * http://www.azillionmonkeys.com/qed/pstdint.h 19 | * and change next line to: 20 | * #include "pstdint.h" 21 | */ 22 | #include "pstdint.h" 23 | 24 | #define F_MODRM 0x00000001 25 | #define F_SIB 0x00000002 26 | #define F_IMM8 0x00000004 27 | #define F_IMM16 0x00000008 28 | #define F_IMM32 0x00000010 29 | #define F_IMM64 0x00000020 30 | #define F_DISP8 0x00000040 31 | #define F_DISP16 0x00000080 32 | #define F_DISP32 0x00000100 33 | #define F_RELATIVE 0x00000200 34 | #define F_ERROR 0x00001000 35 | #define F_ERROR_OPCODE 0x00002000 36 | #define F_ERROR_LENGTH 0x00004000 37 | #define F_ERROR_LOCK 0x00008000 38 | #define F_ERROR_OPERAND 0x00010000 39 | #define F_PREFIX_REPNZ 0x01000000 40 | #define F_PREFIX_REPX 0x02000000 41 | #define F_PREFIX_REP 0x03000000 42 | #define F_PREFIX_66 0x04000000 43 | #define F_PREFIX_67 0x08000000 44 | #define F_PREFIX_LOCK 0x10000000 45 | #define F_PREFIX_SEG 0x20000000 46 | #define F_PREFIX_REX 0x40000000 47 | #define F_PREFIX_ANY 0x7f000000 48 | 49 | #define PREFIX_SEGMENT_CS 0x2e 50 | #define PREFIX_SEGMENT_SS 0x36 51 | #define PREFIX_SEGMENT_DS 0x3e 52 | #define PREFIX_SEGMENT_ES 0x26 53 | #define PREFIX_SEGMENT_FS 0x64 54 | #define PREFIX_SEGMENT_GS 0x65 55 | #define PREFIX_LOCK 0xf0 56 | #define PREFIX_REPNZ 0xf2 57 | #define PREFIX_REPX 0xf3 58 | #define PREFIX_OPERAND_SIZE 0x66 59 | #define PREFIX_ADDRESS_SIZE 0x67 60 | 61 | #pragma pack(push,1) 62 | 63 | typedef struct { 64 | uint8_t len; 65 | uint8_t p_rep; 66 | uint8_t p_lock; 67 | uint8_t p_seg; 68 | uint8_t p_66; 69 | uint8_t p_67; 70 | uint8_t rex; 71 | uint8_t rex_w; 72 | uint8_t rex_r; 73 | uint8_t rex_x; 74 | uint8_t rex_b; 75 | uint8_t opcode; 76 | uint8_t opcode2; 77 | uint8_t modrm; 78 | uint8_t modrm_mod; 79 | uint8_t modrm_reg; 80 | uint8_t modrm_rm; 81 | uint8_t sib; 82 | uint8_t sib_scale; 83 | uint8_t sib_index; 84 | uint8_t sib_base; 85 | union { 86 | uint8_t imm8; 87 | uint16_t imm16; 88 | uint32_t imm32; 89 | uint64_t imm64; 90 | } imm; 91 | union { 92 | uint8_t disp8; 93 | uint16_t disp16; 94 | uint32_t disp32; 95 | } disp; 96 | uint32_t flags; 97 | } hde64s; 98 | 99 | #pragma pack(pop) 100 | 101 | #ifdef __cplusplus 102 | extern "C" { 103 | #endif 104 | 105 | /* __cdecl */ 106 | unsigned int hde64_disasm(const void *code, hde64s *hs); 107 | 108 | #ifdef __cplusplus 109 | } 110 | #endif 111 | 112 | #endif /* _HDE64_H_ */ 113 | -------------------------------------------------------------------------------- /Libraries/MinHook/hde/table32.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Hacker Disassembler Engine 32 C 3 | * Copyright (c) 2008-2009, Vyacheslav Patkov. 4 | * All rights reserved. 5 | * 6 | */ 7 | 8 | #define C_NONE 0x00 9 | #define C_MODRM 0x01 10 | #define C_IMM8 0x02 11 | #define C_IMM16 0x04 12 | #define C_IMM_P66 0x10 13 | #define C_REL8 0x20 14 | #define C_REL32 0x40 15 | #define C_GROUP 0x80 16 | #define C_ERROR 0xff 17 | 18 | #define PRE_ANY 0x00 19 | #define PRE_NONE 0x01 20 | #define PRE_F2 0x02 21 | #define PRE_F3 0x04 22 | #define PRE_66 0x08 23 | #define PRE_67 0x10 24 | #define PRE_LOCK 0x20 25 | #define PRE_SEG 0x40 26 | #define PRE_ALL 0xff 27 | 28 | #define DELTA_OPCODES 0x4a 29 | #define DELTA_FPU_REG 0xf1 30 | #define DELTA_FPU_MODRM 0xf8 31 | #define DELTA_PREFIXES 0x130 32 | #define DELTA_OP_LOCK_OK 0x1a1 33 | #define DELTA_OP2_LOCK_OK 0x1b9 34 | #define DELTA_OP_ONLY_MEM 0x1cb 35 | #define DELTA_OP2_ONLY_MEM 0x1da 36 | 37 | unsigned char hde32_table[] = { 38 | 0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3, 39 | 0xa8,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xac,0xaa,0xb2,0xaa,0x9f,0x9f, 40 | 0x9f,0x9f,0xb5,0xa3,0xa3,0xa4,0xaa,0xaa,0xba,0xaa,0x96,0xaa,0xa8,0xaa,0xc3, 41 | 0xc3,0x96,0x96,0xb7,0xae,0xd6,0xbd,0xa3,0xc5,0xa3,0xa3,0x9f,0xc3,0x9c,0xaa, 42 | 0xaa,0xac,0xaa,0xbf,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0x90, 43 | 0x82,0x7d,0x97,0x59,0x59,0x59,0x59,0x59,0x7f,0x59,0x59,0x60,0x7d,0x7f,0x7f, 44 | 0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x9a,0x88,0x7d, 45 | 0x59,0x50,0x50,0x50,0x50,0x59,0x59,0x59,0x59,0x61,0x94,0x61,0x9e,0x59,0x59, 46 | 0x85,0x59,0x92,0xa3,0x60,0x60,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59, 47 | 0x59,0x59,0x9f,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xcc,0x01,0xbc,0x03,0xf0, 48 | 0x10,0x10,0x10,0x10,0x50,0x50,0x50,0x50,0x14,0x20,0x20,0x20,0x20,0x01,0x01, 49 | 0x01,0x01,0xc4,0x02,0x10,0x00,0x00,0x00,0x00,0x01,0x01,0xc0,0xc2,0x10,0x11, 50 | 0x02,0x03,0x11,0x03,0x03,0x04,0x00,0x00,0x14,0x00,0x02,0x00,0x00,0xc6,0xc8, 51 | 0x02,0x02,0x02,0x02,0x00,0x00,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0xca, 52 | 0x01,0x01,0x01,0x00,0x06,0x00,0x04,0x00,0xc0,0xc2,0x01,0x01,0x03,0x01,0xff, 53 | 0xff,0x01,0x00,0x03,0xc4,0xc4,0xc6,0x03,0x01,0x01,0x01,0xff,0x03,0x03,0x03, 54 | 0xc8,0x40,0x00,0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00, 55 | 0x00,0x00,0x00,0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00, 56 | 0x00,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 57 | 0x00,0xff,0xff,0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 58 | 0x7f,0x00,0x00,0xff,0x4a,0x4a,0x4a,0x4a,0x4b,0x52,0x4a,0x4a,0x4a,0x4a,0x4f, 59 | 0x4c,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x55,0x45,0x40,0x4a,0x4a,0x4a, 60 | 0x45,0x59,0x4d,0x46,0x4a,0x5d,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a, 61 | 0x4a,0x4a,0x4a,0x4a,0x4a,0x61,0x63,0x67,0x4e,0x4a,0x4a,0x6b,0x6d,0x4a,0x4a, 62 | 0x45,0x6d,0x4a,0x4a,0x44,0x45,0x4a,0x4a,0x00,0x00,0x00,0x02,0x0d,0x06,0x06, 63 | 0x06,0x06,0x0e,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x00,0x06,0x06,0x02,0x06, 64 | 0x00,0x0a,0x0a,0x07,0x07,0x06,0x02,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04, 65 | 0x04,0x04,0x00,0x00,0x00,0x0e,0x05,0x06,0x06,0x06,0x01,0x06,0x00,0x00,0x08, 66 | 0x00,0x10,0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01, 67 | 0x86,0x00,0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba, 68 | 0xf8,0xbb,0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00, 69 | 0xc4,0xff,0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00, 70 | 0x13,0x09,0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07, 71 | 0xb2,0xff,0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf, 72 | 0xe7,0x08,0x00,0xf0,0x02,0x00 73 | }; 74 | -------------------------------------------------------------------------------- /Modules/CMakeClean/CMakeClean.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | #include 4 | #include 5 | 6 | HOOK(Shell32.dll, HINSTANCE WINAPI, ShellExecuteA)( 7 | HWND hwnd, 8 | LPCSTR lpOperation, 9 | LPCSTR lpFile, 10 | LPCSTR lpParameters, 11 | LPCSTR lpDirectory, 12 | INT nShowCmd 13 | ) 14 | { 15 | dlogp("\"%s\"", lpFile); 16 | return original_ShellExecuteA(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd); 17 | } 18 | 19 | static bool FileExists(const wchar_t* szFileName) 20 | { 21 | return GetFileAttributesW(szFileName) != INVALID_FILE_ATTRIBUTES; 22 | }; 23 | 24 | static wchar_t szCurrentDirectory[MAX_PATH * 10]; 25 | 26 | HOOK_ENTRYPOINT() 27 | { 28 | dlog(); 29 | 30 | bool restoreCurrentDirectory = false; 31 | GetCurrentDirectoryW(_countof(szCurrentDirectory), szCurrentDirectory); 32 | 33 | auto commandLine = GetCommandLineW(); 34 | int argc = 0; 35 | auto argv = CommandLineToArgvW(commandLine, &argc); 36 | if (argv) 37 | { 38 | for (int i = 1; i < argc; i++) 39 | { 40 | auto arg = argv[i]; 41 | if (wcsstr(arg, L"-B") == arg) 42 | { 43 | const wchar_t* buildDir = nullptr; 44 | if (wcslen(arg) == 2) 45 | { 46 | buildDir = argv[i + 1]; 47 | } 48 | else if (i + 1 < argc) 49 | { 50 | buildDir = arg + 2; 51 | } 52 | 53 | if (buildDir != nullptr) 54 | { 55 | dlogp("SetCurrentDirectory: %S", buildDir); 56 | SetCurrentDirectoryW(buildDir); 57 | restoreCurrentDirectory = true; 58 | } 59 | } 60 | } 61 | LocalFree(argv); 62 | } 63 | { 64 | auto buildDir = wcsstr(commandLine, L"-B"); 65 | if (buildDir) 66 | { 67 | // Skip -B 68 | buildDir += 2; 69 | // Skip spaces 70 | while (*buildDir == L' ') 71 | buildDir++; 72 | } 73 | } 74 | 75 | if (wcsstr(commandLine, L" --clean")) 76 | { 77 | bool cacheDeleted = true; 78 | if (FileExists(L"CMakeCache.txt")) 79 | { 80 | if (system("del CMakeCache.txt > nul 2>&1") != 0) 81 | { 82 | cacheDeleted = false; 83 | puts("Failed to delete CMakeCache.txt"); 84 | } 85 | } 86 | bool filesDeleted = true; 87 | if (FileExists(L"CMakeFiles")) 88 | { 89 | if (system("rmdir /q /s CMakeFiles") != 0) 90 | { 91 | filesDeleted = false; 92 | } 93 | } 94 | return filesDeleted && cacheDeleted ? EXIT_SUCCESS : EXIT_FAILURE; 95 | } 96 | else if (wcsstr(commandLine, L"--clear")) 97 | { 98 | if (FileExists(L"CMakeCache.txt")) 99 | { 100 | // TODO: nicer error handling 101 | // Thanks to Jonas for the help with the command 102 | system("rmdir /s /q . > nul 2>&1 & dir /b"); 103 | } 104 | 105 | if (restoreCurrentDirectory) 106 | { 107 | // Remove the --clear flag and continue execution 108 | std::wstring cleanCommandLine(commandLine); 109 | auto clearIdx = cleanCommandLine.find(L"--clear"); 110 | auto hasSpace = cleanCommandLine.size() > clearIdx + 7 && cleanCommandLine[clearIdx + 7] == L' '; 111 | cleanCommandLine = cleanCommandLine.erase(clearIdx, 7 + hasSpace ? 1 : 0); 112 | dlogp("commandLine: %S", cleanCommandLine.c_str()); 113 | wcscpy(commandLine, cleanCommandLine.c_str()); 114 | } 115 | else 116 | { 117 | // Fini 118 | return 0; 119 | } 120 | } 121 | 122 | if (restoreCurrentDirectory) 123 | { 124 | SetCurrentDirectoryW(szCurrentDirectory); 125 | } 126 | 127 | return original_EntryPoint(); 128 | } 129 | 130 | BOOL WINAPI DllMain( 131 | _In_ HINSTANCE hinstDLL, 132 | _In_ DWORD fdwReason, 133 | _In_ LPVOID lpvReserved 134 | ) 135 | { 136 | return HookDllMain(hinstDLL, fdwReason, lpvReserved); 137 | } -------------------------------------------------------------------------------- /Libraries/MinHook/hde/table64.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Hacker Disassembler Engine 64 C 3 | * Copyright (c) 2008-2009, Vyacheslav Patkov. 4 | * All rights reserved. 5 | * 6 | */ 7 | 8 | #define C_NONE 0x00 9 | #define C_MODRM 0x01 10 | #define C_IMM8 0x02 11 | #define C_IMM16 0x04 12 | #define C_IMM_P66 0x10 13 | #define C_REL8 0x20 14 | #define C_REL32 0x40 15 | #define C_GROUP 0x80 16 | #define C_ERROR 0xff 17 | 18 | #define PRE_ANY 0x00 19 | #define PRE_NONE 0x01 20 | #define PRE_F2 0x02 21 | #define PRE_F3 0x04 22 | #define PRE_66 0x08 23 | #define PRE_67 0x10 24 | #define PRE_LOCK 0x20 25 | #define PRE_SEG 0x40 26 | #define PRE_ALL 0xff 27 | 28 | #define DELTA_OPCODES 0x4a 29 | #define DELTA_FPU_REG 0xfd 30 | #define DELTA_FPU_MODRM 0x104 31 | #define DELTA_PREFIXES 0x13c 32 | #define DELTA_OP_LOCK_OK 0x1ae 33 | #define DELTA_OP2_LOCK_OK 0x1c6 34 | #define DELTA_OP_ONLY_MEM 0x1d8 35 | #define DELTA_OP2_ONLY_MEM 0x1e7 36 | 37 | unsigned char hde64_table[] = { 38 | 0xa5,0xaa,0xa5,0xb8,0xa5,0xaa,0xa5,0xaa,0xa5,0xb8,0xa5,0xb8,0xa5,0xb8,0xa5, 39 | 0xb8,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xac,0xc0,0xcc,0xc0,0xa1,0xa1, 40 | 0xa1,0xa1,0xb1,0xa5,0xa5,0xa6,0xc0,0xc0,0xd7,0xda,0xe0,0xc0,0xe4,0xc0,0xea, 41 | 0xea,0xe0,0xe0,0x98,0xc8,0xee,0xf1,0xa5,0xd3,0xa5,0xa5,0xa1,0xea,0x9e,0xc0, 42 | 0xc0,0xc2,0xc0,0xe6,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0xab, 43 | 0x8b,0x90,0x64,0x5b,0x5b,0x5b,0x5b,0x5b,0x92,0x5b,0x5b,0x76,0x90,0x92,0x92, 44 | 0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x6a,0x73,0x90, 45 | 0x5b,0x52,0x52,0x52,0x52,0x5b,0x5b,0x5b,0x5b,0x77,0x7c,0x77,0x85,0x5b,0x5b, 46 | 0x70,0x5b,0x7a,0xaf,0x76,0x76,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b, 47 | 0x5b,0x5b,0x86,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xd5,0x03,0xcc,0x01,0xbc, 48 | 0x03,0xf0,0x03,0x03,0x04,0x00,0x50,0x50,0x50,0x50,0xff,0x20,0x20,0x20,0x20, 49 | 0x01,0x01,0x01,0x01,0xc4,0x02,0x10,0xff,0xff,0xff,0x01,0x00,0x03,0x11,0xff, 50 | 0x03,0xc4,0xc6,0xc8,0x02,0x10,0x00,0xff,0xcc,0x01,0x01,0x01,0x00,0x00,0x00, 51 | 0x00,0x01,0x01,0x03,0x01,0xff,0xff,0xc0,0xc2,0x10,0x11,0x02,0x03,0x01,0x01, 52 | 0x01,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0x00,0x00,0xff,0xff,0xff,0xff,0x10, 53 | 0x10,0x10,0x10,0x02,0x10,0x00,0x00,0xc6,0xc8,0x02,0x02,0x02,0x02,0x06,0x00, 54 | 0x04,0x00,0x02,0xff,0x00,0xc0,0xc2,0x01,0x01,0x03,0x03,0x03,0xca,0x40,0x00, 55 | 0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00,0x00,0x00,0x00, 56 | 0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0xff,0x00, 57 | 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff, 58 | 0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x00,0x00, 59 | 0xff,0x40,0x40,0x40,0x40,0x41,0x49,0x40,0x40,0x40,0x40,0x4c,0x42,0x40,0x40, 60 | 0x40,0x40,0x40,0x40,0x40,0x40,0x4f,0x44,0x53,0x40,0x40,0x40,0x44,0x57,0x43, 61 | 0x5c,0x40,0x60,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, 62 | 0x40,0x40,0x64,0x66,0x6e,0x6b,0x40,0x40,0x6a,0x46,0x40,0x40,0x44,0x46,0x40, 63 | 0x40,0x5b,0x44,0x40,0x40,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x01,0x06, 64 | 0x06,0x02,0x06,0x06,0x00,0x06,0x00,0x0a,0x0a,0x00,0x00,0x00,0x02,0x07,0x07, 65 | 0x06,0x02,0x0d,0x06,0x06,0x06,0x0e,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04, 66 | 0x04,0x04,0x05,0x06,0x06,0x06,0x00,0x00,0x00,0x0e,0x00,0x00,0x08,0x00,0x10, 67 | 0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01,0x86,0x00, 68 | 0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba,0xf8,0xbb, 69 | 0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00,0xc4,0xff, 70 | 0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00,0x13,0x09, 71 | 0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07,0xb2,0xff, 72 | 0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf,0xe7,0x08, 73 | 0x00,0xf0,0x02,0x00 74 | }; 75 | -------------------------------------------------------------------------------- /Libraries/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file is automatically generated from cmake.toml - DO NOT EDIT 2 | # See https://github.com/build-cpp/cmkr for more information 3 | 4 | # Create a configure-time dependency on cmake.toml to improve IDE support 5 | if(CMKR_ROOT_PROJECT) 6 | configure_file(cmake.toml cmake.toml COPYONLY) 7 | endif() 8 | 9 | # Target ntdll 10 | set(CMKR_TARGET ntdll) 11 | set(ntdll_SOURCES "") 12 | 13 | set(CMKR_SOURCES ${ntdll_SOURCES}) 14 | add_library(ntdll INTERFACE) 15 | 16 | if(ntdll_SOURCES) 17 | target_sources(ntdll INTERFACE ${ntdll_SOURCES}) 18 | endif() 19 | 20 | target_include_directories(ntdll INTERFACE 21 | ${CMAKE_CURRENT_SOURCE_DIR} 22 | ) 23 | 24 | target_link_directories(ntdll INTERFACE 25 | ntdll 26 | ) 27 | 28 | if(CMAKE_SIZEOF_VOID_P EQUAL 4) # x86 29 | target_link_libraries(ntdll INTERFACE 30 | ntdll_x86 31 | ) 32 | endif() 33 | 34 | if(CMAKE_SIZEOF_VOID_P EQUAL 8) # x64 35 | target_link_libraries(ntdll INTERFACE 36 | ntdll_x64 37 | ) 38 | endif() 39 | 40 | unset(CMKR_TARGET) 41 | unset(CMKR_SOURCES) 42 | 43 | # Target MinHook 44 | set(CMKR_TARGET MinHook) 45 | set(MinHook_SOURCES "") 46 | 47 | list(APPEND MinHook_SOURCES 48 | "MinHook/buffer.c" 49 | "MinHook/hde/hde32.c" 50 | "MinHook/hde/hde64.c" 51 | "MinHook/hook.c" 52 | "MinHook/trampoline.c" 53 | "MinHook/MinHook.h" 54 | "MinHook/buffer.h" 55 | "MinHook/hde/hde32.h" 56 | "MinHook/hde/hde64.h" 57 | "MinHook/hde/pstdint.h" 58 | "MinHook/hde/table32.h" 59 | "MinHook/hde/table64.h" 60 | "MinHook/trampoline.h" 61 | ) 62 | 63 | list(APPEND MinHook_SOURCES 64 | cmake.toml 65 | ) 66 | 67 | set(CMKR_SOURCES ${MinHook_SOURCES}) 68 | add_library(MinHook STATIC) 69 | 70 | if(MinHook_SOURCES) 71 | target_sources(MinHook PRIVATE ${MinHook_SOURCES}) 72 | endif() 73 | 74 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${MinHook_SOURCES}) 75 | 76 | target_include_directories(MinHook PUBLIC 77 | ${CMAKE_CURRENT_SOURCE_DIR} 78 | ) 79 | 80 | unset(CMKR_TARGET) 81 | unset(CMKR_SOURCES) 82 | 83 | # Target HookDll 84 | set(CMKR_TARGET HookDll) 85 | set(HookDll_SOURCES "") 86 | 87 | list(APPEND HookDll_SOURCES 88 | "HookDll/HookDll.cpp" 89 | "HookDll/HookDll.hpp" 90 | "ntdll/ntdll.h" 91 | ) 92 | 93 | list(APPEND HookDll_SOURCES 94 | cmake.toml 95 | ) 96 | 97 | set(CMKR_SOURCES ${HookDll_SOURCES}) 98 | add_library(HookDll STATIC) 99 | 100 | if(HookDll_SOURCES) 101 | target_sources(HookDll PRIVATE ${HookDll_SOURCES}) 102 | endif() 103 | 104 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${HookDll_SOURCES}) 105 | 106 | target_include_directories(HookDll PUBLIC 107 | HookDll 108 | ) 109 | 110 | target_link_libraries(HookDll PUBLIC 111 | ntdll 112 | MinHook 113 | ) 114 | 115 | unset(CMKR_TARGET) 116 | unset(CMKR_SOURCES) 117 | 118 | # Target AppInitDispatcher 119 | set(CMKR_TARGET AppInitDispatcher) 120 | set(AppInitDispatcher_SOURCES "") 121 | 122 | list(APPEND AppInitDispatcher_SOURCES 123 | "AppInitDispatcher/AppInitDispatcher.cpp" 124 | "AppInitDispatcher/Utf8Ini.hpp" 125 | ) 126 | 127 | list(APPEND AppInitDispatcher_SOURCES 128 | cmake.toml 129 | ) 130 | 131 | set(CMKR_SOURCES ${AppInitDispatcher_SOURCES}) 132 | add_library(AppInitDispatcher SHARED) 133 | 134 | if(AppInitDispatcher_SOURCES) 135 | target_sources(AppInitDispatcher PRIVATE ${AppInitDispatcher_SOURCES}) 136 | endif() 137 | 138 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${AppInitDispatcher_SOURCES}) 139 | 140 | if(APPINITHOOK_UNLOAD_DISPATCHER) # unload-dispatcher 141 | target_compile_definitions(AppInitDispatcher PUBLIC 142 | UNLOAD_DISPATCHER 143 | ) 144 | endif() 145 | 146 | target_link_libraries(AppInitDispatcher PUBLIC 147 | HookDll 148 | ) 149 | 150 | set_target_properties(AppInitDispatcher PROPERTIES 151 | EXCLUDE_FROM_DEFAULT_BUILD 152 | TRUE 153 | ) 154 | 155 | unset(CMKR_TARGET) 156 | unset(CMKR_SOURCES) 157 | 158 | -------------------------------------------------------------------------------- /Libraries/HookDll/HookDll.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | // Empty export to allow adding this DLL to the IAT 8 | extern "C" __declspec(dllexport) void inject() { } 9 | 10 | void dprintf(const char* format, ...) 11 | { 12 | static char dprintf_msg[66000]; 13 | va_list args; 14 | va_start(args, format); 15 | *dprintf_msg = 0; 16 | auto len = vsnprintf_s(dprintf_msg, sizeof(dprintf_msg), format, args); 17 | for (; len > 1; len--) 18 | { 19 | auto& ch = dprintf_msg[len - 1]; 20 | if (ch == '\r' || ch == '\n') 21 | ch = '\0'; 22 | else 23 | break; 24 | } 25 | OutputDebugStringA(dprintf_msg); 26 | } 27 | 28 | void dputs(const char* text) 29 | { 30 | dprintf("%s\n", text); 31 | } 32 | 33 | extern "C" IMAGE_DOS_HEADER __ImageBase; 34 | 35 | const char* modname() 36 | { 37 | static char szModuleName[MAX_PATH]; 38 | if (*szModuleName == '\0') 39 | { 40 | GetModuleFileNameA((HMODULE)&__ImageBase, szModuleName, _countof(szModuleName)); 41 | auto backslash = strrchr(szModuleName, '\\'); 42 | if (backslash) 43 | { 44 | backslash++; 45 | memmove(szModuleName, backslash, strlen(backslash) + 1); 46 | auto period = strrchr(szModuleName, '.'); 47 | if (period) 48 | { 49 | *period = L'\0'; 50 | } 51 | } 52 | } 53 | return szModuleName; 54 | } 55 | 56 | // Call this from your DllMain to use the HOOK macros 57 | BOOL WINAPI HookDllMain( 58 | _In_ HINSTANCE hinstDLL, 59 | _In_ DWORD fdwReason, 60 | _In_ LPVOID lpvReserved 61 | ) 62 | { 63 | if (fdwReason == DLL_PROCESS_ATTACH) 64 | { 65 | auto initStatus = MH_Initialize(); 66 | if (initStatus != MH_OK) 67 | { 68 | dlogp("MH_Initialize failed, status: %s", MH_StatusToString(initStatus)); 69 | return FALSE; 70 | } 71 | int hooksInstalled = 0; 72 | for (auto hook = std::next(&hooks_begin); hook != &hooks_end; ++hook, hooksInstalled++) 73 | { 74 | if (hook->pszModule == nullptr && hook->pszProcName == nullptr) 75 | { 76 | void* entryPoint = nullptr; 77 | auto base = (char*)GetModuleHandleW(nullptr); 78 | auto pdh = PIMAGE_DOS_HEADER(base); 79 | if (pdh->e_magic == IMAGE_DOS_SIGNATURE) 80 | { 81 | auto pnth = PIMAGE_NT_HEADERS(base + pdh->e_lfanew); 82 | if (pnth->Signature == IMAGE_NT_SIGNATURE) 83 | { 84 | if (pnth->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR_MAGIC) 85 | { 86 | entryPoint = base + pnth->OptionalHeader.AddressOfEntryPoint; 87 | } 88 | } 89 | 90 | } 91 | if (entryPoint == nullptr) 92 | { 93 | dlogp("Failed to get entry point"); 94 | return FALSE; 95 | } 96 | auto hookStatus = MH_CreateHook(entryPoint, hook->pDetour, hook->ppOriginal); 97 | if (hookStatus != MH_OK) 98 | { 99 | dlogp("Failed to hook EntryPoint 0x%p, status: %s", entryPoint, MH_StatusToString(hookStatus)); 100 | return FALSE; 101 | } 102 | else 103 | { 104 | dlogp("Hooked EntryPoint 0x%p", entryPoint); 105 | } 106 | } 107 | else 108 | { 109 | auto hookStatus = MH_CreateHookApi(hook->pszModule, hook->pszProcName, hook->pDetour, hook->ppOriginal); 110 | if (hookStatus != MH_OK) 111 | { 112 | dlogp("Failed to hook %S:%s, status: %s", hook->pszModule, hook->pszProcName, MH_StatusToString(hookStatus)); 113 | return FALSE; 114 | } 115 | else 116 | { 117 | dlogp("Hooked %S:%s", hook->pszModule, hook->pszProcName); 118 | } 119 | } 120 | } 121 | if (hooksInstalled > 0) 122 | { 123 | auto enableStatus = MH_EnableHook(MH_ALL_HOOKS); 124 | if (enableStatus != MH_OK) 125 | { 126 | dlogp("MH_EnableHook failed, status: %s", MH_StatusToString(enableStatus)); 127 | return FALSE; 128 | } 129 | } 130 | } 131 | return TRUE; 132 | } -------------------------------------------------------------------------------- /Libraries/AppInitDispatcher/AppInitDispatcher.cpp: -------------------------------------------------------------------------------- 1 | #include "HookDll.hpp" 2 | #include "Utf8Ini.hpp" 3 | 4 | static std::string Utf16ToUtf8(const wchar_t* wstr) 5 | { 6 | std::string convertedString; 7 | if (!wstr || !*wstr) 8 | return convertedString; 9 | auto requiredSize = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, nullptr, 0, nullptr, nullptr); 10 | if (requiredSize > 0) 11 | { 12 | convertedString.resize(requiredSize - 1); 13 | if (!WideCharToMultiByte(CP_UTF8, 0, wstr, -1, (char*)convertedString.c_str(), requiredSize, nullptr, nullptr)) 14 | convertedString.clear(); 15 | } 16 | return convertedString; 17 | } 18 | 19 | static std::wstring Utf8ToUtf16(const char* str) 20 | { 21 | std::wstring convertedString; 22 | if (!str || !*str) 23 | return convertedString; 24 | int requiredSize = MultiByteToWideChar(CP_UTF8, 0, str, -1, nullptr, 0); 25 | if (requiredSize > 0) 26 | { 27 | convertedString.resize(requiredSize - 1); 28 | if (!MultiByteToWideChar(CP_UTF8, 0, str, -1, (wchar_t*)convertedString.c_str(), requiredSize)) 29 | convertedString.clear(); 30 | } 31 | return convertedString; 32 | } 33 | 34 | BOOL WINAPI DllMain( 35 | _In_ HINSTANCE hinstDLL, 36 | _In_ DWORD fdwReason, 37 | _In_ LPVOID lpvReserved 38 | ) 39 | { 40 | if (fdwReason == DLL_PROCESS_ATTACH) 41 | { 42 | dlog(); 43 | wchar_t szDllPath[MAX_PATH] = L""; 44 | GetModuleFileNameW(hinstDLL, szDllPath, _countof(szDllPath)); 45 | { 46 | auto p = wcsrchr(szDllPath, L'\\'); 47 | if (!p) 48 | { 49 | dlogp("Failed to get settings path"); 50 | return FALSE; 51 | } 52 | *p = L'\0'; 53 | } 54 | 55 | wchar_t szIniPath[MAX_PATH] = L""; 56 | wcsncpy_s(szIniPath, szDllPath, _TRUNCATE); 57 | wcsncat_s(szIniPath, L"\\AppInitHook.ini", _TRUNCATE); 58 | dlogp("Settings: '%S'", szIniPath); 59 | 60 | std::string processName; 61 | { 62 | wchar_t szProcessPath[MAX_PATH] = L""; 63 | GetModuleFileNameW(GetModuleHandleW(nullptr), szProcessPath, _countof(szProcessPath)); 64 | auto p = wcsrchr(szProcessPath, L'\\'); 65 | if (!p) 66 | { 67 | dlogp("Failed to get process path"); 68 | return FALSE; 69 | } 70 | processName = Utf16ToUtf8(p + 1); 71 | for (auto& ch : processName) 72 | ch = tolower(ch); 73 | } 74 | dlogp("Process: '%s'", processName.c_str()); 75 | 76 | Utf8Ini ini; 77 | auto hFile = CreateFileW(szIniPath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); 78 | if (hFile != INVALID_HANDLE_VALUE) 79 | { 80 | std::string data; 81 | data.resize(GetFileSize(hFile, nullptr)); 82 | DWORD read = 0; 83 | if (ReadFile(hFile, (void*)data.data(), (DWORD)data.size(), &read, nullptr)) 84 | { 85 | int errorLine = 0; 86 | if (!ini.Deserialize(data, errorLine)) 87 | { 88 | dlogp("Utf8Ini::Deserialize failed"); 89 | ini.Clear(); 90 | } 91 | else 92 | { 93 | dlogp("Settings deserialized"); 94 | } 95 | 96 | } 97 | else 98 | { 99 | dlogp("Failed to read settings"); 100 | } 101 | CloseHandle(hFile); 102 | } 103 | else 104 | { 105 | dlogp("Failed to open settings"); 106 | } 107 | auto dllToLoad = Utf8ToUtf16(ini.GetValue(processName, "Module").c_str()); 108 | if (!dllToLoad.empty()) 109 | { 110 | if (dllToLoad.find_first_of('\\') == std::wstring::npos) 111 | { 112 | dllToLoad = szDllPath + (L"\\" + dllToLoad); 113 | } 114 | dlogp("dllToLoad: '%S'", dllToLoad.c_str()); 115 | if (LoadLibraryW(dllToLoad.c_str())) 116 | { 117 | dlogp("Successfully loaded module"); 118 | } 119 | else 120 | { 121 | dlogp("Failed to load module"); 122 | } 123 | } 124 | else 125 | { 126 | dlogp("No module to load for this process"); 127 | } 128 | } 129 | 130 | #ifdef UNLOAD_DISPATCHER 131 | return FALSE; 132 | #else 133 | return TRUE; 134 | #endif // UNLOAD_DISPATCHER 135 | } -------------------------------------------------------------------------------- /Libraries/MinHook/trampoline.h: -------------------------------------------------------------------------------- 1 | /* 2 | * MinHook - The Minimalistic API Hooking Library for x64/x86 3 | * Copyright (C) 2009-2017 Tsuda Kageyu. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18 | * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19 | * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20 | * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #pragma once 30 | 31 | #pragma pack(push, 1) 32 | 33 | // Structs for writing x86/x64 instructions. 34 | 35 | // 8-bit relative jump. 36 | typedef struct _JMP_REL_SHORT 37 | { 38 | UINT8 opcode; // EB xx: JMP +2+xx 39 | UINT8 operand; 40 | } JMP_REL_SHORT, *PJMP_REL_SHORT; 41 | 42 | // 32-bit direct relative jump/call. 43 | typedef struct _JMP_REL 44 | { 45 | UINT8 opcode; // E9/E8 xxxxxxxx: JMP/CALL +5+xxxxxxxx 46 | UINT32 operand; // Relative destination address 47 | } JMP_REL, *PJMP_REL, CALL_REL; 48 | 49 | // 64-bit indirect absolute jump. 50 | typedef struct _JMP_ABS 51 | { 52 | UINT8 opcode0; // FF25 00000000: JMP [+6] 53 | UINT8 opcode1; 54 | UINT32 dummy; 55 | UINT64 address; // Absolute destination address 56 | } JMP_ABS, *PJMP_ABS; 57 | 58 | // 64-bit indirect absolute call. 59 | typedef struct _CALL_ABS 60 | { 61 | UINT8 opcode0; // FF15 00000002: CALL [+6] 62 | UINT8 opcode1; 63 | UINT32 dummy0; 64 | UINT8 dummy1; // EB 08: JMP +10 65 | UINT8 dummy2; 66 | UINT64 address; // Absolute destination address 67 | } CALL_ABS; 68 | 69 | // 32-bit direct relative conditional jumps. 70 | typedef struct _JCC_REL 71 | { 72 | UINT8 opcode0; // 0F8* xxxxxxxx: J** +6+xxxxxxxx 73 | UINT8 opcode1; 74 | UINT32 operand; // Relative destination address 75 | } JCC_REL; 76 | 77 | // 64bit indirect absolute conditional jumps that x64 lacks. 78 | typedef struct _JCC_ABS 79 | { 80 | UINT8 opcode; // 7* 0E: J** +16 81 | UINT8 dummy0; 82 | UINT8 dummy1; // FF25 00000000: JMP [+6] 83 | UINT8 dummy2; 84 | UINT32 dummy3; 85 | UINT64 address; // Absolute destination address 86 | } JCC_ABS; 87 | 88 | #pragma pack(pop) 89 | 90 | typedef struct _TRAMPOLINE 91 | { 92 | LPVOID pTarget; // [In] Address of the target function. 93 | LPVOID pDetour; // [In] Address of the detour function. 94 | LPVOID pTrampoline; // [In] Buffer address for the trampoline and relay function. 95 | 96 | #if defined(_M_X64) || defined(__x86_64__) 97 | LPVOID pRelay; // [Out] Address of the relay function. 98 | #endif 99 | BOOL patchAbove; // [Out] Should use the hot patch area? 100 | UINT nIP; // [Out] Number of the instruction boundaries. 101 | UINT8 oldIPs[8]; // [Out] Instruction boundaries of the target function. 102 | UINT8 newIPs[8]; // [Out] Instruction boundaries of the trampoline function. 103 | } TRAMPOLINE, *PTRAMPOLINE; 104 | 105 | BOOL CreateTrampolineFunction(PTRAMPOLINE ct); 106 | -------------------------------------------------------------------------------- /Libraries/MinHook/MinHook.h: -------------------------------------------------------------------------------- 1 | /* 2 | * MinHook - The Minimalistic API Hooking Library for x64/x86 3 | * Copyright (C) 2009-2017 Tsuda Kageyu. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18 | * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19 | * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20 | * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #pragma once 30 | 31 | #if !(defined _M_IX86) && !(defined _M_X64) && !(defined __i386__) && !(defined __x86_64__) 32 | #error MinHook supports only x86 and x64 systems. 33 | #endif 34 | 35 | #include 36 | 37 | // MinHook Error Codes. 38 | typedef enum MH_STATUS 39 | { 40 | // Unknown error. Should not be returned. 41 | MH_UNKNOWN = -1, 42 | 43 | // Successful. 44 | MH_OK = 0, 45 | 46 | // MinHook is already initialized. 47 | MH_ERROR_ALREADY_INITIALIZED, 48 | 49 | // MinHook is not initialized yet, or already uninitialized. 50 | MH_ERROR_NOT_INITIALIZED, 51 | 52 | // The hook for the specified target function is already created. 53 | MH_ERROR_ALREADY_CREATED, 54 | 55 | // The hook for the specified target function is not created yet. 56 | MH_ERROR_NOT_CREATED, 57 | 58 | // The hook for the specified target function is already enabled. 59 | MH_ERROR_ENABLED, 60 | 61 | // The hook for the specified target function is not enabled yet, or already 62 | // disabled. 63 | MH_ERROR_DISABLED, 64 | 65 | // The specified pointer is invalid. It points the address of non-allocated 66 | // and/or non-executable region. 67 | MH_ERROR_NOT_EXECUTABLE, 68 | 69 | // The specified target function cannot be hooked. 70 | MH_ERROR_UNSUPPORTED_FUNCTION, 71 | 72 | // Failed to allocate memory. 73 | MH_ERROR_MEMORY_ALLOC, 74 | 75 | // Failed to change the memory protection. 76 | MH_ERROR_MEMORY_PROTECT, 77 | 78 | // The specified module is not loaded. 79 | MH_ERROR_MODULE_NOT_FOUND, 80 | 81 | // The specified function is not found. 82 | MH_ERROR_FUNCTION_NOT_FOUND 83 | } 84 | MH_STATUS; 85 | 86 | // Can be passed as a parameter to MH_EnableHook, MH_DisableHook, 87 | // MH_QueueEnableHook or MH_QueueDisableHook. 88 | #define MH_ALL_HOOKS NULL 89 | 90 | #ifdef __cplusplus 91 | extern "C" { 92 | #endif 93 | 94 | // Initialize the MinHook library. You must call this function EXACTLY ONCE 95 | // at the beginning of your program. 96 | MH_STATUS WINAPI MH_Initialize(VOID); 97 | 98 | // Uninitialize the MinHook library. You must call this function EXACTLY 99 | // ONCE at the end of your program. 100 | MH_STATUS WINAPI MH_Uninitialize(VOID); 101 | 102 | // Creates a Hook for the specified target function, in disabled state. 103 | // Parameters: 104 | // pTarget [in] A pointer to the target function, which will be 105 | // overridden by the detour function. 106 | // pDetour [in] A pointer to the detour function, which will override 107 | // the target function. 108 | // ppOriginal [out] A pointer to the trampoline function, which will be 109 | // used to call the original target function. 110 | // This parameter can be NULL. 111 | MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal); 112 | 113 | // Creates a Hook for the specified API function, in disabled state. 114 | // Parameters: 115 | // pszModule [in] A pointer to the loaded module name which contains the 116 | // target function. 117 | // pszTarget [in] A pointer to the target function name, which will be 118 | // overridden by the detour function. 119 | // pDetour [in] A pointer to the detour function, which will override 120 | // the target function. 121 | // ppOriginal [out] A pointer to the trampoline function, which will be 122 | // used to call the original target function. 123 | // This parameter can be NULL. 124 | MH_STATUS WINAPI MH_CreateHookApi( 125 | LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal); 126 | 127 | // Creates a Hook for the specified API function, in disabled state. 128 | // Parameters: 129 | // pszModule [in] A pointer to the loaded module name which contains the 130 | // target function. 131 | // pszTarget [in] A pointer to the target function name, which will be 132 | // overridden by the detour function. 133 | // pDetour [in] A pointer to the detour function, which will override 134 | // the target function. 135 | // ppOriginal [out] A pointer to the trampoline function, which will be 136 | // used to call the original target function. 137 | // This parameter can be NULL. 138 | // ppTarget [out] A pointer to the target function, which will be used 139 | // with other functions. 140 | // This parameter can be NULL. 141 | MH_STATUS WINAPI MH_CreateHookApiEx( 142 | LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget); 143 | 144 | // Removes an already created hook. 145 | // Parameters: 146 | // pTarget [in] A pointer to the target function. 147 | MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget); 148 | 149 | // Enables an already created hook. 150 | // Parameters: 151 | // pTarget [in] A pointer to the target function. 152 | // If this parameter is MH_ALL_HOOKS, all created hooks are 153 | // enabled in one go. 154 | MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget); 155 | 156 | // Disables an already created hook. 157 | // Parameters: 158 | // pTarget [in] A pointer to the target function. 159 | // If this parameter is MH_ALL_HOOKS, all created hooks are 160 | // disabled in one go. 161 | MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget); 162 | 163 | // Queues to enable an already created hook. 164 | // Parameters: 165 | // pTarget [in] A pointer to the target function. 166 | // If this parameter is MH_ALL_HOOKS, all created hooks are 167 | // queued to be enabled. 168 | MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget); 169 | 170 | // Queues to disable an already created hook. 171 | // Parameters: 172 | // pTarget [in] A pointer to the target function. 173 | // If this parameter is MH_ALL_HOOKS, all created hooks are 174 | // queued to be disabled. 175 | MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget); 176 | 177 | // Applies all queued changes in one go. 178 | MH_STATUS WINAPI MH_ApplyQueued(VOID); 179 | 180 | // Translates the MH_STATUS to its name as a string. 181 | const char * WINAPI MH_StatusToString(MH_STATUS status); 182 | 183 | #ifdef __cplusplus 184 | } 185 | #endif 186 | 187 | -------------------------------------------------------------------------------- /Modules/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file is automatically generated from cmake.toml - DO NOT EDIT 2 | # See https://github.com/build-cpp/cmkr for more information 3 | 4 | # Create a configure-time dependency on cmake.toml to improve IDE support 5 | if(CMKR_ROOT_PROJECT) 6 | configure_file(cmake.toml cmake.toml COPYONLY) 7 | endif() 8 | 9 | # Target AppInitExampleModule 10 | set(CMKR_TARGET AppInitExampleModule) 11 | set(AppInitExampleModule_SOURCES "") 12 | 13 | list(APPEND AppInitExampleModule_SOURCES 14 | "AppInitExampleModule/AppInitExampleModule.cpp" 15 | ) 16 | 17 | list(APPEND AppInitExampleModule_SOURCES 18 | cmake.toml 19 | ) 20 | 21 | set(CMKR_SOURCES ${AppInitExampleModule_SOURCES}) 22 | add_library(AppInitExampleModule SHARED) 23 | 24 | if(AppInitExampleModule_SOURCES) 25 | target_sources(AppInitExampleModule PRIVATE ${AppInitExampleModule_SOURCES}) 26 | endif() 27 | 28 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${AppInitExampleModule_SOURCES}) 29 | 30 | target_link_libraries(AppInitExampleModule PUBLIC 31 | HookDll 32 | ) 33 | 34 | unset(CMKR_TARGET) 35 | unset(CMKR_SOURCES) 36 | 37 | # Target clang-cl-hacks 38 | set(CMKR_TARGET clang-cl-hacks) 39 | set(clang-cl-hacks_SOURCES "") 40 | 41 | list(APPEND clang-cl-hacks_SOURCES 42 | "clang-cl-hacks/clang-cl-hacks.cpp" 43 | ) 44 | 45 | list(APPEND clang-cl-hacks_SOURCES 46 | cmake.toml 47 | ) 48 | 49 | set(CMKR_SOURCES ${clang-cl-hacks_SOURCES}) 50 | add_library(clang-cl-hacks SHARED) 51 | 52 | if(clang-cl-hacks_SOURCES) 53 | target_sources(clang-cl-hacks PRIVATE ${clang-cl-hacks_SOURCES}) 54 | endif() 55 | 56 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${clang-cl-hacks_SOURCES}) 57 | 58 | target_link_libraries(clang-cl-hacks PUBLIC 59 | HookDll 60 | ) 61 | 62 | unset(CMKR_TARGET) 63 | unset(CMKR_SOURCES) 64 | 65 | # Target CMakeClean 66 | set(CMKR_TARGET CMakeClean) 67 | set(CMakeClean_SOURCES "") 68 | 69 | list(APPEND CMakeClean_SOURCES 70 | "CMakeClean/CMakeClean.cpp" 71 | ) 72 | 73 | list(APPEND CMakeClean_SOURCES 74 | cmake.toml 75 | ) 76 | 77 | set(CMKR_SOURCES ${CMakeClean_SOURCES}) 78 | add_library(CMakeClean SHARED) 79 | 80 | if(CMakeClean_SOURCES) 81 | target_sources(CMakeClean PRIVATE ${CMakeClean_SOURCES}) 82 | endif() 83 | 84 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${CMakeClean_SOURCES}) 85 | 86 | target_link_libraries(CMakeClean PUBLIC 87 | HookDll 88 | ) 89 | 90 | unset(CMKR_TARGET) 91 | unset(CMKR_SOURCES) 92 | 93 | # Target CmdImproved 94 | set(CMKR_TARGET CmdImproved) 95 | set(CmdImproved_SOURCES "") 96 | 97 | list(APPEND CmdImproved_SOURCES 98 | "CmdImproved/CmdImproved.cpp" 99 | ) 100 | 101 | list(APPEND CmdImproved_SOURCES 102 | cmake.toml 103 | ) 104 | 105 | set(CMKR_SOURCES ${CmdImproved_SOURCES}) 106 | add_library(CmdImproved SHARED) 107 | 108 | if(CmdImproved_SOURCES) 109 | target_sources(CmdImproved PRIVATE ${CmdImproved_SOURCES}) 110 | endif() 111 | 112 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${CmdImproved_SOURCES}) 113 | 114 | target_link_libraries(CmdImproved PUBLIC 115 | HookDll 116 | ) 117 | 118 | unset(CMKR_TARGET) 119 | unset(CMKR_SOURCES) 120 | 121 | # Target ConhostLoader 122 | set(CMKR_TARGET ConhostLoader) 123 | set(ConhostLoader_SOURCES "") 124 | 125 | list(APPEND ConhostLoader_SOURCES 126 | "ConhostLoader/ConhostLoader.cpp" 127 | ) 128 | 129 | list(APPEND ConhostLoader_SOURCES 130 | cmake.toml 131 | ) 132 | 133 | set(CMKR_SOURCES ${ConhostLoader_SOURCES}) 134 | add_library(ConhostLoader SHARED) 135 | 136 | if(ConhostLoader_SOURCES) 137 | target_sources(ConhostLoader PRIVATE ${ConhostLoader_SOURCES}) 138 | endif() 139 | 140 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${ConhostLoader_SOURCES}) 141 | 142 | target_link_libraries(ConhostLoader PUBLIC 143 | HookDll 144 | ) 145 | 146 | unset(CMKR_TARGET) 147 | unset(CMKR_SOURCES) 148 | 149 | # Target ExitProcess 150 | set(CMKR_TARGET ExitProcess) 151 | set(ExitProcess_SOURCES "") 152 | 153 | list(APPEND ExitProcess_SOURCES 154 | "ExitProcess/ExitProcess.cpp" 155 | ) 156 | 157 | list(APPEND ExitProcess_SOURCES 158 | cmake.toml 159 | ) 160 | 161 | set(CMKR_SOURCES ${ExitProcess_SOURCES}) 162 | add_library(ExitProcess SHARED) 163 | 164 | if(ExitProcess_SOURCES) 165 | target_sources(ExitProcess PRIVATE ${ExitProcess_SOURCES}) 166 | endif() 167 | 168 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${ExitProcess_SOURCES}) 169 | 170 | target_link_libraries(ExitProcess PUBLIC 171 | HookDll 172 | ) 173 | 174 | unset(CMKR_TARGET) 175 | unset(CMKR_SOURCES) 176 | 177 | # Target ForceQuit 178 | set(CMKR_TARGET ForceQuit) 179 | set(ForceQuit_SOURCES "") 180 | 181 | list(APPEND ForceQuit_SOURCES 182 | "ForceQuit/ForceQuit.cpp" 183 | ) 184 | 185 | list(APPEND ForceQuit_SOURCES 186 | cmake.toml 187 | ) 188 | 189 | set(CMKR_SOURCES ${ForceQuit_SOURCES}) 190 | add_library(ForceQuit SHARED) 191 | 192 | if(ForceQuit_SOURCES) 193 | target_sources(ForceQuit PRIVATE ${ForceQuit_SOURCES}) 194 | endif() 195 | 196 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${ForceQuit_SOURCES}) 197 | 198 | target_link_libraries(ForceQuit PUBLIC 199 | HookDll 200 | ) 201 | 202 | unset(CMKR_TARGET) 203 | unset(CMKR_SOURCES) 204 | 205 | # Target GitMagic 206 | set(CMKR_TARGET GitMagic) 207 | set(GitMagic_SOURCES "") 208 | 209 | list(APPEND GitMagic_SOURCES 210 | "GitMagic/GitMagic.cpp" 211 | ) 212 | 213 | list(APPEND GitMagic_SOURCES 214 | cmake.toml 215 | ) 216 | 217 | set(CMKR_SOURCES ${GitMagic_SOURCES}) 218 | add_library(GitMagic SHARED) 219 | 220 | if(GitMagic_SOURCES) 221 | target_sources(GitMagic PRIVATE ${GitMagic_SOURCES}) 222 | endif() 223 | 224 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${GitMagic_SOURCES}) 225 | 226 | target_link_libraries(GitMagic PUBLIC 227 | HookDll 228 | ) 229 | 230 | unset(CMKR_TARGET) 231 | unset(CMKR_SOURCES) 232 | 233 | # Target HighPriority 234 | set(CMKR_TARGET HighPriority) 235 | set(HighPriority_SOURCES "") 236 | 237 | list(APPEND HighPriority_SOURCES 238 | "HighPriority/HighPriority.cpp" 239 | ) 240 | 241 | list(APPEND HighPriority_SOURCES 242 | cmake.toml 243 | ) 244 | 245 | set(CMKR_SOURCES ${HighPriority_SOURCES}) 246 | add_library(HighPriority SHARED) 247 | 248 | if(HighPriority_SOURCES) 249 | target_sources(HighPriority PRIVATE ${HighPriority_SOURCES}) 250 | endif() 251 | 252 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${HighPriority_SOURCES}) 253 | 254 | target_link_libraries(HighPriority PUBLIC 255 | HookDll 256 | ) 257 | 258 | unset(CMKR_TARGET) 259 | unset(CMKR_SOURCES) 260 | 261 | # Target NoSoftwareInventory 262 | set(CMKR_TARGET NoSoftwareInventory) 263 | set(NoSoftwareInventory_SOURCES "") 264 | 265 | list(APPEND NoSoftwareInventory_SOURCES 266 | "NoSoftwareInventory/NoSoftwareInventory.cpp" 267 | ) 268 | 269 | list(APPEND NoSoftwareInventory_SOURCES 270 | cmake.toml 271 | ) 272 | 273 | set(CMKR_SOURCES ${NoSoftwareInventory_SOURCES}) 274 | add_library(NoSoftwareInventory SHARED) 275 | 276 | if(NoSoftwareInventory_SOURCES) 277 | target_sources(NoSoftwareInventory PRIVATE ${NoSoftwareInventory_SOURCES}) 278 | endif() 279 | 280 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${NoSoftwareInventory_SOURCES}) 281 | 282 | target_link_libraries(NoSoftwareInventory PUBLIC 283 | HookDll 284 | ) 285 | 286 | unset(CMKR_TARGET) 287 | unset(CMKR_SOURCES) 288 | 289 | # Target TotalCommander 290 | set(CMKR_TARGET TotalCommander) 291 | set(TotalCommander_SOURCES "") 292 | 293 | list(APPEND TotalCommander_SOURCES 294 | "TotalCommander/TotalCommander.cpp" 295 | ) 296 | 297 | list(APPEND TotalCommander_SOURCES 298 | cmake.toml 299 | ) 300 | 301 | set(CMKR_SOURCES ${TotalCommander_SOURCES}) 302 | add_library(TotalCommander SHARED) 303 | 304 | if(TotalCommander_SOURCES) 305 | target_sources(TotalCommander PRIVATE ${TotalCommander_SOURCES}) 306 | endif() 307 | 308 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${TotalCommander_SOURCES}) 309 | 310 | target_link_libraries(TotalCommander PUBLIC 311 | HookDll 312 | ) 313 | 314 | unset(CMKR_TARGET) 315 | unset(CMKR_SOURCES) 316 | 317 | # Target WerfaultMagic 318 | set(CMKR_TARGET WerfaultMagic) 319 | set(WerfaultMagic_SOURCES "") 320 | 321 | list(APPEND WerfaultMagic_SOURCES 322 | "WerfaultMagic/WerfaultMagic.cpp" 323 | ) 324 | 325 | list(APPEND WerfaultMagic_SOURCES 326 | cmake.toml 327 | ) 328 | 329 | set(CMKR_SOURCES ${WerfaultMagic_SOURCES}) 330 | add_library(WerfaultMagic SHARED) 331 | 332 | if(WerfaultMagic_SOURCES) 333 | target_sources(WerfaultMagic PRIVATE ${WerfaultMagic_SOURCES}) 334 | endif() 335 | 336 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${WerfaultMagic_SOURCES}) 337 | 338 | target_link_libraries(WerfaultMagic PUBLIC 339 | HookDll 340 | ) 341 | 342 | unset(CMKR_TARGET) 343 | unset(CMKR_SOURCES) 344 | 345 | # Target WowUndirect 346 | set(CMKR_TARGET WowUndirect) 347 | set(WowUndirect_SOURCES "") 348 | 349 | list(APPEND WowUndirect_SOURCES 350 | "WowUndirect/WowUndirect.cpp" 351 | ) 352 | 353 | list(APPEND WowUndirect_SOURCES 354 | cmake.toml 355 | ) 356 | 357 | set(CMKR_SOURCES ${WowUndirect_SOURCES}) 358 | add_library(WowUndirect SHARED) 359 | 360 | if(WowUndirect_SOURCES) 361 | target_sources(WowUndirect PRIVATE ${WowUndirect_SOURCES}) 362 | endif() 363 | 364 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${WowUndirect_SOURCES}) 365 | 366 | target_link_libraries(WowUndirect PUBLIC 367 | HookDll 368 | ) 369 | 370 | unset(CMKR_TARGET) 371 | unset(CMKR_SOURCES) 372 | 373 | -------------------------------------------------------------------------------- /CMake/cmkr.cmake: -------------------------------------------------------------------------------- 1 | include_guard() 2 | 3 | # Change these defaults to point to your infrastructure if desired 4 | set(CMKR_REPO "https://github.com/build-cpp/cmkr" CACHE STRING "cmkr git repository" FORCE) 5 | set(CMKR_TAG "v0.2.12" CACHE STRING "cmkr git tag (this needs to be available forever)" FORCE) 6 | set(CMKR_COMMIT_HASH "" CACHE STRING "cmkr git commit hash (optional)" FORCE) 7 | 8 | # To bootstrap/generate a cmkr project: cmake -P cmkr.cmake 9 | if(CMAKE_SCRIPT_MODE_FILE) 10 | set(CMAKE_BINARY_DIR "${CMAKE_BINARY_DIR}/build") 11 | set(CMAKE_CURRENT_BINARY_DIR "${CMAKE_BINARY_DIR}") 12 | file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}") 13 | endif() 14 | 15 | # Set these from the command line to customize for development/debugging purposes 16 | set(CMKR_EXECUTABLE "" CACHE FILEPATH "cmkr executable") 17 | set(CMKR_SKIP_GENERATION OFF CACHE BOOL "skip automatic cmkr generation") 18 | set(CMKR_BUILD_TYPE "Debug" CACHE STRING "cmkr build configuration") 19 | mark_as_advanced(CMKR_REPO CMKR_TAG CMKR_COMMIT_HASH CMKR_EXECUTABLE CMKR_SKIP_GENERATION CMKR_BUILD_TYPE) 20 | 21 | # Disable cmkr if generation is disabled 22 | if(DEFINED ENV{CI} OR CMKR_SKIP_GENERATION OR CMKR_BUILD_SKIP_GENERATION) 23 | message(STATUS "[cmkr] Skipping automatic cmkr generation") 24 | unset(CMKR_BUILD_SKIP_GENERATION CACHE) 25 | macro(cmkr) 26 | endmacro() 27 | return() 28 | endif() 29 | 30 | # Disable cmkr if no cmake.toml file is found 31 | if(NOT CMAKE_SCRIPT_MODE_FILE AND NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/cmake.toml") 32 | message(AUTHOR_WARNING "[cmkr] Not found: ${CMAKE_CURRENT_SOURCE_DIR}/cmake.toml") 33 | macro(cmkr) 34 | endmacro() 35 | return() 36 | endif() 37 | 38 | # Convert a Windows native path to CMake path 39 | if(CMKR_EXECUTABLE MATCHES "\\\\") 40 | string(REPLACE "\\" "/" CMKR_EXECUTABLE_CMAKE "${CMKR_EXECUTABLE}") 41 | set(CMKR_EXECUTABLE "${CMKR_EXECUTABLE_CMAKE}" CACHE FILEPATH "" FORCE) 42 | unset(CMKR_EXECUTABLE_CMAKE) 43 | endif() 44 | 45 | # Helper macro to execute a process (COMMAND_ERROR_IS_FATAL ANY is 3.19 and higher) 46 | function(cmkr_exec) 47 | execute_process(COMMAND ${ARGV} RESULT_VARIABLE CMKR_EXEC_RESULT) 48 | if(NOT CMKR_EXEC_RESULT EQUAL 0) 49 | message(FATAL_ERROR "cmkr_exec(${ARGV}) failed (exit code ${CMKR_EXEC_RESULT})") 50 | endif() 51 | endfunction() 52 | 53 | # Windows-specific hack (CMAKE_EXECUTABLE_PREFIX is not set at the moment) 54 | if(WIN32) 55 | set(CMKR_EXECUTABLE_NAME "cmkr.exe") 56 | else() 57 | set(CMKR_EXECUTABLE_NAME "cmkr") 58 | endif() 59 | 60 | # Use cached cmkr if found 61 | if(DEFINED ENV{CMKR_CACHE} AND EXISTS "$ENV{CMKR_CACHE}") 62 | set(CMKR_DIRECTORY_PREFIX "$ENV{CMKR_CACHE}") 63 | string(REPLACE "\\" "/" CMKR_DIRECTORY_PREFIX "${CMKR_DIRECTORY_PREFIX}") 64 | if(NOT CMKR_DIRECTORY_PREFIX MATCHES "\\/$") 65 | set(CMKR_DIRECTORY_PREFIX "${CMKR_DIRECTORY_PREFIX}/") 66 | endif() 67 | # Build in release mode for the cache 68 | set(CMKR_BUILD_TYPE "Release") 69 | else() 70 | set(CMKR_DIRECTORY_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/_cmkr_") 71 | endif() 72 | set(CMKR_DIRECTORY "${CMKR_DIRECTORY_PREFIX}${CMKR_TAG}") 73 | set(CMKR_CACHED_EXECUTABLE "${CMKR_DIRECTORY}/bin/${CMKR_EXECUTABLE_NAME}") 74 | 75 | # Handle upgrading logic 76 | if(CMKR_EXECUTABLE AND NOT CMKR_CACHED_EXECUTABLE STREQUAL CMKR_EXECUTABLE) 77 | if(CMKR_EXECUTABLE MATCHES "^${CMAKE_CURRENT_BINARY_DIR}/_cmkr") 78 | if(DEFINED ENV{CMKR_CACHE} AND EXISTS "$ENV{CMKR_CACHE}") 79 | message(AUTHOR_WARNING "[cmkr] Switching to cached cmkr: '${CMKR_CACHED_EXECUTABLE}'") 80 | if(EXISTS "${CMKR_CACHED_EXECUTABLE}") 81 | set(CMKR_EXECUTABLE "${CMKR_CACHED_EXECUTABLE}" CACHE FILEPATH "Full path to cmkr executable" FORCE) 82 | else() 83 | unset(CMKR_EXECUTABLE CACHE) 84 | endif() 85 | else() 86 | message(AUTHOR_WARNING "[cmkr] Upgrading '${CMKR_EXECUTABLE}' to '${CMKR_CACHED_EXECUTABLE}'") 87 | unset(CMKR_EXECUTABLE CACHE) 88 | endif() 89 | elseif(DEFINED ENV{CMKR_CACHE} AND EXISTS "$ENV{CMKR_CACHE}" AND CMKR_EXECUTABLE MATCHES "^${CMKR_DIRECTORY_PREFIX}") 90 | message(AUTHOR_WARNING "[cmkr] Upgrading cached '${CMKR_EXECUTABLE}' to '${CMKR_CACHED_EXECUTABLE}'") 91 | unset(CMKR_EXECUTABLE CACHE) 92 | endif() 93 | endif() 94 | 95 | if(CMKR_EXECUTABLE AND EXISTS "${CMKR_EXECUTABLE}") 96 | message(VERBOSE "[cmkr] Found cmkr: '${CMKR_EXECUTABLE}'") 97 | elseif(CMKR_EXECUTABLE AND NOT CMKR_EXECUTABLE STREQUAL CMKR_CACHED_EXECUTABLE) 98 | message(FATAL_ERROR "[cmkr] '${CMKR_EXECUTABLE}' not found") 99 | elseif(NOT CMKR_EXECUTABLE AND EXISTS "${CMKR_CACHED_EXECUTABLE}") 100 | set(CMKR_EXECUTABLE "${CMKR_CACHED_EXECUTABLE}" CACHE FILEPATH "Full path to cmkr executable" FORCE) 101 | message(STATUS "[cmkr] Found cached cmkr: '${CMKR_EXECUTABLE}'") 102 | else() 103 | set(CMKR_EXECUTABLE "${CMKR_CACHED_EXECUTABLE}" CACHE FILEPATH "Full path to cmkr executable" FORCE) 104 | message(VERBOSE "[cmkr] Bootstrapping '${CMKR_EXECUTABLE}'") 105 | 106 | message(STATUS "[cmkr] Fetching cmkr...") 107 | if(EXISTS "${CMKR_DIRECTORY}") 108 | cmkr_exec("${CMAKE_COMMAND}" -E rm -rf "${CMKR_DIRECTORY}") 109 | endif() 110 | find_package(Git QUIET REQUIRED) 111 | cmkr_exec("${GIT_EXECUTABLE}" 112 | clone 113 | --config advice.detachedHead=false 114 | --branch ${CMKR_TAG} 115 | --depth 1 116 | ${CMKR_REPO} 117 | "${CMKR_DIRECTORY}" 118 | ) 119 | if(CMKR_COMMIT_HASH) 120 | execute_process( 121 | COMMAND "${GIT_EXECUTABLE}" checkout -q "${CMKR_COMMIT_HASH}" 122 | RESULT_VARIABLE CMKR_EXEC_RESULT 123 | WORKING_DIRECTORY "${CMKR_DIRECTORY}" 124 | ) 125 | if(NOT CMKR_EXEC_RESULT EQUAL 0) 126 | message(FATAL_ERROR "Tag '${CMKR_TAG}' hash is not '${CMKR_COMMIT_HASH}'") 127 | endif() 128 | endif() 129 | message(STATUS "[cmkr] Building cmkr (using system compiler)...") 130 | cmkr_exec("${CMAKE_COMMAND}" 131 | --no-warn-unused-cli 132 | "${CMKR_DIRECTORY}" 133 | "-B${CMKR_DIRECTORY}/build" 134 | "-DCMAKE_BUILD_TYPE=${CMKR_BUILD_TYPE}" 135 | "-DCMAKE_UNITY_BUILD=ON" 136 | "-DCMAKE_INSTALL_PREFIX=${CMKR_DIRECTORY}" 137 | "-DCMKR_GENERATE_DOCUMENTATION=OFF" 138 | ) 139 | cmkr_exec("${CMAKE_COMMAND}" 140 | --build "${CMKR_DIRECTORY}/build" 141 | --config "${CMKR_BUILD_TYPE}" 142 | --parallel 143 | ) 144 | cmkr_exec("${CMAKE_COMMAND}" 145 | --install "${CMKR_DIRECTORY}/build" 146 | --config "${CMKR_BUILD_TYPE}" 147 | --prefix "${CMKR_DIRECTORY}" 148 | --component cmkr 149 | ) 150 | if(NOT EXISTS ${CMKR_EXECUTABLE}) 151 | message(FATAL_ERROR "[cmkr] Failed to bootstrap '${CMKR_EXECUTABLE}'") 152 | endif() 153 | cmkr_exec("${CMKR_EXECUTABLE}" version) 154 | message(STATUS "[cmkr] Bootstrapped ${CMKR_EXECUTABLE}") 155 | endif() 156 | execute_process(COMMAND "${CMKR_EXECUTABLE}" version 157 | RESULT_VARIABLE CMKR_EXEC_RESULT 158 | ) 159 | if(NOT CMKR_EXEC_RESULT EQUAL 0) 160 | message(FATAL_ERROR "[cmkr] Failed to get version, try clearing the cache and rebuilding") 161 | endif() 162 | 163 | # Use cmkr.cmake as a script 164 | if(CMAKE_SCRIPT_MODE_FILE) 165 | if(NOT EXISTS "${CMAKE_SOURCE_DIR}/cmake.toml") 166 | execute_process(COMMAND "${CMKR_EXECUTABLE}" init 167 | RESULT_VARIABLE CMKR_EXEC_RESULT 168 | ) 169 | if(NOT CMKR_EXEC_RESULT EQUAL 0) 170 | message(FATAL_ERROR "[cmkr] Failed to bootstrap cmkr project. Please report an issue: https://github.com/build-cpp/cmkr/issues/new") 171 | else() 172 | message(STATUS "[cmkr] Modify cmake.toml and then configure using: cmake -B build") 173 | endif() 174 | else() 175 | execute_process(COMMAND "${CMKR_EXECUTABLE}" gen 176 | RESULT_VARIABLE CMKR_EXEC_RESULT 177 | ) 178 | if(NOT CMKR_EXEC_RESULT EQUAL 0) 179 | message(FATAL_ERROR "[cmkr] Failed to generate project.") 180 | else() 181 | message(STATUS "[cmkr] Configure using: cmake -B build") 182 | endif() 183 | endif() 184 | endif() 185 | 186 | # This is the macro that contains black magic 187 | macro(cmkr) 188 | # When this macro is called from the generated file, fake some internal CMake variables 189 | get_source_file_property(CMKR_CURRENT_LIST_FILE "${CMAKE_CURRENT_LIST_FILE}" CMKR_CURRENT_LIST_FILE) 190 | if(CMKR_CURRENT_LIST_FILE) 191 | set(CMAKE_CURRENT_LIST_FILE "${CMKR_CURRENT_LIST_FILE}") 192 | get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" DIRECTORY) 193 | endif() 194 | 195 | # File-based include guard (include_guard is not documented to work) 196 | get_source_file_property(CMKR_INCLUDE_GUARD "${CMAKE_CURRENT_LIST_FILE}" CMKR_INCLUDE_GUARD) 197 | if(NOT CMKR_INCLUDE_GUARD) 198 | set_source_files_properties("${CMAKE_CURRENT_LIST_FILE}" PROPERTIES CMKR_INCLUDE_GUARD TRUE) 199 | 200 | file(SHA256 "${CMAKE_CURRENT_LIST_FILE}" CMKR_LIST_FILE_SHA256_PRE) 201 | 202 | # Generate CMakeLists.txt 203 | cmkr_exec("${CMKR_EXECUTABLE}" gen 204 | WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" 205 | ) 206 | 207 | file(SHA256 "${CMAKE_CURRENT_LIST_FILE}" CMKR_LIST_FILE_SHA256_POST) 208 | 209 | # Delete the temporary file if it was left for some reason 210 | set(CMKR_TEMP_FILE "${CMAKE_CURRENT_SOURCE_DIR}/CMakerLists.txt") 211 | if(EXISTS "${CMKR_TEMP_FILE}") 212 | file(REMOVE "${CMKR_TEMP_FILE}") 213 | endif() 214 | 215 | if(NOT CMKR_LIST_FILE_SHA256_PRE STREQUAL CMKR_LIST_FILE_SHA256_POST) 216 | # Copy the now-generated CMakeLists.txt to CMakerLists.txt 217 | # This is done because you cannot include() a file you are currently in 218 | configure_file(CMakeLists.txt "${CMKR_TEMP_FILE}" COPYONLY) 219 | 220 | # Add the macro required for the hack at the start of the cmkr macro 221 | set_source_files_properties("${CMKR_TEMP_FILE}" PROPERTIES 222 | CMKR_CURRENT_LIST_FILE "${CMAKE_CURRENT_LIST_FILE}" 223 | ) 224 | 225 | # 'Execute' the newly-generated CMakeLists.txt 226 | include("${CMKR_TEMP_FILE}") 227 | 228 | # Delete the generated file 229 | file(REMOVE "${CMKR_TEMP_FILE}") 230 | 231 | # Do not execute the rest of the original CMakeLists.txt 232 | return() 233 | endif() 234 | # Resume executing the unmodified CMakeLists.txt 235 | endif() 236 | endmacro() 237 | -------------------------------------------------------------------------------- /Libraries/MinHook/hde/hde32.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Hacker Disassembler Engine 32 C 3 | * Copyright (c) 2008-2009, Vyacheslav Patkov. 4 | * All rights reserved. 5 | * 6 | */ 7 | 8 | #if defined(_M_IX86) || defined(__i386__) 9 | 10 | #include "hde32.h" 11 | #include "table32.h" 12 | 13 | unsigned int hde32_disasm(const void *code, hde32s *hs) 14 | { 15 | uint8_t x, c, *p = (uint8_t *)code, cflags, opcode, pref = 0; 16 | uint8_t *ht = hde32_table, m_mod, m_reg, m_rm, disp_size = 0; 17 | 18 | // Avoid using memset to reduce the footprint. 19 | #ifndef _MSC_VER 20 | memset((LPBYTE)hs, 0, sizeof(hde32s)); 21 | #else 22 | __stosb((LPBYTE)hs, 0, sizeof(hde32s)); 23 | #endif 24 | 25 | for (x = 16; x; x--) 26 | switch (c = *p++) { 27 | case 0xf3: 28 | hs->p_rep = c; 29 | pref |= PRE_F3; 30 | break; 31 | case 0xf2: 32 | hs->p_rep = c; 33 | pref |= PRE_F2; 34 | break; 35 | case 0xf0: 36 | hs->p_lock = c; 37 | pref |= PRE_LOCK; 38 | break; 39 | case 0x26: case 0x2e: case 0x36: 40 | case 0x3e: case 0x64: case 0x65: 41 | hs->p_seg = c; 42 | pref |= PRE_SEG; 43 | break; 44 | case 0x66: 45 | hs->p_66 = c; 46 | pref |= PRE_66; 47 | break; 48 | case 0x67: 49 | hs->p_67 = c; 50 | pref |= PRE_67; 51 | break; 52 | default: 53 | goto pref_done; 54 | } 55 | pref_done: 56 | 57 | hs->flags = (uint32_t)pref << 23; 58 | 59 | if (!pref) 60 | pref |= PRE_NONE; 61 | 62 | if ((hs->opcode = c) == 0x0f) { 63 | hs->opcode2 = c = *p++; 64 | ht += DELTA_OPCODES; 65 | } else if (c >= 0xa0 && c <= 0xa3) { 66 | if (pref & PRE_67) 67 | pref |= PRE_66; 68 | else 69 | pref &= ~PRE_66; 70 | } 71 | 72 | opcode = c; 73 | cflags = ht[ht[opcode / 4] + (opcode % 4)]; 74 | 75 | if (cflags == C_ERROR) { 76 | hs->flags |= F_ERROR | F_ERROR_OPCODE; 77 | cflags = 0; 78 | if ((opcode & -3) == 0x24) 79 | cflags++; 80 | } 81 | 82 | x = 0; 83 | if (cflags & C_GROUP) { 84 | uint16_t t; 85 | t = *(uint16_t *)(ht + (cflags & 0x7f)); 86 | cflags = (uint8_t)t; 87 | x = (uint8_t)(t >> 8); 88 | } 89 | 90 | if (hs->opcode2) { 91 | ht = hde32_table + DELTA_PREFIXES; 92 | if (ht[ht[opcode / 4] + (opcode % 4)] & pref) 93 | hs->flags |= F_ERROR | F_ERROR_OPCODE; 94 | } 95 | 96 | if (cflags & C_MODRM) { 97 | hs->flags |= F_MODRM; 98 | hs->modrm = c = *p++; 99 | hs->modrm_mod = m_mod = c >> 6; 100 | hs->modrm_rm = m_rm = c & 7; 101 | hs->modrm_reg = m_reg = (c & 0x3f) >> 3; 102 | 103 | if (x && ((x << m_reg) & 0x80)) 104 | hs->flags |= F_ERROR | F_ERROR_OPCODE; 105 | 106 | if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { 107 | uint8_t t = opcode - 0xd9; 108 | if (m_mod == 3) { 109 | ht = hde32_table + DELTA_FPU_MODRM + t*8; 110 | t = ht[m_reg] << m_rm; 111 | } else { 112 | ht = hde32_table + DELTA_FPU_REG; 113 | t = ht[t] << m_reg; 114 | } 115 | if (t & 0x80) 116 | hs->flags |= F_ERROR | F_ERROR_OPCODE; 117 | } 118 | 119 | if (pref & PRE_LOCK) { 120 | if (m_mod == 3) { 121 | hs->flags |= F_ERROR | F_ERROR_LOCK; 122 | } else { 123 | uint8_t *table_end, op = opcode; 124 | if (hs->opcode2) { 125 | ht = hde32_table + DELTA_OP2_LOCK_OK; 126 | table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; 127 | } else { 128 | ht = hde32_table + DELTA_OP_LOCK_OK; 129 | table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; 130 | op &= -2; 131 | } 132 | for (; ht != table_end; ht++) 133 | if (*ht++ == op) { 134 | if (!((*ht << m_reg) & 0x80)) 135 | goto no_lock_error; 136 | else 137 | break; 138 | } 139 | hs->flags |= F_ERROR | F_ERROR_LOCK; 140 | no_lock_error: 141 | ; 142 | } 143 | } 144 | 145 | if (hs->opcode2) { 146 | switch (opcode) { 147 | case 0x20: case 0x22: 148 | m_mod = 3; 149 | if (m_reg > 4 || m_reg == 1) 150 | goto error_operand; 151 | else 152 | goto no_error_operand; 153 | case 0x21: case 0x23: 154 | m_mod = 3; 155 | if (m_reg == 4 || m_reg == 5) 156 | goto error_operand; 157 | else 158 | goto no_error_operand; 159 | } 160 | } else { 161 | switch (opcode) { 162 | case 0x8c: 163 | if (m_reg > 5) 164 | goto error_operand; 165 | else 166 | goto no_error_operand; 167 | case 0x8e: 168 | if (m_reg == 1 || m_reg > 5) 169 | goto error_operand; 170 | else 171 | goto no_error_operand; 172 | } 173 | } 174 | 175 | if (m_mod == 3) { 176 | uint8_t *table_end; 177 | if (hs->opcode2) { 178 | ht = hde32_table + DELTA_OP2_ONLY_MEM; 179 | table_end = ht + sizeof(hde32_table) - DELTA_OP2_ONLY_MEM; 180 | } else { 181 | ht = hde32_table + DELTA_OP_ONLY_MEM; 182 | table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; 183 | } 184 | for (; ht != table_end; ht += 2) 185 | if (*ht++ == opcode) { 186 | if (*ht++ & pref && !((*ht << m_reg) & 0x80)) 187 | goto error_operand; 188 | else 189 | break; 190 | } 191 | goto no_error_operand; 192 | } else if (hs->opcode2) { 193 | switch (opcode) { 194 | case 0x50: case 0xd7: case 0xf7: 195 | if (pref & (PRE_NONE | PRE_66)) 196 | goto error_operand; 197 | break; 198 | case 0xd6: 199 | if (pref & (PRE_F2 | PRE_F3)) 200 | goto error_operand; 201 | break; 202 | case 0xc5: 203 | goto error_operand; 204 | } 205 | goto no_error_operand; 206 | } else 207 | goto no_error_operand; 208 | 209 | error_operand: 210 | hs->flags |= F_ERROR | F_ERROR_OPERAND; 211 | no_error_operand: 212 | 213 | c = *p++; 214 | if (m_reg <= 1) { 215 | if (opcode == 0xf6) 216 | cflags |= C_IMM8; 217 | else if (opcode == 0xf7) 218 | cflags |= C_IMM_P66; 219 | } 220 | 221 | switch (m_mod) { 222 | case 0: 223 | if (pref & PRE_67) { 224 | if (m_rm == 6) 225 | disp_size = 2; 226 | } else 227 | if (m_rm == 5) 228 | disp_size = 4; 229 | break; 230 | case 1: 231 | disp_size = 1; 232 | break; 233 | case 2: 234 | disp_size = 2; 235 | if (!(pref & PRE_67)) 236 | disp_size <<= 1; 237 | } 238 | 239 | if (m_mod != 3 && m_rm == 4 && !(pref & PRE_67)) { 240 | hs->flags |= F_SIB; 241 | p++; 242 | hs->sib = c; 243 | hs->sib_scale = c >> 6; 244 | hs->sib_index = (c & 0x3f) >> 3; 245 | if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1)) 246 | disp_size = 4; 247 | } 248 | 249 | p--; 250 | switch (disp_size) { 251 | case 1: 252 | hs->flags |= F_DISP8; 253 | hs->disp.disp8 = *p; 254 | break; 255 | case 2: 256 | hs->flags |= F_DISP16; 257 | hs->disp.disp16 = *(uint16_t *)p; 258 | break; 259 | case 4: 260 | hs->flags |= F_DISP32; 261 | hs->disp.disp32 = *(uint32_t *)p; 262 | } 263 | p += disp_size; 264 | } else if (pref & PRE_LOCK) 265 | hs->flags |= F_ERROR | F_ERROR_LOCK; 266 | 267 | if (cflags & C_IMM_P66) { 268 | if (cflags & C_REL32) { 269 | if (pref & PRE_66) { 270 | hs->flags |= F_IMM16 | F_RELATIVE; 271 | hs->imm.imm16 = *(uint16_t *)p; 272 | p += 2; 273 | goto disasm_done; 274 | } 275 | goto rel32_ok; 276 | } 277 | if (pref & PRE_66) { 278 | hs->flags |= F_IMM16; 279 | hs->imm.imm16 = *(uint16_t *)p; 280 | p += 2; 281 | } else { 282 | hs->flags |= F_IMM32; 283 | hs->imm.imm32 = *(uint32_t *)p; 284 | p += 4; 285 | } 286 | } 287 | 288 | if (cflags & C_IMM16) { 289 | if (hs->flags & F_IMM32) { 290 | hs->flags |= F_IMM16; 291 | hs->disp.disp16 = *(uint16_t *)p; 292 | } else if (hs->flags & F_IMM16) { 293 | hs->flags |= F_2IMM16; 294 | hs->disp.disp16 = *(uint16_t *)p; 295 | } else { 296 | hs->flags |= F_IMM16; 297 | hs->imm.imm16 = *(uint16_t *)p; 298 | } 299 | p += 2; 300 | } 301 | if (cflags & C_IMM8) { 302 | hs->flags |= F_IMM8; 303 | hs->imm.imm8 = *p++; 304 | } 305 | 306 | if (cflags & C_REL32) { 307 | rel32_ok: 308 | hs->flags |= F_IMM32 | F_RELATIVE; 309 | hs->imm.imm32 = *(uint32_t *)p; 310 | p += 4; 311 | } else if (cflags & C_REL8) { 312 | hs->flags |= F_IMM8 | F_RELATIVE; 313 | hs->imm.imm8 = *p++; 314 | } 315 | 316 | disasm_done: 317 | 318 | if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) { 319 | hs->flags |= F_ERROR | F_ERROR_LENGTH; 320 | hs->len = 15; 321 | } 322 | 323 | return (unsigned int)hs->len; 324 | } 325 | 326 | #endif // defined(_M_IX86) || defined(__i386__) 327 | -------------------------------------------------------------------------------- /Libraries/MinHook/hde/hde64.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Hacker Disassembler Engine 64 C 3 | * Copyright (c) 2008-2009, Vyacheslav Patkov. 4 | * All rights reserved. 5 | * 6 | */ 7 | 8 | #if defined(_M_X64) || defined(__x86_64__) 9 | 10 | #include "hde64.h" 11 | #include "table64.h" 12 | 13 | unsigned int hde64_disasm(const void *code, hde64s *hs) 14 | { 15 | uint8_t x, c, *p = (uint8_t *)code, cflags, opcode, pref = 0; 16 | uint8_t *ht = hde64_table, m_mod, m_reg, m_rm, disp_size = 0; 17 | uint8_t op64 = 0; 18 | 19 | // Avoid using memset to reduce the footprint. 20 | #ifndef _MSC_VER 21 | memset((LPBYTE)hs, 0, sizeof(hde64s)); 22 | #else 23 | __stosb((LPBYTE)hs, 0, sizeof(hde64s)); 24 | #endif 25 | 26 | for (x = 16; x; x--) 27 | switch (c = *p++) { 28 | case 0xf3: 29 | hs->p_rep = c; 30 | pref |= PRE_F3; 31 | break; 32 | case 0xf2: 33 | hs->p_rep = c; 34 | pref |= PRE_F2; 35 | break; 36 | case 0xf0: 37 | hs->p_lock = c; 38 | pref |= PRE_LOCK; 39 | break; 40 | case 0x26: case 0x2e: case 0x36: 41 | case 0x3e: case 0x64: case 0x65: 42 | hs->p_seg = c; 43 | pref |= PRE_SEG; 44 | break; 45 | case 0x66: 46 | hs->p_66 = c; 47 | pref |= PRE_66; 48 | break; 49 | case 0x67: 50 | hs->p_67 = c; 51 | pref |= PRE_67; 52 | break; 53 | default: 54 | goto pref_done; 55 | } 56 | pref_done: 57 | 58 | hs->flags = (uint32_t)pref << 23; 59 | 60 | if (!pref) 61 | pref |= PRE_NONE; 62 | 63 | if ((c & 0xf0) == 0x40) { 64 | hs->flags |= F_PREFIX_REX; 65 | if ((hs->rex_w = (c & 0xf) >> 3) && (*p & 0xf8) == 0xb8) 66 | op64++; 67 | hs->rex_r = (c & 7) >> 2; 68 | hs->rex_x = (c & 3) >> 1; 69 | hs->rex_b = c & 1; 70 | if (((c = *p++) & 0xf0) == 0x40) { 71 | opcode = c; 72 | goto error_opcode; 73 | } 74 | } 75 | 76 | if ((hs->opcode = c) == 0x0f) { 77 | hs->opcode2 = c = *p++; 78 | ht += DELTA_OPCODES; 79 | } else if (c >= 0xa0 && c <= 0xa3) { 80 | op64++; 81 | if (pref & PRE_67) 82 | pref |= PRE_66; 83 | else 84 | pref &= ~PRE_66; 85 | } 86 | 87 | opcode = c; 88 | cflags = ht[ht[opcode / 4] + (opcode % 4)]; 89 | 90 | if (cflags == C_ERROR) { 91 | error_opcode: 92 | hs->flags |= F_ERROR | F_ERROR_OPCODE; 93 | cflags = 0; 94 | if ((opcode & -3) == 0x24) 95 | cflags++; 96 | } 97 | 98 | x = 0; 99 | if (cflags & C_GROUP) { 100 | uint16_t t; 101 | t = *(uint16_t *)(ht + (cflags & 0x7f)); 102 | cflags = (uint8_t)t; 103 | x = (uint8_t)(t >> 8); 104 | } 105 | 106 | if (hs->opcode2) { 107 | ht = hde64_table + DELTA_PREFIXES; 108 | if (ht[ht[opcode / 4] + (opcode % 4)] & pref) 109 | hs->flags |= F_ERROR | F_ERROR_OPCODE; 110 | } 111 | 112 | if (cflags & C_MODRM) { 113 | hs->flags |= F_MODRM; 114 | hs->modrm = c = *p++; 115 | hs->modrm_mod = m_mod = c >> 6; 116 | hs->modrm_rm = m_rm = c & 7; 117 | hs->modrm_reg = m_reg = (c & 0x3f) >> 3; 118 | 119 | if (x && ((x << m_reg) & 0x80)) 120 | hs->flags |= F_ERROR | F_ERROR_OPCODE; 121 | 122 | if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { 123 | uint8_t t = opcode - 0xd9; 124 | if (m_mod == 3) { 125 | ht = hde64_table + DELTA_FPU_MODRM + t*8; 126 | t = ht[m_reg] << m_rm; 127 | } else { 128 | ht = hde64_table + DELTA_FPU_REG; 129 | t = ht[t] << m_reg; 130 | } 131 | if (t & 0x80) 132 | hs->flags |= F_ERROR | F_ERROR_OPCODE; 133 | } 134 | 135 | if (pref & PRE_LOCK) { 136 | if (m_mod == 3) { 137 | hs->flags |= F_ERROR | F_ERROR_LOCK; 138 | } else { 139 | uint8_t *table_end, op = opcode; 140 | if (hs->opcode2) { 141 | ht = hde64_table + DELTA_OP2_LOCK_OK; 142 | table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; 143 | } else { 144 | ht = hde64_table + DELTA_OP_LOCK_OK; 145 | table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; 146 | op &= -2; 147 | } 148 | for (; ht != table_end; ht++) 149 | if (*ht++ == op) { 150 | if (!((*ht << m_reg) & 0x80)) 151 | goto no_lock_error; 152 | else 153 | break; 154 | } 155 | hs->flags |= F_ERROR | F_ERROR_LOCK; 156 | no_lock_error: 157 | ; 158 | } 159 | } 160 | 161 | if (hs->opcode2) { 162 | switch (opcode) { 163 | case 0x20: case 0x22: 164 | m_mod = 3; 165 | if (m_reg > 4 || m_reg == 1) 166 | goto error_operand; 167 | else 168 | goto no_error_operand; 169 | case 0x21: case 0x23: 170 | m_mod = 3; 171 | if (m_reg == 4 || m_reg == 5) 172 | goto error_operand; 173 | else 174 | goto no_error_operand; 175 | } 176 | } else { 177 | switch (opcode) { 178 | case 0x8c: 179 | if (m_reg > 5) 180 | goto error_operand; 181 | else 182 | goto no_error_operand; 183 | case 0x8e: 184 | if (m_reg == 1 || m_reg > 5) 185 | goto error_operand; 186 | else 187 | goto no_error_operand; 188 | } 189 | } 190 | 191 | if (m_mod == 3) { 192 | uint8_t *table_end; 193 | if (hs->opcode2) { 194 | ht = hde64_table + DELTA_OP2_ONLY_MEM; 195 | table_end = ht + sizeof(hde64_table) - DELTA_OP2_ONLY_MEM; 196 | } else { 197 | ht = hde64_table + DELTA_OP_ONLY_MEM; 198 | table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; 199 | } 200 | for (; ht != table_end; ht += 2) 201 | if (*ht++ == opcode) { 202 | if (*ht++ & pref && !((*ht << m_reg) & 0x80)) 203 | goto error_operand; 204 | else 205 | break; 206 | } 207 | goto no_error_operand; 208 | } else if (hs->opcode2) { 209 | switch (opcode) { 210 | case 0x50: case 0xd7: case 0xf7: 211 | if (pref & (PRE_NONE | PRE_66)) 212 | goto error_operand; 213 | break; 214 | case 0xd6: 215 | if (pref & (PRE_F2 | PRE_F3)) 216 | goto error_operand; 217 | break; 218 | case 0xc5: 219 | goto error_operand; 220 | } 221 | goto no_error_operand; 222 | } else 223 | goto no_error_operand; 224 | 225 | error_operand: 226 | hs->flags |= F_ERROR | F_ERROR_OPERAND; 227 | no_error_operand: 228 | 229 | c = *p++; 230 | if (m_reg <= 1) { 231 | if (opcode == 0xf6) 232 | cflags |= C_IMM8; 233 | else if (opcode == 0xf7) 234 | cflags |= C_IMM_P66; 235 | } 236 | 237 | switch (m_mod) { 238 | case 0: 239 | if (pref & PRE_67) { 240 | if (m_rm == 6) 241 | disp_size = 2; 242 | } else 243 | if (m_rm == 5) 244 | disp_size = 4; 245 | break; 246 | case 1: 247 | disp_size = 1; 248 | break; 249 | case 2: 250 | disp_size = 2; 251 | if (!(pref & PRE_67)) 252 | disp_size <<= 1; 253 | } 254 | 255 | if (m_mod != 3 && m_rm == 4) { 256 | hs->flags |= F_SIB; 257 | p++; 258 | hs->sib = c; 259 | hs->sib_scale = c >> 6; 260 | hs->sib_index = (c & 0x3f) >> 3; 261 | if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1)) 262 | disp_size = 4; 263 | } 264 | 265 | p--; 266 | switch (disp_size) { 267 | case 1: 268 | hs->flags |= F_DISP8; 269 | hs->disp.disp8 = *p; 270 | break; 271 | case 2: 272 | hs->flags |= F_DISP16; 273 | hs->disp.disp16 = *(uint16_t *)p; 274 | break; 275 | case 4: 276 | hs->flags |= F_DISP32; 277 | hs->disp.disp32 = *(uint32_t *)p; 278 | } 279 | p += disp_size; 280 | } else if (pref & PRE_LOCK) 281 | hs->flags |= F_ERROR | F_ERROR_LOCK; 282 | 283 | if (cflags & C_IMM_P66) { 284 | if (cflags & C_REL32) { 285 | if (pref & PRE_66) { 286 | hs->flags |= F_IMM16 | F_RELATIVE; 287 | hs->imm.imm16 = *(uint16_t *)p; 288 | p += 2; 289 | goto disasm_done; 290 | } 291 | goto rel32_ok; 292 | } 293 | if (op64) { 294 | hs->flags |= F_IMM64; 295 | hs->imm.imm64 = *(uint64_t *)p; 296 | p += 8; 297 | } else if (!(pref & PRE_66)) { 298 | hs->flags |= F_IMM32; 299 | hs->imm.imm32 = *(uint32_t *)p; 300 | p += 4; 301 | } else 302 | goto imm16_ok; 303 | } 304 | 305 | 306 | if (cflags & C_IMM16) { 307 | imm16_ok: 308 | hs->flags |= F_IMM16; 309 | hs->imm.imm16 = *(uint16_t *)p; 310 | p += 2; 311 | } 312 | if (cflags & C_IMM8) { 313 | hs->flags |= F_IMM8; 314 | hs->imm.imm8 = *p++; 315 | } 316 | 317 | if (cflags & C_REL32) { 318 | rel32_ok: 319 | hs->flags |= F_IMM32 | F_RELATIVE; 320 | hs->imm.imm32 = *(uint32_t *)p; 321 | p += 4; 322 | } else if (cflags & C_REL8) { 323 | hs->flags |= F_IMM8 | F_RELATIVE; 324 | hs->imm.imm8 = *p++; 325 | } 326 | 327 | disasm_done: 328 | 329 | if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) { 330 | hs->flags |= F_ERROR | F_ERROR_LENGTH; 331 | hs->len = 15; 332 | } 333 | 334 | return (unsigned int)hs->len; 335 | } 336 | 337 | #endif // defined(_M_X64) || defined(__x86_64__) 338 | -------------------------------------------------------------------------------- /Libraries/MinHook/buffer.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MinHook - The Minimalistic API Hooking Library for x64/x86 3 | * Copyright (C) 2009-2017 Tsuda Kageyu. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18 | * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19 | * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20 | * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #include 30 | #include "buffer.h" 31 | 32 | // Size of each memory block. (= page size of VirtualAlloc) 33 | #define MEMORY_BLOCK_SIZE 0x1000 34 | 35 | // Max range for seeking a memory block. (= 1024MB) 36 | #define MAX_MEMORY_RANGE 0x40000000 37 | 38 | // Memory protection flags to check the executable address. 39 | #define PAGE_EXECUTE_FLAGS \ 40 | (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) 41 | 42 | // Memory slot. 43 | typedef struct _MEMORY_SLOT 44 | { 45 | union 46 | { 47 | struct _MEMORY_SLOT *pNext; 48 | UINT8 buffer[MEMORY_SLOT_SIZE]; 49 | }; 50 | } MEMORY_SLOT, *PMEMORY_SLOT; 51 | 52 | // Memory block info. Placed at the head of each block. 53 | typedef struct _MEMORY_BLOCK 54 | { 55 | struct _MEMORY_BLOCK *pNext; 56 | PMEMORY_SLOT pFree; // First element of the free slot list. 57 | UINT usedCount; 58 | } MEMORY_BLOCK, *PMEMORY_BLOCK; 59 | 60 | //------------------------------------------------------------------------- 61 | // Global Variables: 62 | //------------------------------------------------------------------------- 63 | 64 | // First element of the memory block list. 65 | PMEMORY_BLOCK g_pMemoryBlocks; 66 | 67 | //------------------------------------------------------------------------- 68 | VOID InitializeBuffer(VOID) 69 | { 70 | // Nothing to do for now. 71 | } 72 | 73 | //------------------------------------------------------------------------- 74 | VOID UninitializeBuffer(VOID) 75 | { 76 | PMEMORY_BLOCK pBlock = g_pMemoryBlocks; 77 | g_pMemoryBlocks = NULL; 78 | 79 | while (pBlock) 80 | { 81 | PMEMORY_BLOCK pNext = pBlock->pNext; 82 | VirtualFree(pBlock, 0, MEM_RELEASE); 83 | pBlock = pNext; 84 | } 85 | } 86 | 87 | //------------------------------------------------------------------------- 88 | #if defined(_M_X64) || defined(__x86_64__) 89 | static LPVOID FindPrevFreeRegion(LPVOID pAddress, LPVOID pMinAddr, DWORD dwAllocationGranularity) 90 | { 91 | ULONG_PTR tryAddr = (ULONG_PTR)pAddress; 92 | 93 | // Round down to the allocation granularity. 94 | tryAddr -= tryAddr % dwAllocationGranularity; 95 | 96 | // Start from the previous allocation granularity multiply. 97 | tryAddr -= dwAllocationGranularity; 98 | 99 | while (tryAddr >= (ULONG_PTR)pMinAddr) 100 | { 101 | MEMORY_BASIC_INFORMATION mbi; 102 | if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0) 103 | break; 104 | 105 | if (mbi.State == MEM_FREE) 106 | return (LPVOID)tryAddr; 107 | 108 | if ((ULONG_PTR)mbi.AllocationBase < dwAllocationGranularity) 109 | break; 110 | 111 | tryAddr = (ULONG_PTR)mbi.AllocationBase - dwAllocationGranularity; 112 | } 113 | 114 | return NULL; 115 | } 116 | #endif 117 | 118 | //------------------------------------------------------------------------- 119 | #if defined(_M_X64) || defined(__x86_64__) 120 | static LPVOID FindNextFreeRegion(LPVOID pAddress, LPVOID pMaxAddr, DWORD dwAllocationGranularity) 121 | { 122 | ULONG_PTR tryAddr = (ULONG_PTR)pAddress; 123 | 124 | // Round down to the allocation granularity. 125 | tryAddr -= tryAddr % dwAllocationGranularity; 126 | 127 | // Start from the next allocation granularity multiply. 128 | tryAddr += dwAllocationGranularity; 129 | 130 | while (tryAddr <= (ULONG_PTR)pMaxAddr) 131 | { 132 | MEMORY_BASIC_INFORMATION mbi; 133 | if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0) 134 | break; 135 | 136 | if (mbi.State == MEM_FREE) 137 | return (LPVOID)tryAddr; 138 | 139 | tryAddr = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; 140 | 141 | // Round up to the next allocation granularity. 142 | tryAddr += dwAllocationGranularity - 1; 143 | tryAddr -= tryAddr % dwAllocationGranularity; 144 | } 145 | 146 | return NULL; 147 | } 148 | #endif 149 | 150 | //------------------------------------------------------------------------- 151 | static PMEMORY_BLOCK GetMemoryBlock(LPVOID pOrigin) 152 | { 153 | PMEMORY_BLOCK pBlock; 154 | #if defined(_M_X64) || defined(__x86_64__) 155 | ULONG_PTR minAddr; 156 | ULONG_PTR maxAddr; 157 | 158 | SYSTEM_INFO si; 159 | GetSystemInfo(&si); 160 | minAddr = (ULONG_PTR)si.lpMinimumApplicationAddress; 161 | maxAddr = (ULONG_PTR)si.lpMaximumApplicationAddress; 162 | 163 | // pOrigin ± 512MB 164 | if ((ULONG_PTR)pOrigin > MAX_MEMORY_RANGE && minAddr < (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE) 165 | minAddr = (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE; 166 | 167 | if (maxAddr > (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE) 168 | maxAddr = (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE; 169 | 170 | // Make room for MEMORY_BLOCK_SIZE bytes. 171 | maxAddr -= MEMORY_BLOCK_SIZE - 1; 172 | #endif 173 | 174 | // Look the registered blocks for a reachable one. 175 | for (pBlock = g_pMemoryBlocks; pBlock != NULL; pBlock = pBlock->pNext) 176 | { 177 | #if defined(_M_X64) || defined(__x86_64__) 178 | // Ignore the blocks too far. 179 | if ((ULONG_PTR)pBlock < minAddr || (ULONG_PTR)pBlock >= maxAddr) 180 | continue; 181 | #endif 182 | // The block has at least one unused slot. 183 | if (pBlock->pFree != NULL) 184 | return pBlock; 185 | } 186 | 187 | #if defined(_M_X64) || defined(__x86_64__) 188 | // Alloc a new block above if not found. 189 | { 190 | LPVOID pAlloc = pOrigin; 191 | while ((ULONG_PTR)pAlloc >= minAddr) 192 | { 193 | pAlloc = FindPrevFreeRegion(pAlloc, (LPVOID)minAddr, si.dwAllocationGranularity); 194 | if (pAlloc == NULL) 195 | break; 196 | 197 | pBlock = (PMEMORY_BLOCK)VirtualAlloc( 198 | pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); 199 | if (pBlock != NULL) 200 | break; 201 | } 202 | } 203 | 204 | // Alloc a new block below if not found. 205 | if (pBlock == NULL) 206 | { 207 | LPVOID pAlloc = pOrigin; 208 | while ((ULONG_PTR)pAlloc <= maxAddr) 209 | { 210 | pAlloc = FindNextFreeRegion(pAlloc, (LPVOID)maxAddr, si.dwAllocationGranularity); 211 | if (pAlloc == NULL) 212 | break; 213 | 214 | pBlock = (PMEMORY_BLOCK)VirtualAlloc( 215 | pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); 216 | if (pBlock != NULL) 217 | break; 218 | } 219 | } 220 | #else 221 | // In x86 mode, a memory block can be placed anywhere. 222 | pBlock = (PMEMORY_BLOCK)VirtualAlloc( 223 | NULL, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); 224 | #endif 225 | 226 | if (pBlock != NULL) 227 | { 228 | // Build a linked list of all the slots. 229 | PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBlock + 1; 230 | pBlock->pFree = NULL; 231 | pBlock->usedCount = 0; 232 | do 233 | { 234 | pSlot->pNext = pBlock->pFree; 235 | pBlock->pFree = pSlot; 236 | pSlot++; 237 | } while ((ULONG_PTR)pSlot - (ULONG_PTR)pBlock <= MEMORY_BLOCK_SIZE - MEMORY_SLOT_SIZE); 238 | 239 | pBlock->pNext = g_pMemoryBlocks; 240 | g_pMemoryBlocks = pBlock; 241 | } 242 | 243 | return pBlock; 244 | } 245 | 246 | //------------------------------------------------------------------------- 247 | LPVOID AllocateBuffer(LPVOID pOrigin) 248 | { 249 | PMEMORY_SLOT pSlot; 250 | PMEMORY_BLOCK pBlock = GetMemoryBlock(pOrigin); 251 | if (pBlock == NULL) 252 | return NULL; 253 | 254 | // Remove an unused slot from the list. 255 | pSlot = pBlock->pFree; 256 | pBlock->pFree = pSlot->pNext; 257 | pBlock->usedCount++; 258 | #ifdef _DEBUG 259 | // Fill the slot with INT3 for debugging. 260 | memset(pSlot, 0xCC, sizeof(MEMORY_SLOT)); 261 | #endif 262 | return pSlot; 263 | } 264 | 265 | //------------------------------------------------------------------------- 266 | VOID FreeBuffer(LPVOID pBuffer) 267 | { 268 | PMEMORY_BLOCK pBlock = g_pMemoryBlocks; 269 | PMEMORY_BLOCK pPrev = NULL; 270 | ULONG_PTR pTargetBlock = ((ULONG_PTR)pBuffer / MEMORY_BLOCK_SIZE) * MEMORY_BLOCK_SIZE; 271 | 272 | while (pBlock != NULL) 273 | { 274 | if ((ULONG_PTR)pBlock == pTargetBlock) 275 | { 276 | PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBuffer; 277 | #ifdef _DEBUG 278 | // Clear the released slot for debugging. 279 | memset(pSlot, 0x00, sizeof(*pSlot)); 280 | #endif 281 | // Restore the released slot to the list. 282 | pSlot->pNext = pBlock->pFree; 283 | pBlock->pFree = pSlot; 284 | pBlock->usedCount--; 285 | 286 | // Free if unused. 287 | if (pBlock->usedCount == 0) 288 | { 289 | if (pPrev) 290 | pPrev->pNext = pBlock->pNext; 291 | else 292 | g_pMemoryBlocks = pBlock->pNext; 293 | 294 | VirtualFree(pBlock, 0, MEM_RELEASE); 295 | } 296 | 297 | break; 298 | } 299 | 300 | pPrev = pBlock; 301 | pBlock = pBlock->pNext; 302 | } 303 | } 304 | 305 | //------------------------------------------------------------------------- 306 | BOOL IsExecutableAddress(LPVOID pAddress) 307 | { 308 | MEMORY_BASIC_INFORMATION mi; 309 | VirtualQuery(pAddress, &mi, sizeof(mi)); 310 | 311 | return (mi.State == MEM_COMMIT && (mi.Protect & PAGE_EXECUTE_FLAGS)); 312 | } 313 | -------------------------------------------------------------------------------- /Libraries/MinHook/trampoline.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MinHook - The Minimalistic API Hooking Library for x64/x86 3 | * Copyright (C) 2009-2017 Tsuda Kageyu. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18 | * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19 | * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20 | * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #include 30 | 31 | #ifndef ARRAYSIZE 32 | #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) 33 | #endif 34 | 35 | #if defined(_M_X64) || defined(__x86_64__) 36 | #include "./hde/hde64.h" 37 | typedef hde64s HDE; 38 | #define HDE_DISASM(code, hs) hde64_disasm(code, hs) 39 | #else 40 | #include "./hde/hde32.h" 41 | typedef hde32s HDE; 42 | #define HDE_DISASM(code, hs) hde32_disasm(code, hs) 43 | #endif 44 | 45 | #include "trampoline.h" 46 | #include "buffer.h" 47 | 48 | // Maximum size of a trampoline function. 49 | #if defined(_M_X64) || defined(__x86_64__) 50 | #define TRAMPOLINE_MAX_SIZE (MEMORY_SLOT_SIZE - sizeof(JMP_ABS)) 51 | #else 52 | #define TRAMPOLINE_MAX_SIZE MEMORY_SLOT_SIZE 53 | #endif 54 | 55 | //------------------------------------------------------------------------- 56 | static BOOL IsCodePadding(LPBYTE pInst, UINT size) 57 | { 58 | UINT i; 59 | 60 | if (pInst[0] != 0x00 && pInst[0] != 0x90 && pInst[0] != 0xCC) 61 | return FALSE; 62 | 63 | for (i = 1; i < size; ++i) 64 | { 65 | if (pInst[i] != pInst[0]) 66 | return FALSE; 67 | } 68 | return TRUE; 69 | } 70 | 71 | //------------------------------------------------------------------------- 72 | BOOL CreateTrampolineFunction(PTRAMPOLINE ct) 73 | { 74 | #if defined(_M_X64) || defined(__x86_64__) 75 | CALL_ABS call = { 76 | 0xFF, 0x15, 0x00000002, // FF15 00000002: CALL [RIP+8] 77 | 0xEB, 0x08, // EB 08: JMP +10 78 | 0x0000000000000000ULL // Absolute destination address 79 | }; 80 | JMP_ABS jmp = { 81 | 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] 82 | 0x0000000000000000ULL // Absolute destination address 83 | }; 84 | JCC_ABS jcc = { 85 | 0x70, 0x0E, // 7* 0E: J** +16 86 | 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] 87 | 0x0000000000000000ULL // Absolute destination address 88 | }; 89 | #else 90 | CALL_REL call = { 91 | 0xE8, // E8 xxxxxxxx: CALL +5+xxxxxxxx 92 | 0x00000000 // Relative destination address 93 | }; 94 | JMP_REL jmp = { 95 | 0xE9, // E9 xxxxxxxx: JMP +5+xxxxxxxx 96 | 0x00000000 // Relative destination address 97 | }; 98 | JCC_REL jcc = { 99 | 0x0F, 0x80, // 0F8* xxxxxxxx: J** +6+xxxxxxxx 100 | 0x00000000 // Relative destination address 101 | }; 102 | #endif 103 | 104 | UINT8 oldPos = 0; 105 | UINT8 newPos = 0; 106 | ULONG_PTR jmpDest = 0; // Destination address of an internal jump. 107 | BOOL finished = FALSE; // Is the function completed? 108 | #if defined(_M_X64) || defined(__x86_64__) 109 | UINT8 instBuf[16]; 110 | #endif 111 | 112 | ct->patchAbove = FALSE; 113 | ct->nIP = 0; 114 | 115 | do 116 | { 117 | HDE hs; 118 | UINT copySize; 119 | LPVOID pCopySrc; 120 | ULONG_PTR pOldInst = (ULONG_PTR)ct->pTarget + oldPos; 121 | ULONG_PTR pNewInst = (ULONG_PTR)ct->pTrampoline + newPos; 122 | 123 | copySize = HDE_DISASM((LPVOID)pOldInst, &hs); 124 | if (hs.flags & F_ERROR) 125 | return FALSE; 126 | 127 | pCopySrc = (LPVOID)pOldInst; 128 | if (oldPos >= sizeof(JMP_REL)) 129 | { 130 | // The trampoline function is long enough. 131 | // Complete the function with the jump to the target function. 132 | #if defined(_M_X64) || defined(__x86_64__) 133 | jmp.address = pOldInst; 134 | #else 135 | jmp.operand = (UINT32)(pOldInst - (pNewInst + sizeof(jmp))); 136 | #endif 137 | pCopySrc = &jmp; 138 | copySize = sizeof(jmp); 139 | 140 | finished = TRUE; 141 | } 142 | #if defined(_M_X64) || defined(__x86_64__) 143 | else if ((hs.modrm & 0xC7) == 0x05) 144 | { 145 | // Instructions using RIP relative addressing. (ModR/M = 00???101B) 146 | 147 | // Modify the RIP relative address. 148 | PUINT32 pRelAddr; 149 | 150 | // Avoid using memcpy to reduce the footprint. 151 | #ifndef _MSC_VER 152 | memcpy(instBuf, (LPBYTE)pOldInst, copySize); 153 | #else 154 | __movsb(instBuf, (LPBYTE)pOldInst, copySize); 155 | #endif 156 | pCopySrc = instBuf; 157 | 158 | // Relative address is stored at (instruction length - immediate value length - 4). 159 | pRelAddr = (PUINT32)(instBuf + hs.len - ((hs.flags & 0x3C) >> 2) - 4); 160 | *pRelAddr 161 | = (UINT32)((pOldInst + hs.len + (INT32)hs.disp.disp32) - (pNewInst + hs.len)); 162 | 163 | // Complete the function if JMP (FF /4). 164 | if (hs.opcode == 0xFF && hs.modrm_reg == 4) 165 | finished = TRUE; 166 | } 167 | #endif 168 | else if (hs.opcode == 0xE8) 169 | { 170 | // Direct relative CALL 171 | ULONG_PTR dest = pOldInst + hs.len + (INT32)hs.imm.imm32; 172 | #if defined(_M_X64) || defined(__x86_64__) 173 | call.address = dest; 174 | #else 175 | call.operand = (UINT32)(dest - (pNewInst + sizeof(call))); 176 | #endif 177 | pCopySrc = &call; 178 | copySize = sizeof(call); 179 | } 180 | else if ((hs.opcode & 0xFD) == 0xE9) 181 | { 182 | // Direct relative JMP (EB or E9) 183 | ULONG_PTR dest = pOldInst + hs.len; 184 | 185 | if (hs.opcode == 0xEB) // isShort jmp 186 | dest += (INT8)hs.imm.imm8; 187 | else 188 | dest += (INT32)hs.imm.imm32; 189 | 190 | // Simply copy an internal jump. 191 | if ((ULONG_PTR)ct->pTarget <= dest 192 | && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) 193 | { 194 | if (jmpDest < dest) 195 | jmpDest = dest; 196 | } 197 | else 198 | { 199 | #if defined(_M_X64) || defined(__x86_64__) 200 | jmp.address = dest; 201 | #else 202 | jmp.operand = (UINT32)(dest - (pNewInst + sizeof(jmp))); 203 | #endif 204 | pCopySrc = &jmp; 205 | copySize = sizeof(jmp); 206 | 207 | // Exit the function If it is not in the branch 208 | finished = (pOldInst >= jmpDest); 209 | } 210 | } 211 | else if ((hs.opcode & 0xF0) == 0x70 212 | || (hs.opcode & 0xFC) == 0xE0 213 | || (hs.opcode2 & 0xF0) == 0x80) 214 | { 215 | // Direct relative Jcc 216 | ULONG_PTR dest = pOldInst + hs.len; 217 | 218 | if ((hs.opcode & 0xF0) == 0x70 // Jcc 219 | || (hs.opcode & 0xFC) == 0xE0) // LOOPNZ/LOOPZ/LOOP/JECXZ 220 | dest += (INT8)hs.imm.imm8; 221 | else 222 | dest += (INT32)hs.imm.imm32; 223 | 224 | // Simply copy an internal jump. 225 | if ((ULONG_PTR)ct->pTarget <= dest 226 | && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) 227 | { 228 | if (jmpDest < dest) 229 | jmpDest = dest; 230 | } 231 | else if ((hs.opcode & 0xFC) == 0xE0) 232 | { 233 | // LOOPNZ/LOOPZ/LOOP/JCXZ/JECXZ to the outside are not supported. 234 | return FALSE; 235 | } 236 | else 237 | { 238 | UINT8 cond = ((hs.opcode != 0x0F ? hs.opcode : hs.opcode2) & 0x0F); 239 | #if defined(_M_X64) || defined(__x86_64__) 240 | // Invert the condition in x64 mode to simplify the conditional jump logic. 241 | jcc.opcode = 0x71 ^ cond; 242 | jcc.address = dest; 243 | #else 244 | jcc.opcode1 = 0x80 | cond; 245 | jcc.operand = (UINT32)(dest - (pNewInst + sizeof(jcc))); 246 | #endif 247 | pCopySrc = &jcc; 248 | copySize = sizeof(jcc); 249 | } 250 | } 251 | else if ((hs.opcode & 0xFE) == 0xC2) 252 | { 253 | // RET (C2 or C3) 254 | 255 | // Complete the function if not in a branch. 256 | finished = (pOldInst >= jmpDest); 257 | } 258 | 259 | // Can't alter the instruction length in a branch. 260 | if (pOldInst < jmpDest && copySize != hs.len) 261 | return FALSE; 262 | 263 | // Trampoline function is too large. 264 | if ((newPos + copySize) > TRAMPOLINE_MAX_SIZE) 265 | return FALSE; 266 | 267 | // Trampoline function has too many instructions. 268 | if (ct->nIP >= ARRAYSIZE(ct->oldIPs)) 269 | return FALSE; 270 | 271 | ct->oldIPs[ct->nIP] = oldPos; 272 | ct->newIPs[ct->nIP] = newPos; 273 | ct->nIP++; 274 | 275 | // Avoid using memcpy to reduce the footprint. 276 | #ifndef _MSC_VER 277 | memcpy((LPBYTE)ct->pTrampoline + newPos, pCopySrc, copySize); 278 | #else 279 | __movsb((LPBYTE)ct->pTrampoline + newPos, pCopySrc, copySize); 280 | #endif 281 | newPos += copySize; 282 | oldPos += hs.len; 283 | } 284 | while (!finished); 285 | 286 | // Is there enough place for a long jump? 287 | if (oldPos < sizeof(JMP_REL) 288 | && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL) - oldPos)) 289 | { 290 | // Is there enough place for a short jump? 291 | if (oldPos < sizeof(JMP_REL_SHORT) 292 | && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL_SHORT) - oldPos)) 293 | { 294 | return FALSE; 295 | } 296 | 297 | // Can we place the long jump above the function? 298 | if (!IsExecutableAddress((LPBYTE)ct->pTarget - sizeof(JMP_REL))) 299 | return FALSE; 300 | 301 | if (!IsCodePadding((LPBYTE)ct->pTarget - sizeof(JMP_REL), sizeof(JMP_REL))) 302 | return FALSE; 303 | 304 | ct->patchAbove = TRUE; 305 | } 306 | 307 | #if defined(_M_X64) || defined(__x86_64__) 308 | // Create a relay function. 309 | jmp.address = (ULONG_PTR)ct->pDetour; 310 | 311 | ct->pRelay = (LPBYTE)ct->pTrampoline + newPos; 312 | memcpy(ct->pRelay, &jmp, sizeof(jmp)); 313 | #endif 314 | 315 | return TRUE; 316 | } 317 | -------------------------------------------------------------------------------- /Libraries/AppInitDispatcher/Utf8Ini.hpp: -------------------------------------------------------------------------------- 1 | #ifndef UTF8INI_H 2 | #define UTF8INI_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | class Utf8Ini 9 | { 10 | public: 11 | /** 12 | \brief Serialize to the INI file format. 13 | */ 14 | inline std::string Serialize() const 15 | { 16 | std::string output; 17 | for(const auto & section : mSections) 18 | { 19 | if(output.length()) 20 | appendLine(output, ""); 21 | appendLine(output, makeSectionText(section.first)); 22 | for(const auto & keyvalue : section.second) 23 | if(keyvalue.first.length()) 24 | appendLine(output, makeKeyValueText(keyvalue.first, keyvalue.second)); 25 | } 26 | return std::move(output); 27 | } 28 | 29 | /** 30 | \brief Deserialize from the INI file format. 31 | \param data The INI data. 32 | \param [out] errorLine The error line (only has a meaning when this function failed). 33 | \return true if it succeeds, false if it fails. 34 | */ 35 | inline bool Deserialize(const std::string & data, int & errorLine) 36 | { 37 | //initialize 38 | errorLine = 0; 39 | Clear(); 40 | 41 | //read lines 42 | std::vector lines; 43 | std::string curLine; 44 | for(auto ch : data) 45 | { 46 | switch(ch) 47 | { 48 | case '\r': 49 | break; 50 | case '\n': 51 | lines.push_back(trim(curLine)); 52 | curLine.clear(); 53 | break; 54 | default: 55 | curLine += ch; 56 | } 57 | } 58 | if(curLine.length()) 59 | lines.push_back(trim(curLine)); 60 | 61 | //parse lines 62 | std::string section = ""; 63 | for(const auto & line : lines) 64 | { 65 | errorLine++; 66 | switch(getLineType(line)) 67 | { 68 | case LineType::Invalid: 69 | return false; 70 | 71 | case LineType::Comment: 72 | case LineType::Empty: 73 | continue; 74 | 75 | case LineType::KeyValue: 76 | { 77 | std::string key; 78 | std::string value; 79 | if(!section.length() || 80 | !parseKeyValueLine(line, key, value) || 81 | !SetValue(section, key, value)) 82 | return false; 83 | } 84 | break; 85 | 86 | case LineType::Section: 87 | { 88 | if(!parseSectionLine(line, section)) 89 | return false; 90 | } 91 | break; 92 | 93 | default: 94 | return false; 95 | } 96 | } 97 | return true; 98 | } 99 | 100 | /** 101 | \brief Sets a value. This will overwrite older values. 102 | \param section The section. Must have a length greater than one. 103 | \param key The key. Must have a length greater than one. 104 | \param value The value. Can be empty (effectively removing the value). 105 | \return true if the value was set successfully, false otherwise. 106 | */ 107 | inline bool SetValue(const std::string & section, const std::string & key, const std::string & value) 108 | { 109 | auto trimmedSection = trim(section); 110 | auto trimmedKey = trim(key); 111 | if(!trimmedSection.length() || !trimmedKey.length()) 112 | return false; 113 | auto found = mSections.find(trimmedSection); 114 | if(found != mSections.end()) 115 | found->second[trimmedKey] = value; 116 | else 117 | { 118 | KeyValueMap keyValueMap; 119 | keyValueMap[trimmedKey] = value; 120 | mSections[trimmedSection] = keyValueMap; 121 | } 122 | return true; 123 | } 124 | 125 | /** 126 | \brief Removes all key/value pairs from a section. 127 | \param section The section to clear. 128 | \return true if it succeeds, false otherwise. 129 | */ 130 | inline bool ClearSection(const std::string & section) 131 | { 132 | auto trimmedSection = trim(section); 133 | if(!trimmedSection.length()) 134 | return false; 135 | auto found = mSections.find(trimmedSection); 136 | if(found == mSections.end()) 137 | return false; 138 | mSections.erase(found); 139 | return true; 140 | } 141 | 142 | /** 143 | \brief Removes all sections. 144 | */ 145 | inline void Clear() 146 | { 147 | mSections.clear(); 148 | } 149 | 150 | /** 151 | \brief Gets a value. 152 | \param section The section. 153 | \param key The key. 154 | \return The value. Empty string when the value was not found or empty. 155 | */ 156 | inline std::string GetValue(const std::string & section, const std::string & key) const 157 | { 158 | auto trimmedSection = trim(section); 159 | auto trimmedKey = trim(key); 160 | if(!trimmedSection.length() || !trimmedKey.length()) 161 | return ""; 162 | auto sectionFound = mSections.find(trimmedSection); 163 | if(sectionFound == mSections.end()) 164 | return ""; 165 | const auto & keyValueMap = sectionFound->second; 166 | auto keyFound = keyValueMap.find(trimmedKey); 167 | if(keyFound == keyValueMap.end()) 168 | return ""; 169 | return keyFound->second; 170 | } 171 | 172 | /** 173 | \brief Gets the section names. 174 | \return List of section names. 175 | */ 176 | inline std::vector Sections() const 177 | { 178 | std::vector sections; 179 | sections.reserve(mSections.size()); 180 | for(const auto & section : mSections) 181 | sections.push_back(section.first); 182 | return std::move(sections); 183 | } 184 | 185 | /** 186 | \brief Gets keys in a given section. 187 | \param section The section. 188 | \return List of keys in the section. Empty if the section is not found or empty. 189 | */ 190 | inline std::vector Keys(const std::string & section) const 191 | { 192 | std::vector keys; 193 | auto trimmedSection = trim(section); 194 | if(trimmedSection.length()) 195 | { 196 | auto found = mSections.find(trimmedSection); 197 | if(found != mSections.end()) 198 | { 199 | keys.reserve(found->second.size()); 200 | for(const auto & key : found->second) 201 | keys.push_back(key.first); 202 | } 203 | } 204 | return std::move(keys); 205 | } 206 | 207 | private: 208 | typedef std::map KeyValueMap; 209 | std::map mSections; 210 | 211 | enum class LineType 212 | { 213 | Invalid, 214 | Empty, 215 | Section, 216 | KeyValue, 217 | Comment 218 | }; 219 | 220 | static inline LineType getLineType(const std::string & line) 221 | { 222 | auto len = line.length(); 223 | if(!len) 224 | return LineType::Empty; 225 | if(line[0] == '[' && line[len - 1] == ']') 226 | return LineType::Section; 227 | if(line[0] == ';') 228 | return LineType::Comment; 229 | if(line.find('=') != std::string::npos) 230 | return LineType::KeyValue; 231 | return LineType::Invalid; 232 | } 233 | 234 | static inline std::string trim(const std::string & str) 235 | { 236 | auto len = str.length(); 237 | if(!len) 238 | return ""; 239 | size_t pre = 0; 240 | while(str[pre] == ' ') 241 | pre++; 242 | size_t post = 0; 243 | while(str[len - post - 1] == ' ' && post < len) 244 | post++; 245 | auto sublen = len - post - pre; 246 | return sublen > 0 ? str.substr(pre, len - post - pre) : ""; 247 | } 248 | 249 | static inline bool parseKeyValueLine(const std::string & line, std::string & key, std::string & value) 250 | { 251 | auto pos = line.find('='); 252 | key = trim(line.substr(0, pos)); 253 | value = trim(line.substr(pos + 1)); 254 | auto len = value.length(); 255 | if(len && value[0] == '\"' && value[len - 1] == '\"') 256 | value = unescapeValue(value); 257 | return true; 258 | } 259 | 260 | static inline bool parseSectionLine(const std::string & line, std::string & section) 261 | { 262 | section = trim(line.substr(1, line.length() - 2)); 263 | for (auto& ch : section) 264 | ch = tolower(ch); 265 | return section.length() > 0; 266 | } 267 | 268 | static inline void appendLine(std::string & output, const std::string & line) 269 | { 270 | if(output.length()) 271 | output += "\r\n"; 272 | output += line; 273 | } 274 | 275 | static inline std::string makeSectionText(const std::string & section) 276 | { 277 | return "[" + section + "]"; 278 | } 279 | 280 | static inline std::string makeKeyValueText(const std::string & key, const std::string & value) 281 | { 282 | return key + "=" + escapeValue(value); 283 | } 284 | 285 | static inline bool needsEscaping(const std::string & value) 286 | { 287 | auto len = value.length(); 288 | return len && (value[0] == ' ' || value[len - 1] == ' ' || 289 | value.find('\n') != std::string::npos || 290 | value.find('\"') != std::string::npos); 291 | } 292 | 293 | static inline std::string escapeValue(const std::string & value) 294 | { 295 | if(!needsEscaping(value)) 296 | return value; 297 | std::string escaped = "\""; 298 | for(auto ch : value) 299 | { 300 | switch(ch) 301 | { 302 | case '\"': 303 | escaped += "\\\""; 304 | break; 305 | case '\\': 306 | escaped += "\\\\"; 307 | break; 308 | case '\r': 309 | escaped += "\\r"; 310 | break; 311 | case '\n': 312 | escaped += "\\n"; 313 | break; 314 | case '\t': 315 | escaped += "\\t"; 316 | break; 317 | default: 318 | escaped += ch; 319 | } 320 | } 321 | escaped += "\""; 322 | return std::move(escaped); 323 | } 324 | 325 | static inline std::string unescapeValue(const std::string & str) 326 | { 327 | std::string result; 328 | auto bEscaped = false; 329 | for(auto ch : str) 330 | { 331 | if(!bEscaped) 332 | { 333 | switch(ch) 334 | { 335 | case '\"': 336 | break; 337 | case '\\': 338 | bEscaped = true; 339 | break; 340 | default: 341 | result += ch; 342 | } 343 | } 344 | else 345 | { 346 | switch(ch) 347 | { 348 | case 'r': 349 | result += '\r'; 350 | break; 351 | case 'n': 352 | result += '\n'; 353 | break; 354 | case 't': 355 | result += '\t'; 356 | break; 357 | default: 358 | result += ch; 359 | } 360 | bEscaped = false; 361 | } 362 | } 363 | if(bEscaped) 364 | result += '\\'; 365 | return std::move(result); 366 | } 367 | }; 368 | 369 | #endif //UTF8INI_H -------------------------------------------------------------------------------- /Libraries/MinHook/hook.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MinHook - The Minimalistic API Hooking Library for x64/x86 3 | * Copyright (C) 2009-2017 Tsuda Kageyu. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18 | * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19 | * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20 | * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #include 30 | #include 31 | #include 32 | 33 | #include "MinHook.h" 34 | #include "buffer.h" 35 | #include "trampoline.h" 36 | 37 | #ifndef ARRAYSIZE 38 | #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) 39 | #endif 40 | 41 | // Initial capacity of the HOOK_ENTRY buffer. 42 | #define INITIAL_HOOK_CAPACITY 32 43 | 44 | // Initial capacity of the thread IDs buffer. 45 | #define INITIAL_THREAD_CAPACITY 128 46 | 47 | // Special hook position values. 48 | #define INVALID_HOOK_POS UINT_MAX 49 | #define ALL_HOOKS_POS UINT_MAX 50 | 51 | // Freeze() action argument defines. 52 | #define ACTION_DISABLE 0 53 | #define ACTION_ENABLE 1 54 | #define ACTION_APPLY_QUEUED 2 55 | 56 | // Thread access rights for suspending/resuming threads. 57 | #define THREAD_ACCESS \ 58 | (THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | THREAD_SET_CONTEXT) 59 | 60 | // Hook information. 61 | typedef struct _HOOK_ENTRY 62 | { 63 | LPVOID pTarget; // Address of the target function. 64 | LPVOID pDetour; // Address of the detour or relay function. 65 | LPVOID pTrampoline; // Address of the trampoline function. 66 | UINT8 backup[8]; // Original prologue of the target function. 67 | 68 | UINT8 patchAbove : 1; // Uses the hot patch area. 69 | UINT8 isEnabled : 1; // Enabled. 70 | UINT8 queueEnable : 1; // Queued for enabling/disabling when != isEnabled. 71 | 72 | UINT nIP : 4; // Count of the instruction boundaries. 73 | UINT8 oldIPs[8]; // Instruction boundaries of the target function. 74 | UINT8 newIPs[8]; // Instruction boundaries of the trampoline function. 75 | } HOOK_ENTRY, *PHOOK_ENTRY; 76 | 77 | // Suspended threads for Freeze()/Unfreeze(). 78 | typedef struct _FROZEN_THREADS 79 | { 80 | LPDWORD pItems; // Data heap 81 | UINT capacity; // Size of allocated data heap, items 82 | UINT size; // Actual number of data items 83 | } FROZEN_THREADS, *PFROZEN_THREADS; 84 | 85 | //------------------------------------------------------------------------- 86 | // Global Variables: 87 | //------------------------------------------------------------------------- 88 | 89 | // Spin lock flag for EnterSpinLock()/LeaveSpinLock(). 90 | volatile LONG g_isLocked = FALSE; 91 | 92 | // Private heap handle. If not NULL, this library is initialized. 93 | HANDLE g_hHeap = NULL; 94 | 95 | // Hook entries. 96 | struct 97 | { 98 | PHOOK_ENTRY pItems; // Data heap 99 | UINT capacity; // Size of allocated data heap, items 100 | UINT size; // Actual number of data items 101 | } g_hooks; 102 | 103 | //------------------------------------------------------------------------- 104 | // Returns INVALID_HOOK_POS if not found. 105 | static UINT FindHookEntry(LPVOID pTarget) 106 | { 107 | UINT i; 108 | for (i = 0; i < g_hooks.size; ++i) 109 | { 110 | if ((ULONG_PTR)pTarget == (ULONG_PTR)g_hooks.pItems[i].pTarget) 111 | return i; 112 | } 113 | 114 | return INVALID_HOOK_POS; 115 | } 116 | 117 | //------------------------------------------------------------------------- 118 | static PHOOK_ENTRY AddHookEntry() 119 | { 120 | if (g_hooks.pItems == NULL) 121 | { 122 | g_hooks.capacity = INITIAL_HOOK_CAPACITY; 123 | g_hooks.pItems = (PHOOK_ENTRY)HeapAlloc( 124 | g_hHeap, 0, g_hooks.capacity * sizeof(HOOK_ENTRY)); 125 | if (g_hooks.pItems == NULL) 126 | return NULL; 127 | } 128 | else if (g_hooks.size >= g_hooks.capacity) 129 | { 130 | PHOOK_ENTRY p = (PHOOK_ENTRY)HeapReAlloc( 131 | g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity * 2) * sizeof(HOOK_ENTRY)); 132 | if (p == NULL) 133 | return NULL; 134 | 135 | g_hooks.capacity *= 2; 136 | g_hooks.pItems = p; 137 | } 138 | 139 | return &g_hooks.pItems[g_hooks.size++]; 140 | } 141 | 142 | //------------------------------------------------------------------------- 143 | static void DeleteHookEntry(UINT pos) 144 | { 145 | if (pos < g_hooks.size - 1) 146 | g_hooks.pItems[pos] = g_hooks.pItems[g_hooks.size - 1]; 147 | 148 | g_hooks.size--; 149 | 150 | if (g_hooks.capacity / 2 >= INITIAL_HOOK_CAPACITY && g_hooks.capacity / 2 >= g_hooks.size) 151 | { 152 | PHOOK_ENTRY p = (PHOOK_ENTRY)HeapReAlloc( 153 | g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity / 2) * sizeof(HOOK_ENTRY)); 154 | if (p == NULL) 155 | return; 156 | 157 | g_hooks.capacity /= 2; 158 | g_hooks.pItems = p; 159 | } 160 | } 161 | 162 | //------------------------------------------------------------------------- 163 | static DWORD_PTR FindOldIP(PHOOK_ENTRY pHook, DWORD_PTR ip) 164 | { 165 | UINT i; 166 | 167 | if (pHook->patchAbove && ip == ((DWORD_PTR)pHook->pTarget - sizeof(JMP_REL))) 168 | return (DWORD_PTR)pHook->pTarget; 169 | 170 | for (i = 0; i < pHook->nIP; ++i) 171 | { 172 | if (ip == ((DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i])) 173 | return (DWORD_PTR)pHook->pTarget + pHook->oldIPs[i]; 174 | } 175 | 176 | #if defined(_M_X64) || defined(__x86_64__) 177 | // Check relay function. 178 | if (ip == (DWORD_PTR)pHook->pDetour) 179 | return (DWORD_PTR)pHook->pTarget; 180 | #endif 181 | 182 | return 0; 183 | } 184 | 185 | //------------------------------------------------------------------------- 186 | static DWORD_PTR FindNewIP(PHOOK_ENTRY pHook, DWORD_PTR ip) 187 | { 188 | UINT i; 189 | for (i = 0; i < pHook->nIP; ++i) 190 | { 191 | if (ip == ((DWORD_PTR)pHook->pTarget + pHook->oldIPs[i])) 192 | return (DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i]; 193 | } 194 | 195 | return 0; 196 | } 197 | 198 | //------------------------------------------------------------------------- 199 | static void ProcessThreadIPs(HANDLE hThread, UINT pos, UINT action) 200 | { 201 | // If the thread suspended in the overwritten area, 202 | // move IP to the proper address. 203 | 204 | CONTEXT c; 205 | #if defined(_M_X64) || defined(__x86_64__) 206 | DWORD64 *pIP = &c.Rip; 207 | #else 208 | DWORD *pIP = &c.Eip; 209 | #endif 210 | UINT count; 211 | 212 | c.ContextFlags = CONTEXT_CONTROL; 213 | if (!GetThreadContext(hThread, &c)) 214 | return; 215 | 216 | if (pos == ALL_HOOKS_POS) 217 | { 218 | pos = 0; 219 | count = g_hooks.size; 220 | } 221 | else 222 | { 223 | count = pos + 1; 224 | } 225 | 226 | for (; pos < count; ++pos) 227 | { 228 | PHOOK_ENTRY pHook = &g_hooks.pItems[pos]; 229 | BOOL enable; 230 | DWORD_PTR ip; 231 | 232 | switch (action) 233 | { 234 | case ACTION_DISABLE: 235 | enable = FALSE; 236 | break; 237 | 238 | case ACTION_ENABLE: 239 | enable = TRUE; 240 | break; 241 | 242 | default: // ACTION_APPLY_QUEUED 243 | enable = pHook->queueEnable; 244 | break; 245 | } 246 | if (pHook->isEnabled == enable) 247 | continue; 248 | 249 | if (enable) 250 | ip = FindNewIP(pHook, *pIP); 251 | else 252 | ip = FindOldIP(pHook, *pIP); 253 | 254 | if (ip != 0) 255 | { 256 | *pIP = ip; 257 | SetThreadContext(hThread, &c); 258 | } 259 | } 260 | } 261 | 262 | //------------------------------------------------------------------------- 263 | static VOID EnumerateThreads(PFROZEN_THREADS pThreads) 264 | { 265 | HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); 266 | if (hSnapshot != INVALID_HANDLE_VALUE) 267 | { 268 | THREADENTRY32 te; 269 | te.dwSize = sizeof(THREADENTRY32); 270 | if (Thread32First(hSnapshot, &te)) 271 | { 272 | do 273 | { 274 | if (te.dwSize >= (FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(DWORD)) 275 | && te.th32OwnerProcessID == GetCurrentProcessId() 276 | && te.th32ThreadID != GetCurrentThreadId()) 277 | { 278 | if (pThreads->pItems == NULL) 279 | { 280 | pThreads->capacity = INITIAL_THREAD_CAPACITY; 281 | pThreads->pItems 282 | = (LPDWORD)HeapAlloc(g_hHeap, 0, pThreads->capacity * sizeof(DWORD)); 283 | if (pThreads->pItems == NULL) 284 | break; 285 | } 286 | else if (pThreads->size >= pThreads->capacity) 287 | { 288 | LPDWORD p = (LPDWORD)HeapReAlloc( 289 | g_hHeap, 0, pThreads->pItems, (pThreads->capacity * 2) * sizeof(DWORD)); 290 | if (p == NULL) 291 | break; 292 | 293 | pThreads->capacity *= 2; 294 | pThreads->pItems = p; 295 | } 296 | pThreads->pItems[pThreads->size++] = te.th32ThreadID; 297 | } 298 | 299 | te.dwSize = sizeof(THREADENTRY32); 300 | } while (Thread32Next(hSnapshot, &te)); 301 | } 302 | CloseHandle(hSnapshot); 303 | } 304 | } 305 | 306 | //------------------------------------------------------------------------- 307 | static VOID Freeze(PFROZEN_THREADS pThreads, UINT pos, UINT action) 308 | { 309 | pThreads->pItems = NULL; 310 | pThreads->capacity = 0; 311 | pThreads->size = 0; 312 | EnumerateThreads(pThreads); 313 | 314 | if (pThreads->pItems != NULL) 315 | { 316 | UINT i; 317 | for (i = 0; i < pThreads->size; ++i) 318 | { 319 | HANDLE hThread = OpenThread(THREAD_ACCESS, FALSE, pThreads->pItems[i]); 320 | if (hThread != NULL) 321 | { 322 | SuspendThread(hThread); 323 | ProcessThreadIPs(hThread, pos, action); 324 | CloseHandle(hThread); 325 | } 326 | } 327 | } 328 | } 329 | 330 | //------------------------------------------------------------------------- 331 | static VOID Unfreeze(PFROZEN_THREADS pThreads) 332 | { 333 | if (pThreads->pItems != NULL) 334 | { 335 | UINT i; 336 | for (i = 0; i < pThreads->size; ++i) 337 | { 338 | HANDLE hThread = OpenThread(THREAD_ACCESS, FALSE, pThreads->pItems[i]); 339 | if (hThread != NULL) 340 | { 341 | ResumeThread(hThread); 342 | CloseHandle(hThread); 343 | } 344 | } 345 | 346 | HeapFree(g_hHeap, 0, pThreads->pItems); 347 | } 348 | } 349 | 350 | //------------------------------------------------------------------------- 351 | static MH_STATUS EnableHookLL(UINT pos, BOOL enable) 352 | { 353 | PHOOK_ENTRY pHook = &g_hooks.pItems[pos]; 354 | DWORD oldProtect; 355 | SIZE_T patchSize = sizeof(JMP_REL); 356 | LPBYTE pPatchTarget = (LPBYTE)pHook->pTarget; 357 | 358 | if (pHook->patchAbove) 359 | { 360 | pPatchTarget -= sizeof(JMP_REL); 361 | patchSize += sizeof(JMP_REL_SHORT); 362 | } 363 | 364 | if (!VirtualProtect(pPatchTarget, patchSize, PAGE_EXECUTE_READWRITE, &oldProtect)) 365 | return MH_ERROR_MEMORY_PROTECT; 366 | 367 | if (enable) 368 | { 369 | PJMP_REL pJmp = (PJMP_REL)pPatchTarget; 370 | pJmp->opcode = 0xE9; 371 | pJmp->operand = (UINT32)((LPBYTE)pHook->pDetour - (pPatchTarget + sizeof(JMP_REL))); 372 | 373 | if (pHook->patchAbove) 374 | { 375 | PJMP_REL_SHORT pShortJmp = (PJMP_REL_SHORT)pHook->pTarget; 376 | pShortJmp->opcode = 0xEB; 377 | pShortJmp->operand = (UINT8)(0 - (sizeof(JMP_REL_SHORT) + sizeof(JMP_REL))); 378 | } 379 | } 380 | else 381 | { 382 | if (pHook->patchAbove) 383 | memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL) + sizeof(JMP_REL_SHORT)); 384 | else 385 | memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL)); 386 | } 387 | 388 | VirtualProtect(pPatchTarget, patchSize, oldProtect, &oldProtect); 389 | 390 | // Just-in-case measure. 391 | FlushInstructionCache(GetCurrentProcess(), pPatchTarget, patchSize); 392 | 393 | pHook->isEnabled = enable; 394 | pHook->queueEnable = enable; 395 | 396 | return MH_OK; 397 | } 398 | 399 | //------------------------------------------------------------------------- 400 | static MH_STATUS EnableAllHooksLL(BOOL enable) 401 | { 402 | MH_STATUS status = MH_OK; 403 | UINT i, first = INVALID_HOOK_POS; 404 | 405 | for (i = 0; i < g_hooks.size; ++i) 406 | { 407 | if (g_hooks.pItems[i].isEnabled != enable) 408 | { 409 | first = i; 410 | break; 411 | } 412 | } 413 | 414 | if (first != INVALID_HOOK_POS) 415 | { 416 | FROZEN_THREADS threads; 417 | Freeze(&threads, ALL_HOOKS_POS, enable ? ACTION_ENABLE : ACTION_DISABLE); 418 | 419 | for (i = first; i < g_hooks.size; ++i) 420 | { 421 | if (g_hooks.pItems[i].isEnabled != enable) 422 | { 423 | status = EnableHookLL(i, enable); 424 | if (status != MH_OK) 425 | break; 426 | } 427 | } 428 | 429 | Unfreeze(&threads); 430 | } 431 | 432 | return status; 433 | } 434 | 435 | //------------------------------------------------------------------------- 436 | static VOID EnterSpinLock(VOID) 437 | { 438 | SIZE_T spinCount = 0; 439 | 440 | // Wait until the flag is FALSE. 441 | while (InterlockedCompareExchange(&g_isLocked, TRUE, FALSE) != FALSE) 442 | { 443 | // No need to generate a memory barrier here, since InterlockedCompareExchange() 444 | // generates a full memory barrier itself. 445 | 446 | // Prevent the loop from being too busy. 447 | if (spinCount < 32) 448 | Sleep(0); 449 | else 450 | Sleep(1); 451 | 452 | spinCount++; 453 | } 454 | } 455 | 456 | //------------------------------------------------------------------------- 457 | static VOID LeaveSpinLock(VOID) 458 | { 459 | // No need to generate a memory barrier here, since InterlockedExchange() 460 | // generates a full memory barrier itself. 461 | 462 | InterlockedExchange(&g_isLocked, FALSE); 463 | } 464 | 465 | //------------------------------------------------------------------------- 466 | MH_STATUS WINAPI MH_Initialize(VOID) 467 | { 468 | MH_STATUS status = MH_OK; 469 | 470 | EnterSpinLock(); 471 | 472 | if (g_hHeap == NULL) 473 | { 474 | g_hHeap = HeapCreate(0, 0, 0); 475 | if (g_hHeap != NULL) 476 | { 477 | // Initialize the internal function buffer. 478 | InitializeBuffer(); 479 | } 480 | else 481 | { 482 | status = MH_ERROR_MEMORY_ALLOC; 483 | } 484 | } 485 | else 486 | { 487 | status = MH_ERROR_ALREADY_INITIALIZED; 488 | } 489 | 490 | LeaveSpinLock(); 491 | 492 | return status; 493 | } 494 | 495 | //------------------------------------------------------------------------- 496 | MH_STATUS WINAPI MH_Uninitialize(VOID) 497 | { 498 | MH_STATUS status = MH_OK; 499 | 500 | EnterSpinLock(); 501 | 502 | if (g_hHeap != NULL) 503 | { 504 | status = EnableAllHooksLL(FALSE); 505 | if (status == MH_OK) 506 | { 507 | // Free the internal function buffer. 508 | 509 | // HeapFree is actually not required, but some tools detect a false 510 | // memory leak without HeapFree. 511 | 512 | UninitializeBuffer(); 513 | 514 | HeapFree(g_hHeap, 0, g_hooks.pItems); 515 | HeapDestroy(g_hHeap); 516 | 517 | g_hHeap = NULL; 518 | 519 | g_hooks.pItems = NULL; 520 | g_hooks.capacity = 0; 521 | g_hooks.size = 0; 522 | } 523 | } 524 | else 525 | { 526 | status = MH_ERROR_NOT_INITIALIZED; 527 | } 528 | 529 | LeaveSpinLock(); 530 | 531 | return status; 532 | } 533 | 534 | //------------------------------------------------------------------------- 535 | MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal) 536 | { 537 | MH_STATUS status = MH_OK; 538 | 539 | EnterSpinLock(); 540 | 541 | if (g_hHeap != NULL) 542 | { 543 | if (IsExecutableAddress(pTarget) && IsExecutableAddress(pDetour)) 544 | { 545 | UINT pos = FindHookEntry(pTarget); 546 | if (pos == INVALID_HOOK_POS) 547 | { 548 | LPVOID pBuffer = AllocateBuffer(pTarget); 549 | if (pBuffer != NULL) 550 | { 551 | TRAMPOLINE ct; 552 | 553 | ct.pTarget = pTarget; 554 | ct.pDetour = pDetour; 555 | ct.pTrampoline = pBuffer; 556 | if (CreateTrampolineFunction(&ct)) 557 | { 558 | PHOOK_ENTRY pHook = AddHookEntry(); 559 | if (pHook != NULL) 560 | { 561 | pHook->pTarget = ct.pTarget; 562 | #if defined(_M_X64) || defined(__x86_64__) 563 | pHook->pDetour = ct.pRelay; 564 | #else 565 | pHook->pDetour = ct.pDetour; 566 | #endif 567 | pHook->pTrampoline = ct.pTrampoline; 568 | pHook->patchAbove = ct.patchAbove; 569 | pHook->isEnabled = FALSE; 570 | pHook->queueEnable = FALSE; 571 | pHook->nIP = ct.nIP; 572 | memcpy(pHook->oldIPs, ct.oldIPs, ARRAYSIZE(ct.oldIPs)); 573 | memcpy(pHook->newIPs, ct.newIPs, ARRAYSIZE(ct.newIPs)); 574 | 575 | // Back up the target function. 576 | 577 | if (ct.patchAbove) 578 | { 579 | memcpy( 580 | pHook->backup, 581 | (LPBYTE)pTarget - sizeof(JMP_REL), 582 | sizeof(JMP_REL) + sizeof(JMP_REL_SHORT)); 583 | } 584 | else 585 | { 586 | memcpy(pHook->backup, pTarget, sizeof(JMP_REL)); 587 | } 588 | 589 | if (ppOriginal != NULL) 590 | *ppOriginal = pHook->pTrampoline; 591 | } 592 | else 593 | { 594 | status = MH_ERROR_MEMORY_ALLOC; 595 | } 596 | } 597 | else 598 | { 599 | status = MH_ERROR_UNSUPPORTED_FUNCTION; 600 | } 601 | 602 | if (status != MH_OK) 603 | { 604 | FreeBuffer(pBuffer); 605 | } 606 | } 607 | else 608 | { 609 | status = MH_ERROR_MEMORY_ALLOC; 610 | } 611 | } 612 | else 613 | { 614 | status = MH_ERROR_ALREADY_CREATED; 615 | } 616 | } 617 | else 618 | { 619 | status = MH_ERROR_NOT_EXECUTABLE; 620 | } 621 | } 622 | else 623 | { 624 | status = MH_ERROR_NOT_INITIALIZED; 625 | } 626 | 627 | LeaveSpinLock(); 628 | 629 | return status; 630 | } 631 | 632 | //------------------------------------------------------------------------- 633 | MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget) 634 | { 635 | MH_STATUS status = MH_OK; 636 | 637 | EnterSpinLock(); 638 | 639 | if (g_hHeap != NULL) 640 | { 641 | UINT pos = FindHookEntry(pTarget); 642 | if (pos != INVALID_HOOK_POS) 643 | { 644 | if (g_hooks.pItems[pos].isEnabled) 645 | { 646 | FROZEN_THREADS threads; 647 | Freeze(&threads, pos, ACTION_DISABLE); 648 | 649 | status = EnableHookLL(pos, FALSE); 650 | 651 | Unfreeze(&threads); 652 | } 653 | 654 | if (status == MH_OK) 655 | { 656 | FreeBuffer(g_hooks.pItems[pos].pTrampoline); 657 | DeleteHookEntry(pos); 658 | } 659 | } 660 | else 661 | { 662 | status = MH_ERROR_NOT_CREATED; 663 | } 664 | } 665 | else 666 | { 667 | status = MH_ERROR_NOT_INITIALIZED; 668 | } 669 | 670 | LeaveSpinLock(); 671 | 672 | return status; 673 | } 674 | 675 | //------------------------------------------------------------------------- 676 | static MH_STATUS EnableHook(LPVOID pTarget, BOOL enable) 677 | { 678 | MH_STATUS status = MH_OK; 679 | 680 | EnterSpinLock(); 681 | 682 | if (g_hHeap != NULL) 683 | { 684 | if (pTarget == MH_ALL_HOOKS) 685 | { 686 | status = EnableAllHooksLL(enable); 687 | } 688 | else 689 | { 690 | FROZEN_THREADS threads; 691 | UINT pos = FindHookEntry(pTarget); 692 | if (pos != INVALID_HOOK_POS) 693 | { 694 | if (g_hooks.pItems[pos].isEnabled != enable) 695 | { 696 | Freeze(&threads, pos, ACTION_ENABLE); 697 | 698 | status = EnableHookLL(pos, enable); 699 | 700 | Unfreeze(&threads); 701 | } 702 | else 703 | { 704 | status = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED; 705 | } 706 | } 707 | else 708 | { 709 | status = MH_ERROR_NOT_CREATED; 710 | } 711 | } 712 | } 713 | else 714 | { 715 | status = MH_ERROR_NOT_INITIALIZED; 716 | } 717 | 718 | LeaveSpinLock(); 719 | 720 | return status; 721 | } 722 | 723 | //------------------------------------------------------------------------- 724 | MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget) 725 | { 726 | return EnableHook(pTarget, TRUE); 727 | } 728 | 729 | //------------------------------------------------------------------------- 730 | MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget) 731 | { 732 | return EnableHook(pTarget, FALSE); 733 | } 734 | 735 | //------------------------------------------------------------------------- 736 | static MH_STATUS QueueHook(LPVOID pTarget, BOOL queueEnable) 737 | { 738 | MH_STATUS status = MH_OK; 739 | 740 | EnterSpinLock(); 741 | 742 | if (g_hHeap != NULL) 743 | { 744 | if (pTarget == MH_ALL_HOOKS) 745 | { 746 | UINT i; 747 | for (i = 0; i < g_hooks.size; ++i) 748 | g_hooks.pItems[i].queueEnable = queueEnable; 749 | } 750 | else 751 | { 752 | UINT pos = FindHookEntry(pTarget); 753 | if (pos != INVALID_HOOK_POS) 754 | { 755 | g_hooks.pItems[pos].queueEnable = queueEnable; 756 | } 757 | else 758 | { 759 | status = MH_ERROR_NOT_CREATED; 760 | } 761 | } 762 | } 763 | else 764 | { 765 | status = MH_ERROR_NOT_INITIALIZED; 766 | } 767 | 768 | LeaveSpinLock(); 769 | 770 | return status; 771 | } 772 | 773 | //------------------------------------------------------------------------- 774 | MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget) 775 | { 776 | return QueueHook(pTarget, TRUE); 777 | } 778 | 779 | //------------------------------------------------------------------------- 780 | MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget) 781 | { 782 | return QueueHook(pTarget, FALSE); 783 | } 784 | 785 | //------------------------------------------------------------------------- 786 | MH_STATUS WINAPI MH_ApplyQueued(VOID) 787 | { 788 | MH_STATUS status = MH_OK; 789 | UINT i, first = INVALID_HOOK_POS; 790 | 791 | EnterSpinLock(); 792 | 793 | if (g_hHeap != NULL) 794 | { 795 | for (i = 0; i < g_hooks.size; ++i) 796 | { 797 | if (g_hooks.pItems[i].isEnabled != g_hooks.pItems[i].queueEnable) 798 | { 799 | first = i; 800 | break; 801 | } 802 | } 803 | 804 | if (first != INVALID_HOOK_POS) 805 | { 806 | FROZEN_THREADS threads; 807 | Freeze(&threads, ALL_HOOKS_POS, ACTION_APPLY_QUEUED); 808 | 809 | for (i = first; i < g_hooks.size; ++i) 810 | { 811 | PHOOK_ENTRY pHook = &g_hooks.pItems[i]; 812 | if (pHook->isEnabled != pHook->queueEnable) 813 | { 814 | status = EnableHookLL(i, pHook->queueEnable); 815 | if (status != MH_OK) 816 | break; 817 | } 818 | } 819 | 820 | Unfreeze(&threads); 821 | } 822 | } 823 | else 824 | { 825 | status = MH_ERROR_NOT_INITIALIZED; 826 | } 827 | 828 | LeaveSpinLock(); 829 | 830 | return status; 831 | } 832 | 833 | //------------------------------------------------------------------------- 834 | MH_STATUS WINAPI MH_CreateHookApiEx( 835 | LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, 836 | LPVOID *ppOriginal, LPVOID *ppTarget) 837 | { 838 | HMODULE hModule; 839 | LPVOID pTarget; 840 | 841 | hModule = GetModuleHandleW(pszModule); 842 | if (hModule == NULL) 843 | return MH_ERROR_MODULE_NOT_FOUND; 844 | 845 | pTarget = (LPVOID)GetProcAddress(hModule, pszProcName); 846 | if (pTarget == NULL) 847 | return MH_ERROR_FUNCTION_NOT_FOUND; 848 | 849 | if(ppTarget != NULL) 850 | *ppTarget = pTarget; 851 | 852 | return MH_CreateHook(pTarget, pDetour, ppOriginal); 853 | } 854 | 855 | //------------------------------------------------------------------------- 856 | MH_STATUS WINAPI MH_CreateHookApi( 857 | LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal) 858 | { 859 | return MH_CreateHookApiEx(pszModule, pszProcName, pDetour, ppOriginal, NULL); 860 | } 861 | 862 | //------------------------------------------------------------------------- 863 | const char * WINAPI MH_StatusToString(MH_STATUS status) 864 | { 865 | #define MH_ST2STR(x) \ 866 | case x: \ 867 | return #x; 868 | 869 | switch (status) { 870 | MH_ST2STR(MH_UNKNOWN) 871 | MH_ST2STR(MH_OK) 872 | MH_ST2STR(MH_ERROR_ALREADY_INITIALIZED) 873 | MH_ST2STR(MH_ERROR_NOT_INITIALIZED) 874 | MH_ST2STR(MH_ERROR_ALREADY_CREATED) 875 | MH_ST2STR(MH_ERROR_NOT_CREATED) 876 | MH_ST2STR(MH_ERROR_ENABLED) 877 | MH_ST2STR(MH_ERROR_DISABLED) 878 | MH_ST2STR(MH_ERROR_NOT_EXECUTABLE) 879 | MH_ST2STR(MH_ERROR_UNSUPPORTED_FUNCTION) 880 | MH_ST2STR(MH_ERROR_MEMORY_ALLOC) 881 | MH_ST2STR(MH_ERROR_MEMORY_PROTECT) 882 | MH_ST2STR(MH_ERROR_MODULE_NOT_FOUND) 883 | MH_ST2STR(MH_ERROR_FUNCTION_NOT_FOUND) 884 | } 885 | 886 | #undef MH_ST2STR 887 | 888 | return "(unknown)"; 889 | } 890 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------