I tried to hook CreateThread() function by using Detour library. But it won't work due to some errors. Finally just call the CreateThread function rather than direct call, I construct my own DLL. During DLL construct and program compilation. It doesn't return any error.But, while running its getting stop.
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;
}
by using above testdll.cpp, I am constructing 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 //* main program *//
#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;
}
Even i compiled this, cl /Zi testcall.cpp
But I run testcall.exe file. Library was properly loaded, But while executing below line, It getting stop.
HANDLE a = C_thread(NULL, 0, ThreadFu, NULL, 0, &threadID);
I am using Visual-C++ command prompt (not GUI). Please help me to solve this. If anything, correct me.
Your program has undefined behavior. When you create a thread it is not guaranteed that it runs immediately. Even if it runs immediately you have a race condition between the FreeLibrary
and the run-time call to printf
in the thread.
Your main thread must wait until the secondary thread has terminated:
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);