[英]Hooking with MS Detours crash when hook function is called C++
我寫了一個簡單的程序,它做了 3 件事:
它使用文本“NOT HOOKED”調用 MessageBoxA (MBA)
然后它加載我創建的一個 dll 文件,該文件掛鈎 MBA 函數並使用文本“HOOKED”調用 MBA。
之后,它再次使用相同的文本(“NOT HOOKED”)調用 MBA。 當然,第二個 MBA 呼叫應該被掛斷並顯示一條帶有“HOOKED”文本的消息。
最終它調用 FreeLibrary 並退出。
這是 .cpp 文件:
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
//Place the path of the dll file here, "DLLs\\HookDLL.dll" is the default path.
char dllPath[] = "HookDLL.dll";
//Display a pop-up message with the "NOT HOOKED" message and title.
MessageBoxA(NULL, "NOT HOOKED", "NOT HOOKED", MB_OK);
//Load the dll file
HMODULE hModule = LoadLibraryA((LPCSTR)dllPath);
//If hModule is null, then the dll wasn't loaded.
//An error message will be printed out to the console.
if (!hModule) {
cout << "Couldn't load the DLL file!" << endl;
return 1;
}
//This is the tricky part.
//This should display a pop-up message like before with the "NOT HOOKED" message and title,
//but the dll that was loaded should hook MessageBoxA function,
//and call a new one with a "HOOKED" message and title instead.
MessageBoxA(NULL, "NOT HOOKED", "NOT HOOKED", MB_OK);
FreeLibrary(hModule);
return 0;
}
這是 .dll 文件:
#include "pch.h"
#include "detours.h"
#include <iostream>
#include <Windows.h>
using namespace std;
typedef int(WINAPI* MBA)(HWND, LPCSTR, LPCSTR, UINT);
MBA originalMBA = NULL;
int HookedMessageBoxA(
HWND hWnd,
LPCSTR lpText,
LPCSTR lpCaption,
UINT uType
) {
return originalMBA(NULL, "HOOKED", "HOOKED", MB_OK);
}
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD reason,
LPVOID lpReserved
)
{
if (reason == DLL_PROCESS_ATTACH) {
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
originalMBA = (MBA)DetourFindFunction("user32.dll", "MessageBoxA");//Pointer the the original MBA (MessageBoxA) function.
DetourAttach(&(PVOID&)originalMBA, (PVOID)HookedMessageBoxA);
DetourTransactionCommit();
}
return TRUE;
}
當我在調試模式下構建和運行時,它在第二次 MBA 調用時崩潰(當然在 .cpp 文件中):
它像它應該的那樣顯示帶有“HOOKED”的鈎子MBA,然后它崩潰,打印下面的錯誤並且程序以代碼3退出:
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.
我檢查了這個錯誤和退出代碼,發現了很多信息豐富的帖子和解決方案,但我無法讓它們中的任何一個對我有用(也許我做錯了什么)。
注1:
如果我處於發布模式,我可以根據需要調用任意數量的 MBA 調用,只要它們在FreeLibrary 調用之前,並且所有這些調用都將被 .dll 文件很好地掛鈎,並且程序將正確退出。 但是,如果我在 FreeLibrary 調用后嘗試調用 MBA 函數 - 程序會因以下錯誤而崩潰:
Exception thrown at 0x50011000 in ProgrammingTask.exe: 0xC0000005: Access violation executing location 0x50011000.
筆記2:
我嘗試使用 DetourDetouch 分離 dll,但它沒有解決它,也許我做錯了。
另外,我嘗試閱讀有關 CreateRemoteThread 的內容,但對我來說太麻煩了。
提前致謝。
找到了!
忘記將 __stdcall 添加到 HookedMessageBox 函數。
所以,而不是
int HookedMessageBoxA
我把它改寫成這樣:
int __stdcall HookedMessageBoxA
感謝你的幫助! <3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.