我尝试使用Detour库挂钩CreateThread()功能。但由于一些错误,它不会起作用。最后只调用CreateThread函数而不是直接调用,我构造自己的DLL。在DLL构造和程序编译期间。它不会返回任何错误。但是,在运行它的停止时。
testdll.cpp
#include <windows.h>
BOOL _stdcall DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
return TRUE;
}
extern "C" _declspec(dllexport) bool _stdcall C_thread(LPSECURITY_ATTRIBUTES lpThreadAttributes,SIZE_T dwStackSize,LPTHREAD_START_ROUTINE lpStartAddress,LPVOID lpParameter,DWORD dwCreationFlags,LPDWORD lpThreadId)
{
HANDLE hThread;
DWORD threadID;
hThread = CreateThread(lpThreadAttributes,dwStackSize,lpStartAddress,lpParameter,dwCreationFlags,lpThreadId);
return hThread;
}
通过使用上面的testdll.cpp,我正在构建DLL。
cl / nologo / W3 / Ox / Zi / MD / LD test.cpp
link / DEBUG / SUBSYSTEM:WINDOWS / ENTRY:DllMain /OUT:testdll_temp.dll /DEF:test.def testdll_temp.obj kernel32.lib
testcall.cpp // *主程序* //
#include<stdio.h>
#include<windows.h>
DWORD WINAPI ThreadFun(LPVOID param)
{
printf("hi");
return 0;
}
int main()
{
HANDLE h;
DWORD threadID;
typedef bool (_stdcall *CALL_A)(LPSECURITY_ATTRIBUTES lpThreadAttributes,SIZE_T dwStackSize,LPTHREAD_START_ROUTINE lpStartAddress,LPVOID lpParameter,DWORD dwCreationFlags,LPDWORD lpThreadId);
printf("Creating Handle");
HINSTANCE hinstDLL;
BOOL fFreeDLL;
printf("\nLoading library test.dll .... ");
hinstDLL = LoadLibrary("testdll.dll");
if (hinstDLL != NULL)
{
printf("\nLibrary loaded\n");
CALL_A C_thread;
C_thread = (CALL_A)GetProcAddress(hinstDLL,"C_thread");
if (C_thread != NULL)
{
printf("lets see, it calling");
HANDLE a = C_thread(NULL, 0, ThreadFu, NULL, 0, &threadID);
printf("working");
}
else
{
printf("Address not found ");
}
fFreeDLL = FreeLibrary(hinstDLL);
}
else
printf("Library not found");
return 0;
}
即使我编译了这个, cl / Zi testcall.cpp
但是我运行了testcall.exe文件。 库已正确加载,但在执行下线时,它停止了。
HANDLE a = C_thread(NULL,0,ThreadFu,NULL,0,&amp; threadID);
我正在使用Visual-C ++命令提示符(不是GUI)。 请帮我解决这个问题。 如果有的话,请指正。
答案 0 :(得分:0)
您的程序有未定义的行为。创建线程时,无法保证它立即运行。即使它立即运行,您在线程中FreeLibrary
和printf
的运行时调用之间也存在竞争条件。
您的主线程必须等到辅助线程终止:
CALL_A C_thread;
C_thread = (CALL_A)GetProcAddress(hinstDLL,"C_thread");
if (C_thread != NULL)
{
printf("lets see, it calling");
HANDLE a = C_thread(NULL, 0, ThreadFu, NULL, 0, &threadID);
printf("working");
if (WaitForSingleObject(a, some_time_or_infinite) != WAIT_OBJECT_0)
{
// this is dirty since the thread has probable no chance to release resources.
TerminateThread(hThread);
}
}
else
{
printf("Address not found ");
}
fFreeDLL = FreeLibrary(hinstDLL);