Browse Source

First try

main
DangerKiddy 1 year ago
commit
43e872d13e
  1. 117
      MS Detours/Makefile
  2. 1577
      MS Detours/creatwth.cpp
  3. 2364
      MS Detours/detours.cpp
  4. 1059
      MS Detours/detours.h
  5. BIN
      MS Detours/detours.lib
  6. 27
      MS Detours/detver.h
  7. 4236
      MS Detours/disasm.cpp
  8. 2
      MS Detours/disolarm.cpp
  9. 2
      MS Detours/disolarm64.cpp
  10. 2
      MS Detours/disolia64.cpp
  11. 2
      MS Detours/disolx64.cpp
  12. 2
      MS Detours/disolx86.cpp
  13. 2251
      MS Detours/image.cpp
  14. 929
      MS Detours/modules.cpp
  15. 269
      MS Detours/uimports.cpp
  16. 46
      diddlerInternal/Firespread.cpp
  17. 7
      diddlerInternal/Firespread.h
  18. 36
      diddlerInternal/Flamethrower.cpp
  19. 5
      diddlerInternal/Flamethrower.h
  20. 165
      diddlerInternal/Global.cpp
  21. 245
      diddlerInternal/Global.h
  22. 197
      diddlerInternal/Harop.cpp
  23. 8
      diddlerInternal/Harop.h
  24. 14
      diddlerInternal/Jetpack.cpp
  25. 5
      diddlerInternal/Jetpack.h
  26. 117
      diddlerInternal/Makefile
  27. 68
      diddlerInternal/Mods.cpp
  28. 19
      diddlerInternal/Mods.h
  29. 89
      diddlerInternal/Raycaster.cpp
  30. 48
      diddlerInternal/Raycaster.h
  31. 165
      diddlerInternal/TDFuncs.cpp
  32. 3
      diddlerInternal/TDFuncs.h
  33. 0
      diddlerInternal/TDObjects.cpp
  34. 487
      diddlerInternal/TDObjects.h
  35. 109
      diddlerInternal/balloons.cpp
  36. 7
      diddlerInternal/balloons.h
  37. 251
      diddlerInternal/c4.cpp
  38. 7
      diddlerInternal/c4.h
  39. 555
      diddlerInternal/camera.cpp
  40. 29
      diddlerInternal/camera.h
  41. 34
      diddlerInternal/cameraManager.cpp
  42. 6
      diddlerInternal/cameraManager.h
  43. 423
      diddlerInternal/console.cpp
  44. 20
      diddlerInternal/console.h
  45. 61
      diddlerInternal/constClock.cpp
  46. 7
      diddlerInternal/constClock.h
  47. 8
      diddlerInternal/cutter.cpp
  48. 4
      diddlerInternal/cutter.h
  49. 1061
      diddlerInternal/detours.h
  50. 27
      diddlerInternal/detver.h
  51. 60
      diddlerInternal/diddlerInternal.rc
  52. 336
      diddlerInternal/diddlerInternal.vcxproj
  53. 545
      diddlerInternal/diddlerInternal.vcxproj.filters
  54. 197
      diddlerInternal/dllmain.cpp
  55. 103
      diddlerInternal/dotProjector.cpp
  56. 22
      diddlerInternal/dotProjector.h
  57. 76
      diddlerInternal/drawCube.cpp
  58. 6
      diddlerInternal/drawCube.h
  59. 43
      diddlerInternal/envOptions.cpp
  60. 7
      diddlerInternal/envOptions.h
  61. 33
      diddlerInternal/focusHook.cpp
  62. 7
      diddlerInternal/focusHook.h
  63. BIN
      diddlerInternal/glew32.dll
  64. 92
      diddlerInternal/glm/.appveyor.yml
  65. 61
      diddlerInternal/glm/.gitignore
  66. 428
      diddlerInternal/glm/.travis.yml
  67. 78
      diddlerInternal/glm/CMakeLists.txt
  68. 21
      diddlerInternal/glm/cmake/cmake_uninstall.cmake.in
  69. 11
      diddlerInternal/glm/cmake/glm/glmConfig-version.cmake
  70. 22
      diddlerInternal/glm/cmake/glm/glmConfig.cmake
  71. 539
      diddlerInternal/glm/common.hpp
  72. 54
      diddlerInternal/glm/copying.txt
  73. 394
      diddlerInternal/glm/detail/_features.hpp
  74. 27
      diddlerInternal/glm/detail/_fixes.hpp
  75. 81
      diddlerInternal/glm/detail/_noise.hpp
  76. 804
      diddlerInternal/glm/detail/_swizzle.hpp
  77. 682
      diddlerInternal/glm/detail/_swizzle_func.hpp
  78. 162
      diddlerInternal/glm/detail/_vectorize.hpp
  79. 50
      diddlerInternal/glm/detail/compute_common.hpp
  80. 30
      diddlerInternal/glm/detail/compute_vector_relational.hpp
  81. 792
      diddlerInternal/glm/detail/func_common.inl
  82. 231
      diddlerInternal/glm/detail/func_common_simd.inl
  83. 152
      diddlerInternal/glm/detail/func_exponential.inl
  84. 37
      diddlerInternal/glm/detail/func_exponential_simd.inl
  85. 243
      diddlerInternal/glm/detail/func_geometric.inl
  86. 163
      diddlerInternal/glm/detail/func_geometric_simd.inl
  87. 372
      diddlerInternal/glm/detail/func_integer.inl
  88. 65
      diddlerInternal/glm/detail/func_integer_simd.inl
  89. 443
      diddlerInternal/glm/detail/func_matrix.inl
  90. 249
      diddlerInternal/glm/detail/func_matrix_simd.inl
  91. 189
      diddlerInternal/glm/detail/func_packing.inl
  92. 6
      diddlerInternal/glm/detail/func_packing_simd.inl
  93. 197
      diddlerInternal/glm/detail/func_trigonometric.inl
  94. 0
      diddlerInternal/glm/detail/func_trigonometric_simd.inl
  95. 87
      diddlerInternal/glm/detail/func_vector_relational.inl
  96. 6
      diddlerInternal/glm/detail/func_vector_relational_simd.inl
  97. 263
      diddlerInternal/glm/detail/glm.cpp
  98. 230
      diddlerInternal/glm/detail/qualifier.hpp
  99. 1139
      diddlerInternal/glm/detail/setup.hpp
  100. 68
      diddlerInternal/glm/detail/type_float.hpp
  101. Some files were not shown because too many files have changed in this diff Show More

117
MS Detours/Makefile

@ -0,0 +1,117 @@
##############################################################################
##
## Makefile for Detours.
##
## Microsoft Research Detours Package, Version 4.0.1
##
## Copyright (c) Microsoft Corporation. All rights reserved.
##
ROOT = ..
!include "$(ROOT)\system.mak"
!IF "$(DETOURS_SOURCE_BROWSING)" == ""
DETOURS_SOURCE_BROWSING = 0
!ENDIF
#######################/#######################################################
##
CFLAGS=/W4 /WX /Zi /MT /Gy /Gm- /Zl /Od
!IF $(DETOURS_SOURCE_BROWSING)==1
CFLAGS=$(CFLAGS) /FR
!ELSE
CFLAGS=$(CFLAGS) /DWIN32_LEAN_AND_MEAN /D_WIN32_WINNT=0x501
!ENDIF
!IF "$(DETOURS_TARGET_PROCESSOR)" == "IA64"
CFLAGS=$(CFLAGS) /wd4163 # intrinsic rdtebex not available; using newer Windows headers with older compiler
!ENDIF
!if defined(DETOURS_WIN_7) && defined(DETOURS_CL_17_OR_NEWER)
CFLAGS=$(CFLAGS) /D_USING_V110_SDK71_
!elseif defined(DETOURS_ANALYZE)
CFLAGS=$(CFLAGS) /analyze
!endif
OBJS = \
$(OBJD)\detours.obj \
$(OBJD)\modules.obj \
$(OBJD)\disasm.obj \
$(OBJD)\image.obj \
$(OBJD)\creatwth.obj \
$(OBJD)\disolx86.obj \
$(OBJD)\disolx64.obj \
$(OBJD)\disolia64.obj \
$(OBJD)\disolarm.obj \
$(OBJD)\disolarm64.obj \
##############################################################################
##
.SUFFIXES: .cpp .h .obj
!ifdef DETOURS_ANALYZE
.cpp{$(OBJD)}.obj:
$(CC) $(CFLAGS) /Fd$(LIBD)\detours.pdb /Fo$(OBJD)\ /c $<
!else
.cpp{$(OBJD)}.obj::
$(CC) $(CFLAGS) /Fd$(LIBD)\detours.pdb /Fo$(OBJD)\ /c $<
!endif
##############################################################################
all: dirs \
$(LIBD)\detours.lib \
$(INCD)\detours.h \
$(INCD)\detver.h \
!IF $(DETOURS_SOURCE_BROWSING)==1
$(OBJD)\detours.bsc \
!endif
##############################################################################
clean:
-del *~ 2>nul
-del $(LIBD)\detours.pdb $(LIBD)\detours.lib 2>nul
-rmdir /q /s $(OBJD) 2>nul
realclean: clean
-rmdir /q /s $(OBJDS) 2>nul
##############################################################################
dirs:
@if not exist "$(INCD)" mkdir "$(INCD)" && echo. Created $(INCD)
@if not exist "$(LIBD)" mkdir "$(LIBD)" && echo. Created $(LIBD)
@if not exist "$(BIND)" mkdir "$(BIND)" && echo. Created $(BIND)
@if not exist "$(OBJD)" mkdir "$(OBJD)" && echo. Created $(OBJD)
$(OBJD)\detours.bsc : $(OBJS)
bscmake /v /n /o $@ $(OBJS:.obj=.sbr)
$(LIBD)\detours.lib : $(OBJS)
link /lib /out:$@ $(OBJS)
$(INCD)\detours.h : detours.h
copy detours.h $@
$(INCD)\detver.h : detver.h
copy detver.h $@
$(OBJD)\detours.obj : detours.cpp detours.h
$(OBJD)\modules.obj : modules.cpp detours.h
$(OBJD)\disasm.obj : disasm.cpp detours.h
$(OBJD)\image.obj : image.cpp detours.h
$(OBJD)\creatwth.obj : creatwth.cpp uimports.cpp detours.h
$(OBJD)\disolx86.obj: disasm.cpp detours.h
$(OBJD)\disolx64.obj: disasm.cpp detours.h
$(OBJD)\disolia64.obj: disasm.cpp detours.h
$(OBJD)\disolarm.obj: disasm.cpp detours.h
$(OBJD)\disolarm64.obj: disasm.cpp detours.h
test: all
cd $(MAKEDIR)\..\samples\slept
nmake /nologo test
cd $(MAKEDIR)
################################################################# End of File.

1577
MS Detours/creatwth.cpp

File diff suppressed because it is too large Load Diff

2364
MS Detours/detours.cpp

File diff suppressed because it is too large Load Diff

1059
MS Detours/detours.h

File diff suppressed because it is too large Load Diff

BIN
MS Detours/detours.lib

Binary file not shown.

27
MS Detours/detver.h

@ -0,0 +1,27 @@
//////////////////////////////////////////////////////////////////////////////
//
// Common version parameters.
//
// Microsoft Research Detours Package, Version 4.0.1
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#define _USING_V110_SDK71_ 1
#include "winver.h"
#if 0
#include <windows.h>
#include <detours.h>
#else
#ifndef DETOURS_STRINGIFY
#define DETOURS_STRINGIFY(x) DETOURS_STRINGIFY_(x)
#define DETOURS_STRINGIFY_(x) #x
#endif
#define VER_FILEFLAGSMASK 0x3fL
#define VER_FILEFLAGS 0x0L
#define VER_FILEOS 0x00040004L
#define VER_FILETYPE 0x00000002L
#define VER_FILESUBTYPE 0x00000000L
#endif
#define VER_DETOURS_BITS DETOUR_STRINGIFY(DETOURS_BITS)

4236
MS Detours/disasm.cpp

File diff suppressed because it is too large Load Diff

2
MS Detours/disolarm.cpp

@ -0,0 +1,2 @@
#define DETOURS_ARM_OFFLINE_LIBRARY
#include "disasm.cpp"

2
MS Detours/disolarm64.cpp

@ -0,0 +1,2 @@
#define DETOURS_ARM64_OFFLINE_LIBRARY
#include "disasm.cpp"

2
MS Detours/disolia64.cpp

@ -0,0 +1,2 @@
#define DETOURS_IA64_OFFLINE_LIBRARY
#include "disasm.cpp"

2
MS Detours/disolx64.cpp

@ -0,0 +1,2 @@
#define DETOURS_X64_OFFLINE_LIBRARY
#include "disasm.cpp"

2
MS Detours/disolx86.cpp

@ -0,0 +1,2 @@
#define DETOURS_X86_OFFLINE_LIBRARY
#include "disasm.cpp"

2251
MS Detours/image.cpp

File diff suppressed because it is too large Load Diff

929
MS Detours/modules.cpp

@ -0,0 +1,929 @@
//////////////////////////////////////////////////////////////////////////////
//
// Module Enumeration Functions (modules.cpp of detours.lib)
//
// Microsoft Research Detours Package, Version 4.0.1
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Module enumeration functions.
//
#define _CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS 1
#pragma warning(disable:4068) // unknown pragma (suppress)
#if _MSC_VER >= 1900
#pragma warning(push)
#pragma warning(disable:4091) // empty typedef
#endif
#define _ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE 1
#include <windows.h>
#if (_MSC_VER < 1310)
#else
#pragma warning(push)
#if _MSC_VER > 1400
#pragma warning(disable:6102 6103) // /analyze warnings
#endif
#include <strsafe.h>
#pragma warning(pop)
#endif
// #define DETOUR_DEBUG 1
#define DETOURS_INTERNAL
#include "detours.h"
#if DETOURS_VERSION != 0x4c0c1 // 0xMAJORcMINORcPATCH
#error detours.h version mismatch
#endif
#if _MSC_VER >= 1900
#pragma warning(pop)
#endif
#define CLR_DIRECTORY OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR]
#define IAT_DIRECTORY OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT]
//////////////////////////////////////////////////////////////////////////////
//
const GUID DETOUR_EXE_RESTORE_GUID = {
0x2ed7a3ff, 0x3339, 0x4a8d,
{ 0x80, 0x5c, 0xd4, 0x98, 0x15, 0x3f, 0xc2, 0x8f }};
//////////////////////////////////////////////////////////////////////////////
//
PDETOUR_SYM_INFO DetourLoadImageHlp(VOID)
{
static DETOUR_SYM_INFO symInfo;
static PDETOUR_SYM_INFO pSymInfo = NULL;
static BOOL failed = false;
if (failed) {
return NULL;
}
if (pSymInfo != NULL) {
return pSymInfo;
}
ZeroMemory(&symInfo, sizeof(symInfo));
// Create a real handle to the process.
#if 0
DuplicateHandle(GetCurrentProcess(),
GetCurrentProcess(),
GetCurrentProcess(),
&symInfo.hProcess,
0,
FALSE,
DUPLICATE_SAME_ACCESS);
#else
symInfo.hProcess = GetCurrentProcess();
#endif
symInfo.hDbgHelp = LoadLibraryExW(L"dbghelp.dll", NULL, 0);
if (symInfo.hDbgHelp == NULL) {
abort:
failed = true;
if (symInfo.hDbgHelp != NULL) {
FreeLibrary(symInfo.hDbgHelp);
}
symInfo.pfImagehlpApiVersionEx = NULL;
symInfo.pfSymInitialize = NULL;
symInfo.pfSymSetOptions = NULL;
symInfo.pfSymGetOptions = NULL;
symInfo.pfSymLoadModule64 = NULL;
symInfo.pfSymGetModuleInfo64 = NULL;
symInfo.pfSymFromName = NULL;
return NULL;
}
symInfo.pfImagehlpApiVersionEx
= (PF_ImagehlpApiVersionEx)GetProcAddress(symInfo.hDbgHelp,
"ImagehlpApiVersionEx");
symInfo.pfSymInitialize
= (PF_SymInitialize)GetProcAddress(symInfo.hDbgHelp, "SymInitialize");
symInfo.pfSymSetOptions
= (PF_SymSetOptions)GetProcAddress(symInfo.hDbgHelp, "SymSetOptions");
symInfo.pfSymGetOptions
= (PF_SymGetOptions)GetProcAddress(symInfo.hDbgHelp, "SymGetOptions");
symInfo.pfSymLoadModule64
= (PF_SymLoadModule64)GetProcAddress(symInfo.hDbgHelp, "SymLoadModule64");
symInfo.pfSymGetModuleInfo64
= (PF_SymGetModuleInfo64)GetProcAddress(symInfo.hDbgHelp, "SymGetModuleInfo64");
symInfo.pfSymFromName
= (PF_SymFromName)GetProcAddress(symInfo.hDbgHelp, "SymFromName");
API_VERSION av;
ZeroMemory(&av, sizeof(av));
av.MajorVersion = API_VERSION_NUMBER;
if (symInfo.pfImagehlpApiVersionEx == NULL ||
symInfo.pfSymInitialize == NULL ||
symInfo.pfSymLoadModule64 == NULL ||
symInfo.pfSymGetModuleInfo64 == NULL ||
symInfo.pfSymFromName == NULL) {
goto abort;
}
symInfo.pfImagehlpApiVersionEx(&av);
if (av.MajorVersion < API_VERSION_NUMBER) {
goto abort;
}
if (!symInfo.pfSymInitialize(symInfo.hProcess, NULL, FALSE)) {
// We won't retry the initialize if it fails.
goto abort;
}
if (symInfo.pfSymGetOptions != NULL && symInfo.pfSymSetOptions != NULL) {
DWORD dw = symInfo.pfSymGetOptions();
dw &= ~(SYMOPT_CASE_INSENSITIVE |
SYMOPT_UNDNAME |
SYMOPT_DEFERRED_LOADS |
0);
dw |= (
#if defined(SYMOPT_EXACT_SYMBOLS)
SYMOPT_EXACT_SYMBOLS |
#endif
#if defined(SYMOPT_NO_UNQUALIFIED_LOADS)
SYMOPT_NO_UNQUALIFIED_LOADS |
#endif
SYMOPT_DEFERRED_LOADS |
#if defined(SYMOPT_FAIL_CRITICAL_ERRORS)
SYMOPT_FAIL_CRITICAL_ERRORS |
#endif
#if defined(SYMOPT_INCLUDE_32BIT_MODULES)
SYMOPT_INCLUDE_32BIT_MODULES |
#endif
0);
symInfo.pfSymSetOptions(dw);
}
pSymInfo = &symInfo;
return pSymInfo;
}
PVOID WINAPI DetourFindFunction(_In_ PCSTR pszModule,
_In_ PCSTR pszFunction)
{
/////////////////////////////////////////////// First, try GetProcAddress.
//
#pragma prefast(suppress:28752, "We don't do the unicode conversion for LoadLibraryExA.")
HMODULE hModule = LoadLibraryExA(pszModule, NULL, 0);
if (hModule == NULL) {
return NULL;
}
PBYTE pbCode = (PBYTE)GetProcAddress(hModule, pszFunction);
if (pbCode) {
return pbCode;
}
////////////////////////////////////////////////////// Then try ImageHelp.
//
DETOUR_TRACE(("DetourFindFunction(%hs, %hs)\n", pszModule, pszFunction));
PDETOUR_SYM_INFO pSymInfo = DetourLoadImageHlp();
if (pSymInfo == NULL) {
DETOUR_TRACE(("DetourLoadImageHlp failed: %d\n",
GetLastError()));
return NULL;
}
if (pSymInfo->pfSymLoadModule64(pSymInfo->hProcess, NULL,
(PCHAR)pszModule, NULL,
(DWORD64)hModule, 0) == 0) {
if (ERROR_SUCCESS != GetLastError()) {
DETOUR_TRACE(("SymLoadModule64(%p) failed: %d\n",
pSymInfo->hProcess, GetLastError()));
return NULL;
}
}
HRESULT hrRet;
CHAR szFullName[512];
IMAGEHLP_MODULE64 modinfo;
ZeroMemory(&modinfo, sizeof(modinfo));
modinfo.SizeOfStruct = sizeof(modinfo);
if (!pSymInfo->pfSymGetModuleInfo64(pSymInfo->hProcess, (DWORD64)hModule, &modinfo)) {
DETOUR_TRACE(("SymGetModuleInfo64(%p, %p) failed: %d\n",
pSymInfo->hProcess, hModule, GetLastError()));
return NULL;
}
hrRet = StringCchCopyA(szFullName, sizeof(szFullName)/sizeof(CHAR), modinfo.ModuleName);
if (FAILED(hrRet)) {
DETOUR_TRACE(("StringCchCopyA failed: %08x\n", hrRet));
return NULL;
}
hrRet = StringCchCatA(szFullName, sizeof(szFullName)/sizeof(CHAR), "!");
if (FAILED(hrRet)) {
DETOUR_TRACE(("StringCchCatA failed: %08x\n", hrRet));
return NULL;
}
hrRet = StringCchCatA(szFullName, sizeof(szFullName)/sizeof(CHAR), pszFunction);
if (FAILED(hrRet)) {
DETOUR_TRACE(("StringCchCatA failed: %08x\n", hrRet));
return NULL;
}
struct CFullSymbol : SYMBOL_INFO {
CHAR szRestOfName[512];
} symbol;
ZeroMemory(&symbol, sizeof(symbol));
//symbol.ModBase = (ULONG64)hModule;
symbol.SizeOfStruct = sizeof(SYMBOL_INFO);
#ifdef DBHLPAPI
symbol.MaxNameLen = sizeof(symbol.szRestOfName)/sizeof(symbol.szRestOfName[0]);
#else
symbol.MaxNameLength = sizeof(symbol.szRestOfName)/sizeof(symbol.szRestOfName[0]);
#endif
if (!pSymInfo->pfSymFromName(pSymInfo->hProcess, szFullName, &symbol)) {
DETOUR_TRACE(("SymFromName(%hs) failed: %d\n", szFullName, GetLastError()));
return NULL;
}
#if defined(DETOURS_IA64)
// On the IA64, we get a raw code pointer from the symbol engine
// and have to convert it to a wrapped [code pointer, global pointer].
//
PPLABEL_DESCRIPTOR pldEntry = (PPLABEL_DESCRIPTOR)DetourGetEntryPoint(hModule);
PPLABEL_DESCRIPTOR pldSymbol = new PLABEL_DESCRIPTOR;
pldSymbol->EntryPoint = symbol.Address;
pldSymbol->GlobalPointer = pldEntry->GlobalPointer;
return (PBYTE)pldSymbol;
#elif defined(DETOURS_ARM)
// On the ARM, we get a raw code pointer, which we must convert into a
// valied Thumb2 function pointer.
return DETOURS_PBYTE_TO_PFUNC(symbol.Address);
#else
return (PBYTE)symbol.Address;
#endif
}
//////////////////////////////////////////////////// Module Image Functions.
//
HMODULE WINAPI DetourEnumerateModules(_In_opt_ HMODULE hModuleLast)
{
PBYTE pbLast = (PBYTE)hModuleLast + MM_ALLOCATION_GRANULARITY;
MEMORY_BASIC_INFORMATION mbi;
ZeroMemory(&mbi, sizeof(mbi));
// Find the next memory region that contains a mapped PE image.
//
for (;; pbLast = (PBYTE)mbi.BaseAddress + mbi.RegionSize) {
if (VirtualQuery(pbLast, &mbi, sizeof(mbi)) <= 0) {
break;
}
// Skip uncommitted regions and guard pages.
//
if ((mbi.State != MEM_COMMIT) ||
((mbi.Protect & 0xff) == PAGE_NOACCESS) ||
(mbi.Protect & PAGE_GUARD)) {
continue;
}
__try {
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pbLast;
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE ||
(DWORD)pDosHeader->e_lfanew > mbi.RegionSize ||
(DWORD)pDosHeader->e_lfanew < sizeof(*pDosHeader)) {
continue;
}
PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((PBYTE)pDosHeader +
pDosHeader->e_lfanew);
if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) {
continue;
}
return (HMODULE)pDosHeader;
}
#pragma prefast(suppress:28940, "A bad pointer means this probably isn't a PE header.")
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
continue;
}
}
return NULL;
}
PVOID WINAPI DetourGetEntryPoint(_In_opt_ HMODULE hModule)
{
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)hModule;
if (hModule == NULL) {
pDosHeader = (PIMAGE_DOS_HEADER)GetModuleHandleW(NULL);
}
__try {
#pragma warning(suppress:6011) // GetModuleHandleW(NULL) never returns NULL.
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
SetLastError(ERROR_BAD_EXE_FORMAT);
return NULL;
}
PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((PBYTE)pDosHeader +
pDosHeader->e_lfanew);
if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) {
SetLastError(ERROR_INVALID_EXE_SIGNATURE);
return NULL;
}
if (pNtHeader->FileHeader.SizeOfOptionalHeader == 0) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return NULL;
}
PDETOUR_CLR_HEADER pClrHeader = NULL;
if (pNtHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
if (((PIMAGE_NT_HEADERS32)pNtHeader)->CLR_DIRECTORY.VirtualAddress != 0 &&
((PIMAGE_NT_HEADERS32)pNtHeader)->CLR_DIRECTORY.Size != 0) {
pClrHeader = (PDETOUR_CLR_HEADER)
(((PBYTE)pDosHeader)
+ ((PIMAGE_NT_HEADERS32)pNtHeader)->CLR_DIRECTORY.VirtualAddress);
}
}
else if (pNtHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
if (((PIMAGE_NT_HEADERS64)pNtHeader)->CLR_DIRECTORY.VirtualAddress != 0 &&
((PIMAGE_NT_HEADERS64)pNtHeader)->CLR_DIRECTORY.Size != 0) {
pClrHeader = (PDETOUR_CLR_HEADER)
(((PBYTE)pDosHeader)
+ ((PIMAGE_NT_HEADERS64)pNtHeader)->CLR_DIRECTORY.VirtualAddress);
}
}
if (pClrHeader != NULL) {
// For MSIL assemblies, we want to use the _Cor entry points.
HMODULE hClr = GetModuleHandleW(L"MSCOREE.DLL");
if (hClr == NULL) {
return NULL;
}
SetLastError(NO_ERROR);
return GetProcAddress(hClr, "_CorExeMain");
}
SetLastError(NO_ERROR);
// Pure resource DLLs have neither an entry point nor CLR information
// so handle them by returning NULL (LastError is NO_ERROR)
if (pNtHeader->OptionalHeader.AddressOfEntryPoint == 0) {
return NULL;
}
return ((PBYTE)pDosHeader) +
pNtHeader->OptionalHeader.AddressOfEntryPoint;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return NULL;
}
}
ULONG WINAPI DetourGetModuleSize(_In_opt_ HMODULE hModule)
{
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)hModule;
if (hModule == NULL) {
pDosHeader = (PIMAGE_DOS_HEADER)GetModuleHandleW(NULL);
}
__try {
#pragma warning(suppress:6011) // GetModuleHandleW(NULL) never returns NULL.
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
SetLastError(ERROR_BAD_EXE_FORMAT);
return NULL;
}
PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((PBYTE)pDosHeader +
pDosHeader->e_lfanew);
if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) {
SetLastError(ERROR_INVALID_EXE_SIGNATURE);
return NULL;
}
if (pNtHeader->FileHeader.SizeOfOptionalHeader == 0) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return NULL;
}
SetLastError(NO_ERROR);
return (pNtHeader->OptionalHeader.SizeOfImage);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return NULL;
}
}
HMODULE WINAPI DetourGetContainingModule(_In_ PVOID pvAddr)
{
MEMORY_BASIC_INFORMATION mbi;
ZeroMemory(&mbi, sizeof(mbi));
__try {
if (VirtualQuery(pvAddr, &mbi, sizeof(mbi)) <= 0) {
SetLastError(ERROR_BAD_EXE_FORMAT);
return NULL;
}
// Skip uncommitted regions and guard pages.
//
if ((mbi.State != MEM_COMMIT) ||
((mbi.Protect & 0xff) == PAGE_NOACCESS) ||
(mbi.Protect & PAGE_GUARD)) {
SetLastError(ERROR_BAD_EXE_FORMAT);
return NULL;
}
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mbi.AllocationBase;
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
SetLastError(ERROR_BAD_EXE_FORMAT);
return NULL;
}
PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((PBYTE)pDosHeader +
pDosHeader->e_lfanew);
if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) {
SetLastError(ERROR_INVALID_EXE_SIGNATURE);
return NULL;
}
if (pNtHeader->FileHeader.SizeOfOptionalHeader == 0) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return NULL;
}
SetLastError(NO_ERROR);
return (HMODULE)pDosHeader;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
SetLastError(ERROR_INVALID_EXE_SIGNATURE);
return NULL;
}
}
static inline PBYTE RvaAdjust(_Pre_notnull_ PIMAGE_DOS_HEADER pDosHeader, _In_ DWORD raddr)
{
if (raddr != NULL) {
return ((PBYTE)pDosHeader) + raddr;
}
return NULL;
}
BOOL WINAPI DetourEnumerateExports(_In_ HMODULE hModule,
_In_opt_ PVOID pContext,
_In_ PF_DETOUR_ENUMERATE_EXPORT_CALLBACK pfExport)
{
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)hModule;
if (hModule == NULL) {
pDosHeader = (PIMAGE_DOS_HEADER)GetModuleHandleW(NULL);
}
__try {
#pragma warning(suppress:6011) // GetModuleHandleW(NULL) never returns NULL.
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
SetLastError(ERROR_BAD_EXE_FORMAT);
return NULL;
}
PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((PBYTE)pDosHeader +
pDosHeader->e_lfanew);
if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) {
SetLastError(ERROR_INVALID_EXE_SIGNATURE);
return FALSE;
}
if (pNtHeader->FileHeader.SizeOfOptionalHeader == 0) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return FALSE;
}
PIMAGE_EXPORT_DIRECTORY pExportDir
= (PIMAGE_EXPORT_DIRECTORY)
RvaAdjust(pDosHeader,
pNtHeader->OptionalHeader
.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
if (pExportDir == NULL) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return FALSE;
}
PBYTE pExportDirEnd = (PBYTE)pExportDir + pNtHeader->OptionalHeader
.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
PDWORD pdwFunctions = (PDWORD)RvaAdjust(pDosHeader, pExportDir->AddressOfFunctions);
PDWORD pdwNames = (PDWORD)RvaAdjust(pDosHeader, pExportDir->AddressOfNames);
PWORD pwOrdinals = (PWORD)RvaAdjust(pDosHeader, pExportDir->AddressOfNameOrdinals);
for (DWORD nFunc = 0; nFunc < pExportDir->NumberOfFunctions; nFunc++) {
PBYTE pbCode = (pdwFunctions != NULL)
? (PBYTE)RvaAdjust(pDosHeader, pdwFunctions[nFunc]) : NULL;
PCHAR pszName = NULL;
// if the pointer is in the export region, then it is a forwarder.
if (pbCode > (PBYTE)pExportDir && pbCode < pExportDirEnd) {
pbCode = NULL;
}
for (DWORD n = 0; n < pExportDir->NumberOfNames; n++) {
if (pwOrdinals[n] == nFunc) {
pszName = (pdwNames != NULL)
? (PCHAR)RvaAdjust(pDosHeader, pdwNames[n]) : NULL;
break;
}
}
ULONG nOrdinal = pExportDir->Base + nFunc;
if (!pfExport(pContext, nOrdinal, pszName, pbCode)) {
break;
}
}
SetLastError(NO_ERROR);
return TRUE;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return NULL;
}
}
BOOL WINAPI DetourEnumerateImportsEx(_In_opt_ HMODULE hModule,
_In_opt_ PVOID pContext,
_In_opt_ PF_DETOUR_IMPORT_FILE_CALLBACK pfImportFile,
_In_opt_ PF_DETOUR_IMPORT_FUNC_CALLBACK_EX pfImportFunc)
{
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)hModule;
if (hModule == NULL) {
pDosHeader = (PIMAGE_DOS_HEADER)GetModuleHandleW(NULL);
}
__try {
#pragma warning(suppress:6011) // GetModuleHandleW(NULL) never returns NULL.
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
SetLastError(ERROR_BAD_EXE_FORMAT);
return FALSE;
}
PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((PBYTE)pDosHeader +
pDosHeader->e_lfanew);
if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) {
SetLastError(ERROR_INVALID_EXE_SIGNATURE);
return FALSE;
}
if (pNtHeader->FileHeader.SizeOfOptionalHeader == 0) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return FALSE;
}
PIMAGE_IMPORT_DESCRIPTOR iidp
= (PIMAGE_IMPORT_DESCRIPTOR)
RvaAdjust(pDosHeader,
pNtHeader->OptionalHeader
.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
if (iidp == NULL) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return FALSE;
}
for (; iidp->OriginalFirstThunk != 0; iidp++) {
PCSTR pszName = (PCHAR)RvaAdjust(pDosHeader, iidp->Name);
if (pszName == NULL) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return FALSE;
}
PIMAGE_THUNK_DATA pThunks = (PIMAGE_THUNK_DATA)
RvaAdjust(pDosHeader, iidp->OriginalFirstThunk);
PVOID * pAddrs = (PVOID *)
RvaAdjust(pDosHeader, iidp->FirstThunk);
HMODULE hFile = DetourGetContainingModule(pAddrs[0]);
if (pfImportFile != NULL) {
if (!pfImportFile(pContext, hFile, pszName)) {
break;
}
}
DWORD nNames = 0;
if (pThunks) {
for (; pThunks[nNames].u1.Ordinal; nNames++) {
DWORD nOrdinal = 0;
PCSTR pszFunc = NULL;
if (IMAGE_SNAP_BY_ORDINAL(pThunks[nNames].u1.Ordinal)) {
nOrdinal = (DWORD)IMAGE_ORDINAL(pThunks[nNames].u1.Ordinal);
}
else {
pszFunc = (PCSTR)RvaAdjust(pDosHeader,
(DWORD)pThunks[nNames].u1.AddressOfData + 2);
}
if (pfImportFunc != NULL) {
if (!pfImportFunc(pContext,
nOrdinal,
pszFunc,
&pAddrs[nNames])) {
break;
}
}
}
if (pfImportFunc != NULL) {
pfImportFunc(pContext, 0, NULL, NULL);
}
}
}
if (pfImportFile != NULL) {
pfImportFile(pContext, NULL, NULL);
}
SetLastError(NO_ERROR);
return TRUE;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return FALSE;
}
}
// Context for DetourEnumerateImportsThunk, which adapts "regular" callbacks for use with "Ex".
struct _DETOUR_ENUMERATE_IMPORTS_THUNK_CONTEXT
{
PVOID pContext;
PF_DETOUR_IMPORT_FUNC_CALLBACK pfImportFunc;
};
// Callback for DetourEnumerateImportsEx that adapts DetourEnumerateImportsEx
// for use with a DetourEnumerateImports callback -- derefence the IAT and pass the value on.
static
BOOL
CALLBACK
DetourEnumerateImportsThunk(_In_ PVOID VoidContext,
_In_ DWORD nOrdinal,
_In_opt_ PCSTR pszFunc,
_In_opt_ PVOID* ppvFunc)
{
_DETOUR_ENUMERATE_IMPORTS_THUNK_CONTEXT const * const
pContext = (_DETOUR_ENUMERATE_IMPORTS_THUNK_CONTEXT*)VoidContext;
return pContext->pfImportFunc(pContext->pContext, nOrdinal, pszFunc, ppvFunc ? *ppvFunc : NULL);
}
BOOL WINAPI DetourEnumerateImports(_In_opt_ HMODULE hModule,
_In_opt_ PVOID pContext,
_In_opt_ PF_DETOUR_IMPORT_FILE_CALLBACK pfImportFile,
_In_opt_ PF_DETOUR_IMPORT_FUNC_CALLBACK pfImportFunc)
{
_DETOUR_ENUMERATE_IMPORTS_THUNK_CONTEXT const context = { pContext, pfImportFunc };
return DetourEnumerateImportsEx(hModule,
(PVOID)&context,
pfImportFile,
&DetourEnumerateImportsThunk);
}
static PDETOUR_LOADED_BINARY WINAPI GetPayloadSectionFromModule(HMODULE hModule)
{
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)hModule;
if (hModule == NULL) {
pDosHeader = (PIMAGE_DOS_HEADER)GetModuleHandleW(NULL);
}
__try {
#pragma warning(suppress:6011) // GetModuleHandleW(NULL) never returns NULL.
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
SetLastError(ERROR_BAD_EXE_FORMAT);
return NULL;
}
PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((PBYTE)pDosHeader +
pDosHeader->e_lfanew);
if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) {
SetLastError(ERROR_INVALID_EXE_SIGNATURE);
return NULL;
}
if (pNtHeader->FileHeader.SizeOfOptionalHeader == 0) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return NULL;
}
PIMAGE_SECTION_HEADER pSectionHeaders
= (PIMAGE_SECTION_HEADER)((PBYTE)pNtHeader
+ sizeof(pNtHeader->Signature)
+ sizeof(pNtHeader->FileHeader)
+ pNtHeader->FileHeader.SizeOfOptionalHeader);
for (DWORD n = 0; n < pNtHeader->FileHeader.NumberOfSections; n++) {
if (strcmp((PCHAR)pSectionHeaders[n].Name, ".detour") == 0) {
if (pSectionHeaders[n].VirtualAddress == 0 ||
pSectionHeaders[n].SizeOfRawData == 0) {
break;
}
PBYTE pbData = (PBYTE)pDosHeader + pSectionHeaders[n].VirtualAddress;
DETOUR_SECTION_HEADER *pHeader = (DETOUR_SECTION_HEADER *)pbData;
if (pHeader->cbHeaderSize < sizeof(DETOUR_SECTION_HEADER) ||
pHeader->nSignature != DETOUR_SECTION_HEADER_SIGNATURE) {
break;
}
if (pHeader->nDataOffset == 0) {
pHeader->nDataOffset = pHeader->cbHeaderSize;
}
SetLastError(NO_ERROR);
return (PBYTE)pHeader;
}
}
SetLastError(ERROR_EXE_MARKED_INVALID);
return NULL;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return NULL;
}
}
DWORD WINAPI DetourGetSizeOfPayloads(_In_opt_ HMODULE hModule)
{
PDETOUR_LOADED_BINARY pBinary = GetPayloadSectionFromModule(hModule);
if (pBinary == NULL) {
// Error set by GetPayloadSectionFromModule.
return 0;
}
__try {
DETOUR_SECTION_HEADER *pHeader = (DETOUR_SECTION_HEADER *)pBinary;
if (pHeader->cbHeaderSize < sizeof(DETOUR_SECTION_HEADER) ||
pHeader->nSignature != DETOUR_SECTION_HEADER_SIGNATURE) {
SetLastError(ERROR_INVALID_HANDLE);
return 0;
}
SetLastError(NO_ERROR);
return pHeader->cbDataSize;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
SetLastError(ERROR_INVALID_HANDLE);
return 0;
}
}
_Writable_bytes_(*pcbData)
_Readable_bytes_(*pcbData)
_Success_(return != NULL)
PVOID WINAPI DetourFindPayload(_In_opt_ HMODULE hModule,
_In_ REFGUID rguid,
_Out_ DWORD *pcbData)
{
PBYTE pbData = NULL;
if (pcbData) {
*pcbData = 0;
}
PDETOUR_LOADED_BINARY pBinary = GetPayloadSectionFromModule(hModule);
if (pBinary == NULL) {
// Error set by GetPayloadSectionFromModule.
return NULL;
}
__try {
DETOUR_SECTION_HEADER *pHeader = (DETOUR_SECTION_HEADER *)pBinary;
if (pHeader->cbHeaderSize < sizeof(DETOUR_SECTION_HEADER) ||
pHeader->nSignature != DETOUR_SECTION_HEADER_SIGNATURE) {
SetLastError(ERROR_INVALID_EXE_SIGNATURE);
return NULL;
}
PBYTE pbBeg = ((PBYTE)pHeader) + pHeader->nDataOffset;
PBYTE pbEnd = ((PBYTE)pHeader) + pHeader->cbDataSize;
for (pbData = pbBeg; pbData < pbEnd;) {
DETOUR_SECTION_RECORD *pSection = (DETOUR_SECTION_RECORD *)pbData;
if (pSection->guid.Data1 == rguid.Data1 &&
pSection->guid.Data2 == rguid.Data2 &&
pSection->guid.Data3 == rguid.Data3 &&
pSection->guid.Data4[0] == rguid.Data4[0] &&
pSection->guid.Data4[1] == rguid.Data4[1] &&
pSection->guid.Data4[2] == rguid.Data4[2] &&
pSection->guid.Data4[3] == rguid.Data4[3] &&
pSection->guid.Data4[4] == rguid.Data4[4] &&
pSection->guid.Data4[5] == rguid.Data4[5] &&
pSection->guid.Data4[6] == rguid.Data4[6] &&
pSection->guid.Data4[7] == rguid.Data4[7]) {
if (pcbData) {
*pcbData = pSection->cbBytes - sizeof(*pSection);
SetLastError(NO_ERROR);
return (PBYTE)(pSection + 1);
}
}
pbData = (PBYTE)pSection + pSection->cbBytes;
}
SetLastError(ERROR_INVALID_HANDLE);
return NULL;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
SetLastError(ERROR_INVALID_HANDLE);
return NULL;
}
}
_Writable_bytes_(*pcbData)
_Readable_bytes_(*pcbData)
_Success_(return != NULL)
PVOID WINAPI DetourFindPayloadEx(_In_ REFGUID rguid,
_Out_ DWORD * pcbData)
{
for (HMODULE hMod = NULL; (hMod = DetourEnumerateModules(hMod)) != NULL;) {
PVOID pvData;
pvData = DetourFindPayload(hMod, rguid, pcbData);
if (pvData != NULL) {
return pvData;
}
}
SetLastError(ERROR_MOD_NOT_FOUND);
return NULL;
}
BOOL WINAPI DetourRestoreAfterWithEx(_In_reads_bytes_(cbData) PVOID pvData,
_In_ DWORD cbData)
{
PDETOUR_EXE_RESTORE pder = (PDETOUR_EXE_RESTORE)pvData;
if (pder->cb != sizeof(*pder) || pder->cb > cbData) {
SetLastError(ERROR_BAD_EXE_FORMAT);
return FALSE;
}
DWORD dwPermIdh = ~0u;
DWORD dwPermInh = ~0u;
DWORD dwPermClr = ~0u;
DWORD dwIgnore;
BOOL fSucceeded = FALSE;
BOOL fUpdated32To64 = FALSE;
if (pder->pclr != NULL && pder->clr.Flags != ((PDETOUR_CLR_HEADER)pder->pclr)->Flags) {
// If we had to promote the 32/64-bit agnostic IL to 64-bit, we can't restore
// that.
fUpdated32To64 = TRUE;
}
if (DetourVirtualProtectSameExecute(pder->pidh, pder->cbidh,
PAGE_EXECUTE_READWRITE, &dwPermIdh)) {
if (DetourVirtualProtectSameExecute(pder->pinh, pder->cbinh,
PAGE_EXECUTE_READWRITE, &dwPermInh)) {
CopyMemory(pder->pidh, &pder->idh, pder->cbidh);
CopyMemory(pder->pinh, &pder->inh, pder->cbinh);
if (pder->pclr != NULL && !fUpdated32To64) {
if (DetourVirtualProtectSameExecute(pder->pclr, pder->cbclr,
PAGE_EXECUTE_READWRITE, &dwPermClr)) {
CopyMemory(pder->pclr, &pder->clr, pder->cbclr);
VirtualProtect(pder->pclr, pder->cbclr, dwPermClr, &dwIgnore);
fSucceeded = TRUE;
}
}
else {
fSucceeded = TRUE;
}
VirtualProtect(pder->pinh, pder->cbinh, dwPermInh, &dwIgnore);
}
VirtualProtect(pder->pidh, pder->cbidh, dwPermIdh, &dwIgnore);
}
return fSucceeded;
}
BOOL WINAPI DetourRestoreAfterWith()
{
PVOID pvData;
DWORD cbData;
pvData = DetourFindPayloadEx(DETOUR_EXE_RESTORE_GUID, &cbData);
if (pvData != NULL && cbData != 0) {
return DetourRestoreAfterWithEx(pvData, cbData);
}
SetLastError(ERROR_MOD_NOT_FOUND);
return FALSE;
}
// End of File

269
MS Detours/uimports.cpp

@ -0,0 +1,269 @@
//////////////////////////////////////////////////////////////////////////////
//
// Add DLLs to a module import table (uimports.cpp of detours.lib)
//
// Microsoft Research Detours Package, Version 4.0.1
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Note that this file is included into creatwth.cpp one or more times
// (once for each supported module format).
//
#if DETOURS_VERSION != 0x4c0c1 // 0xMAJORcMINORcPATCH
#error detours.h version mismatch
#endif
// UpdateImports32 aka UpdateImports64
static BOOL UPDATE_IMPORTS_XX(HANDLE hProcess,
HMODULE hModule,
__in_ecount(nDlls) LPCSTR *plpDlls,
DWORD nDlls)
{
BOOL fSucceeded = FALSE;
DWORD cbNew = 0;
BYTE * pbNew = NULL;
DWORD i;
SIZE_T cbRead;
DWORD n;
PBYTE pbModule = (PBYTE)hModule;
IMAGE_DOS_HEADER idh;
ZeroMemory(&idh, sizeof(idh));
if (!ReadProcessMemory(hProcess, pbModule, &idh, sizeof(idh), &cbRead)
|| cbRead < sizeof(idh)) {
DETOUR_TRACE(("ReadProcessMemory(idh@%p..%p) failed: %d\n",
pbModule, pbModule + sizeof(idh), GetLastError()));
finish:
if (pbNew != NULL) {
delete[] pbNew;
pbNew = NULL;
}
return fSucceeded;
}
IMAGE_NT_HEADERS_XX inh;
ZeroMemory(&inh, sizeof(inh));
if (!ReadProcessMemory(hProcess, pbModule + idh.e_lfanew, &inh, sizeof(inh), &cbRead)
|| cbRead < sizeof(inh)) {
DETOUR_TRACE(("ReadProcessMemory(inh@%p..%p) failed: %d\n",
pbModule + idh.e_lfanew,
pbModule + idh.e_lfanew + sizeof(inh),
GetLastError()));
goto finish;
}
if (inh.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC_XX) {
DETOUR_TRACE(("Wrong size image (%04x != %04x).\n",
inh.OptionalHeader.Magic, IMAGE_NT_OPTIONAL_HDR_MAGIC_XX));
SetLastError(ERROR_INVALID_BLOCK);
goto finish;
}
// Zero out the bound table so loader doesn't use it instead of our new table.
inh.BOUND_DIRECTORY.VirtualAddress = 0;
inh.BOUND_DIRECTORY.Size = 0;
// Find the size of the mapped file.
DWORD dwSec = idh.e_lfanew +
FIELD_OFFSET(IMAGE_NT_HEADERS_XX, OptionalHeader) +
inh.FileHeader.SizeOfOptionalHeader;
for (i = 0; i < inh.FileHeader.NumberOfSections; i++) {
IMAGE_SECTION_HEADER ish;
ZeroMemory(&ish, sizeof(ish));
if (!ReadProcessMemory(hProcess, pbModule + dwSec + sizeof(ish) * i, &ish,
sizeof(ish), &cbRead)
|| cbRead < sizeof(ish)) {
DETOUR_TRACE(("ReadProcessMemory(ish@%p..%p) failed: %d\n",
pbModule + dwSec + sizeof(ish) * i,
pbModule + dwSec + sizeof(ish) * (i + 1),
GetLastError()));
goto finish;
}
DETOUR_TRACE(("ish[%d] : va=%08x sr=%d\n", i, ish.VirtualAddress, ish.SizeOfRawData));
// If the file didn't have an IAT_DIRECTORY, we assign it...
if (inh.IAT_DIRECTORY.VirtualAddress == 0 &&
inh.IMPORT_DIRECTORY.VirtualAddress >= ish.VirtualAddress &&
inh.IMPORT_DIRECTORY.VirtualAddress < ish.VirtualAddress + ish.SizeOfRawData) {
inh.IAT_DIRECTORY.VirtualAddress = ish.VirtualAddress;
inh.IAT_DIRECTORY.Size = ish.SizeOfRawData;
}
}
DETOUR_TRACE((" Imports: %p..%p\n",
(DWORD_PTR)pbModule + inh.IMPORT_DIRECTORY.VirtualAddress,
(DWORD_PTR)pbModule + inh.IMPORT_DIRECTORY.VirtualAddress +
inh.IMPORT_DIRECTORY.Size));
DWORD nOldDlls = inh.IMPORT_DIRECTORY.Size / sizeof(IMAGE_IMPORT_DESCRIPTOR);
DWORD obRem = sizeof(IMAGE_IMPORT_DESCRIPTOR) * nDlls;
DWORD obOld = obRem + sizeof(IMAGE_IMPORT_DESCRIPTOR) * nOldDlls;
DWORD obTab = PadToDwordPtr(obOld);
DWORD obDll = obTab + sizeof(DWORD_XX) * 4 * nDlls;
DWORD obStr = obDll;
cbNew = obStr;
for (n = 0; n < nDlls; n++) {
cbNew += PadToDword((DWORD)strlen(plpDlls[n]) + 1);
}
_Analysis_assume_(cbNew >
sizeof(IMAGE_IMPORT_DESCRIPTOR) * (nDlls + nOldDlls)
+ sizeof(DWORD_XX) * 4 * nDlls);
pbNew = new BYTE [cbNew];
if (pbNew == NULL) {
DETOUR_TRACE(("new BYTE [cbNew] failed.\n"));
goto finish;
}
ZeroMemory(pbNew, cbNew);
PBYTE pbBase = pbModule;
PBYTE pbNext = pbBase
+ inh.OptionalHeader.BaseOfCode
+ inh.OptionalHeader.SizeOfCode
+ inh.OptionalHeader.SizeOfInitializedData
+ inh.OptionalHeader.SizeOfUninitializedData;
if (pbBase < pbNext) {
pbBase = pbNext;
}
DETOUR_TRACE(("pbBase = %p\n", pbBase));
PBYTE pbNewIid = FindAndAllocateNearBase(hProcess, pbBase, cbNew);
if (pbNewIid == NULL) {
DETOUR_TRACE(("FindAndAllocateNearBase failed.\n"));
goto finish;
}
PIMAGE_IMPORT_DESCRIPTOR piid = (PIMAGE_IMPORT_DESCRIPTOR)pbNew;
DWORD_XX *pt;
DWORD obBase = (DWORD)(pbNewIid - pbModule);
DWORD dwProtect = 0;
if (inh.IMPORT_DIRECTORY.VirtualAddress != 0) {
// Read the old import directory if it exists.
DETOUR_TRACE(("IMPORT_DIRECTORY perms=%x\n", dwProtect));
if (!ReadProcessMemory(hProcess,
pbModule + inh.IMPORT_DIRECTORY.VirtualAddress,
&piid[nDlls],
nOldDlls * sizeof(IMAGE_IMPORT_DESCRIPTOR), &cbRead)
|| cbRead < nOldDlls * sizeof(IMAGE_IMPORT_DESCRIPTOR)) {
DETOUR_TRACE(("ReadProcessMemory(imports) failed: %d\n", GetLastError()));
goto finish;
}
}
for (n = 0; n < nDlls; n++) {
HRESULT hrRet = StringCchCopyA((char*)pbNew + obStr, cbNew - obStr, plpDlls[n]);
if (FAILED(hrRet)) {
DETOUR_TRACE(("StringCchCopyA failed: %d\n", GetLastError()));
goto finish;
}
// After copying the string, we patch up the size "??" bits if any.
hrRet = ReplaceOptionalSizeA((char*)pbNew + obStr,
cbNew - obStr,
DETOURS_STRINGIFY(DETOURS_BITS_XX));
if (FAILED(hrRet)) {
DETOUR_TRACE(("ReplaceOptionalSizeA failed: %d\n", GetLastError()));
goto finish;
}
DWORD nOffset = obTab + (sizeof(DWORD_XX) * (4 * n));
piid[n].OriginalFirstThunk = obBase + nOffset;
pt = ((DWORD_XX*)(pbNew + nOffset));
pt[0] = IMAGE_ORDINAL_FLAG_XX + 1;
pt[1] = 0;
nOffset = obTab + (sizeof(DWORD_XX) * ((4 * n) + 2));
piid[n].FirstThunk = obBase + nOffset;
pt = ((DWORD_XX*)(pbNew + nOffset));
pt[0] = IMAGE_ORDINAL_FLAG_XX + 1;
pt[1] = 0;
piid[n].TimeDateStamp = 0;
piid[n].ForwarderChain = 0;
piid[n].Name = obBase + obStr;
obStr += PadToDword((DWORD)strlen(plpDlls[n]) + 1);
}
_Analysis_assume_(obStr <= cbNew);
#if 0
for (i = 0; i < nDlls + nOldDlls; i++) {
DETOUR_TRACE(("%8d. Look=%08x Time=%08x Fore=%08x Name=%08x Addr=%08x\n",
i,
piid[i].OriginalFirstThunk,
piid[i].TimeDateStamp,
piid[i].ForwarderChain,
piid[i].Name,
piid[i].FirstThunk));
if (piid[i].OriginalFirstThunk == 0 && piid[i].FirstThunk == 0) {
break;
}
}
#endif
if (!WriteProcessMemory(hProcess, pbNewIid, pbNew, obStr, NULL)) {
DETOUR_TRACE(("WriteProcessMemory(iid) failed: %d\n", GetLastError()));
goto finish;
}
DETOUR_TRACE(("obBaseBef = %08x..%08x\n",
inh.IMPORT_DIRECTORY.VirtualAddress,
inh.IMPORT_DIRECTORY.VirtualAddress + inh.IMPORT_DIRECTORY.Size));
DETOUR_TRACE(("obBaseAft = %08x..%08x\n", obBase, obBase + obStr));
// If the file doesn't have an IAT_DIRECTORY, we create it...
if (inh.IAT_DIRECTORY.VirtualAddress == 0) {
inh.IAT_DIRECTORY.VirtualAddress = obBase;
inh.IAT_DIRECTORY.Size = cbNew;
}
inh.IMPORT_DIRECTORY.VirtualAddress = obBase;
inh.IMPORT_DIRECTORY.Size = cbNew;
/////////////////////// Update the NT header for the new import directory.
//
if (!DetourVirtualProtectSameExecuteEx(hProcess, pbModule, inh.OptionalHeader.SizeOfHeaders,
PAGE_EXECUTE_READWRITE, &dwProtect)) {
DETOUR_TRACE(("VirtualProtectEx(inh) write failed: %d\n", GetLastError()));
goto finish;
}
inh.OptionalHeader.CheckSum = 0;
if (!WriteProcessMemory(hProcess, pbModule, &idh, sizeof(idh), NULL)) {