应用程序崩溃时与MS Detours挂钩并注入Withdll.exe

我使用MS Detours挂钩FindNextFile() 。 我已成功configuration了Detours库,并编写了一个名为“Detuors.dll”的DLL和一个名为“FNFSend.exe”的应用程序。 以下是代码:

DLL:

 #include <cstdio> #include <stdio.h> #include <windows.h> #include "detours.h" #pragma comment (lib,"detours.lib") //Prototypes extern "C" __declspec(dllexport) BOOL (WINAPI *pFNF)(HANDLE hFindFile, LPWIN32_FIND_DATA lpFindFileData) = FindNextFile; extern "C" __declspec(dllexport) BOOL WINAPI MyFNF(HANDLE hFindFile, LPWIN32_FIND_DATA lpFindFileData); //Log File FILE* pFNFLogFile; int counter = 0; INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved) { switch(Reason) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hDLL); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)pFNF, MyFNF); if(DetourTransactionCommit() == NO_ERROR) OutputDebugString("FNF() detoured successfully"); else OutputDebugString("FNF() not detoured"); break; case DLL_PROCESS_DETACH: DetourTransactionBegin(); //Detach DetourUpdateThread(GetCurrentThread()); DetourDetach(&(PVOID&)pFNF, MyFNF); DetourTransactionCommit(); break; case DLL_THREAD_ATTACH: DisableThreadLibraryCalls(hDLL); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)pFNF, MyFNF); if(DetourTransactionCommit() == NO_ERROR) OutputDebugString("FNF() detoured successfully"); else OutputDebugString("FNF() not detoured"); break; case DLL_THREAD_DETACH: break; } return TRUE; } //Open file, write contents, close it extern "C" __declspec(dllexport) int WINAPI MyFNF(HANDLE hFindFile, LPWIN32_FIND_DATA lpFindFileData) { counter ++; fopen_s(&pFNFLogFile, "C:\\FNFLog.txt", "a+"); fprintf(pFNFLogFile, "%s\n", counter); fclose(pFNFLogFile); return pFNF(hFindFile, lpFindFileData); } 

这两个代码编译成功,没有错误。 该应用程序recursion调用FindNextFile()并挂钩它并将计数器写入文件。

然后,我使用由detours库本身提供的名为“withdll.exe”的工具创build一个注入了dll的进程。 所以我使用命令将我的dll注入到应用程序中:

withdll /d:Detuors.dll“C:\ FNFSend.exe”

注入后,函数挂钩成功,即文件在目录中,但突然间应用程序崩溃。 在visual studio中debugging后,我看到“output.c”中的exception,如下所示:

 Unhandled exception at 0x6265984f (msvcr90d.dll) in FNFSend.exe: 0xC0000005: Access violation reading location 0x00000001. 

请帮助纠正这个问题。

%s不是用于打印数字的有效格式字符串 。 改为使用%d

通过指定%s ,告诉fprintf以字符串形式读取地址counter的内存。 您尝试调用fprintf的第一个值是1,这就是为什么在地址0x00000001处存在访问冲突的原因。