C++ - How can I find out where the current thread was created? - c++

I'm working on a huge C++ MFC GUI app using Visual Studio 2010 that's got tons of code the I'm unfamiliar with.
There's a thread that's being spawned way too many times, and I'm not sure where it's being spawned as there's lots of code that spawns this thread. Also, there are many creating points in the code for the same thread. I need to find which creating point started the current thread function.
How can I find where the thread was created in Visual Studio?
Note: I couldn't see where the thread was created in call stack window.

If its possible then make a macro definition for a function which is used for creating threads, then once it is created store thread id/handle in some map which will contain pairs of type: [ThreadID] -> [__FILE__+__LINE__] . This will allow you to check inside your thread where it was created.
a more advanced aproach is to use api hooks, but thats a lot of coding. So you can make use of api hooking with http://codefromthe70s.org/mhook22.aspx and hook CreateThread. When your custom CreateThread function gets executed then you can execute original CreateThread and using its returned handle update a map as in first paragraph. The problem is that you will have to store callstack data to find where this call was executed. You could use http://www.codeproject.com/Articles/11132/Walking-the-callstack for that.
Even with first solution, you might find that __FILE__+__LINE__ does not give you enough information, and a callstack is a must.
I made a small test app with mhook - below is some code that might be useful:
typedef HANDLE(WINAPI *CreateThread_t)(LPSECURITY_ATTRIBUTES, SIZE_T, LPTHREAD_START_ROUTINE, LPVOID, DWORD, LPDWORD);
CreateThread_t fCreateThread = (CreateThread_t)GetProcAddress(LoadLibrary(L"Kernel32.dll"), "CreateThread");
HANDLE
WINAPI
MyCreateThread(
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_opt_ __drv_aliasesMem LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_opt_ LPDWORD lpThreadId
)
{
HANDLE hret = fCreateThread(lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId);
// Here you can add thread entry for hret with current callstack.
// You will probably want to create this thread suspended, to make
// sure it wont get executed before map gets updated. Resume it after
// map update.
//if (lpStartAddress == MyThreadProcToMonitor) {
// log things
//}
return hret;
}
int main() {
// This will hook create thread
Mhook_SetHook((PVOID*)&fCreateThread, MyCreateThread);
// App logic here
Mhook_Unhook((PVOID*)&fCreateThread);
}

If you are allowed to change the code a bit, you could replace the thread-launching calls by a macro that would also log the __FILE__, __LINE__ and thread id, so that you can track the launches.

Related

Unhooking a hook set with SetWindowsHookEx more than once crashes the hooked process

I am trying to hook the keyboard and mouse events of a target application.
I followed the SO question How to hook external process with SetWindowsHookEx and WH_KEYBOARD, and the hooks are installed and uninstalled correctly the first time. However, after I uninstall the hook once and then install it again, trying to uninstall the hook the second time crashes the target application. The purpose of the hook is to monitor application idle time, so that I can do some tasks when the application is idle.
I apologize for the length of the question, but I tried to put in all the details that might help
Thanks
I need to be able to install and uninstall the hooks based on menu commands from a system tray icon. I have a console application [HookApp] which calls the install and uninstall methods in a DLL [HookDLL]. The console application also creates a window to handle menu events. I use the thread of the window to actually install and uninstall the hooks, because the same thread that installed the hook must uninstall it. The Console and the window both must be invisible. Only the system tray icon and its associated menu must be visible.
I start the hooking application from the command line with the parameters
i. ProcessId of the target process
ii. Process Name
iii. Idle time [in seconds] -Idle time before starting the action in the DLL
I am wondering if the timer I start in the HookProcs is responsible for the crash.
Event Viewer Logs
Faulting application name: notepad.exe, version: 10.0.17134.1, time stamp: 0x9d4727c2
Faulting module name: HookDLL_x64.dll_unloaded, version: 0.0.0.0, time stamp: 0x5c31aabd
Exception code: 0xc0000005
Fault offset: 0x00000000000ba505
Faulting process id: 0x2bac
The exception code seems to suggest a memory access violation.
I have tried the following
I.
a. Call the SendMessageTimeout API with HWND_BROADCAST from HookApp
b. Call the SendMessageTimeout API with HWND_BROADCAST from HookDLL
based on Unloading DLL from all processes after unhooking global CBT hook
II.
a. call FreeLibraryAndExitThread API in the DLLMain method on DLL_PROCESS_DETACH AND DLL_THREAD_DETACH -both together and singly
based on http://www.rohitab.com/discuss/topic/42505-unloading-dll-crashes-exe/
III. Made the HookApp console and the window visible and hidden to see if it makes any difference
IV. Was unable to try the following because of 64 bit architecture
https://www.unknowncheats.me/forum/programming-for-beginners/73377-unload-injected-dll-thread-process.html
Other Links I referred to
a. Several programs crash when unhooking with UnhookWindowsHookEx()
b. How to correctly use SetWindowsHookEx & CallNextHookEx
c. Unloading an Injected DLL
d. FreeLibraryAndExitThread crashes program when unloading injected DLL
//Code in the DLL
extern "C" __declspec(dllexport) void install(unsigned long threadID,int _nIdleTime) {
nIdleTime = _nIdleTime;
Log(L"install proc called from app: _nIdleTime", _nIdleTime);
hhKeyboard = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, hinst, threadID);
hhMouse = SetWindowsHookEx(WH_MOUSE, MouseProc, hinst, threadID);
logger->Log("Install");
logger->Log("Keyboard", (LONG)hhKeyboard);
logger->Log("Mouse", (LONG)hhMouse);
}
//Uninstall the dll from the Target Process
DWORD WINAPI UnInjectDLLFromTarget() {
uninstall();
//DWORD_PTR dwResult = 0;
//SendMessageTimeout(HWND_BROADCAST, WM_NULL, 0, 0, SMTO_ABORTIFHUNG | SMTO_NOTIMEOUTIFNOTHUNG, 1000, &dwResult);
return TRUE;
}
LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam) {
if (code < 0) {
return CallNextHookEx(0, code, wParam, lParam);
}
StartTimer();
Beep(1000, 20);
return CallNextHookEx(hhKeyboard, code, wParam, lParam);
}
LRESULT CALLBACK MouseProc(int code, WPARAM wParam, LPARAM lParam) {
if (code < 0) {
return CallNextHookEx(0, code, wParam, lParam);
}
// StartTimer();
//Beep(1000, 20);
return CallNextHookEx(hhMouse, code, wParam, lParam);
}
BOOL WINAPI DllMain(__in HINSTANCE hinstDLL, __in DWORD fdwReason, __in LPVOID lpvReserved) {
if (fdwReason == DLL_PROCESS_DETACH || fdwReason==DLL_THREAD_DETACH) {
FreeLibraryAndExitThread(hinstDLL, 0);
return 0;
}
}
//Code in the Application [HookApp]
Similar to [But not exactly the same - It is a bit more involved because of the need to create the message pump and the menu event handling window]
HINSTANCE hinst = LoadLibrary(_T("MyDLL.dll"));
if (hinst) {
typedef void (*Install)(unsigned long);
typedef void (*Uninstall)();
Install install = (Install) GetProcAddress(hinst, "install");
Uninstall uninstall = (Uninstall) GetProcAddress(hinst, "uninstall");
install(threadID);
Sleep(20000);
uninstall();
}
SendMessageTimeout in the DLL [HookDLL] method Uninstall immediately crashes the application
SendMessageTimeout in the application [HookApp] doesnt appear to do anything useful.
FreeLibraryAndExitThread does not appear to do anything useful.
However, with 2 and 3, I think I am able to install the hook for the second time. Without them, the first unhook crashes the application.
I was unable to try the suggestion using assembly language inline because of 64 bit architecture.
Please help.
for uninstall hook and unload your dll all what you need - call UnhookWindowsHookEx for every hook handle obtained by a previous call to SetWindowsHookEx. all. you not need call FreeLibrary[AndExitThread] yourself. system auto call FreeLibrary on your hook dll after UnhookWindowsHookEx callend, when first (any) message will be received by target application thread and this thread call GetMessage or PeekMessage. so for just unload your dll after several UnhookWindowsHookEx - you need post message to thread, for which you install hook. if you do this for concrete single thread (dwThreadId) - you need PostThreadMessageW(dwThreadId, WM_NULL, 0, 0); - system yourself call FreeLibrary ( called from user32!__ClientFreeLibrary which called from ntdll!KiUserCallbackDispatcher - called inside GetMessage or PeekMessage when thread (or it window) got any message)
call FreeLibrary from dll for yourself - always error - if assume dll will be unloaded by this call - to where we return after call ? to unloaded place. call FreeLibraryAndExitThread exist sense in some cases, but only from thread, which you create yourself. call FreeLibraryAndExitThread from dll entry point at all fatal error - you kill not self thread, thread which you kill - hold critical section (loader lock) inside which called dll entry point - so fatal error. and at all absolute senseless call here - if you say receive DLL_PROCESS_DETACH this mean that dll already in unload process. DLL_THREAD_DETACH - arbitrary point, why and how many time you try call unload for self here ? exit thread while holding process wide critical section without release it. fatal error.
also because the same thread that installed the hook must uninstall it. - this is not true. another thread from also can do this.
also StartTimer(); in your code look like suspicious here. what this code is do ? are and where you cancel timer ?

GetModuleHandle(NULL) vs hInstance

When programming using the Windows API, I've always made the HINSTANCE from WinMain a global variable immediately. If I want to make an OK button, I'd do it like so (given global HINSTANCE g_hInstance):
return CreateWindow("BUTTON", "OK", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON, 10, 10, 100, 30, exampleParentWindow, EXAMPLECHILDID, g_hInstance, NULL);
but lately I've been seeing the instance handle determined without having to be passed as a parameter or clogging up the global namespace, using a call to GetModuleHandle(NULL)*. So, the example above would look like this:
return CreateWindow("BUTTON", "OK", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON, 10, 10, 100, 30, exampleParentWindow, EXAMPLECHILDID, GetModuleHandle(NULL), NULL);
*If your compiler supports it, you can write GetModuleHandle(nullptr) and the statement will have the same result.
What's the advantage (if any) of calling GetModuleHandle(NULL) over explicitly specifying the instance handle?
Fine Print: I know this has an answer, but it has not been phrased as its own question on StackOverflow.
In an EXE, it does not make any difference. hInstance from WinMain() and GetModuleHandle(NULL) both refer to the same HINSTANCE (the module of the .exe file). But it does make a difference if you are creating windows inside of a DLL instead, since you have to use the DLL's hInstance but GetModuleHandle(NULL) will still return the HINSTANCE of the EXE that loaded the DLL.
HMODULE WINAPI GetModuleHandle( _In_opt_ LPCTSTR lpModuleName );
Give the module handle of the module name passed.If you are passing NULL, the you get the module handle of the EXE which is currently running.
If you specifically name the module name, you get the module handle of that dll which is mapped to the process address space.
The use is that when you are trying to call a function exported by the dll, or trying to use a dialog template in side that dll.At that time if you use the HMODULE returned form GetMoudleHandle(NULL) your code wont work.
Just to add my two-cents to these answers. In case you need to get the module handle from within a DLL (and don't want to, or can't save it in a global variable from the DllMain call) you can use this function to get it instead:
HMODULE getThisModuleHandle()
{
//Returns module handle where this function is running in: EXE or DLL
HMODULE hModule = NULL;
::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCTSTR)getThisModuleHandle, &hModule);
return hModule;
}
One potential gain you get from using GetModuleHandle(NULL) over directly using the WinMain HINSTANCE comes more from architecture. If you want to provide a platform-independent system that runs on linux/windows/whatever you can have a layer that does platform-dependent translations. If that's the case you don't want platform dependent objects such as HINSTANCE showing up in the main application code. So, to circumvent that platform-dependence I put GetModuleHandle(NULL) in the constructor of the platform-dependent class which has the same effect that direct use of the WinMain HINSTANCE does but that abstracts that specific functionality out of the main codebase itself.

WINAPI's message loops drives me crazy

I've been trying to implement simple low level keyhook using JNI and all went well til I figured I can't call the methods while the DLL is on infinite loop(message loop). so I decided to create new thread but somehow, after I made it so the message loop runs on its own loop the lowlevel keyhook stops responding meaning that it doesn't call the keyproc anymore, and I got no idea why is this? is there any other work around for this? I am required to be able to call the DLL's methods while the keyboard hook is still functioning.
My current code is as simple as
register keyboard hook:
keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboardProc, hInstance, 0);
start thread
HANDLE threadHandle = CreateThread(NULL, 0, ThreadProc, NULL, 0, &threadId);
my keyboard proc and threadproc are the following:
DWORD WINAPI ThreadProc(LPVOID lpVoid) {
MSG msg;
while(GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK keyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
KBDLLHOOKSTRUCT keyEvent = *((KBDLLHOOKSTRUCT*)lParam);
jint vkCode = keyEvent.vkCode;
jint flags = keyEvent.flags;
jint action = wParam;
(*globalEnv).CallVoidMethod(globalObj, keyboardMethodId, vkCode, flags, action);
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
where do I go wrong?
I am sure it not the java as even if I add simple logging for the keyproc its never called. But if I stop using thread and run the message loop on main thread it works fine but DLL wont respond for method calls after it.
You need to pump the message loop on the same thread that called SetWindowsHookEx(). So just move the call to your ThreadProc(). And of course, beware that your CallVoidMethod() callback runs on that same thread as well so be careful what you do in that function. Any shared state you access needs to be protected with a lock.
You are attempting to install desktop-wide hook, which spans across all processes of the desktop. That is, your DLL is mapped into several processes with process-specific sets of global variables. You don't have valid globalEnv in other processes and you are likely to get access violations or similar errors (global vars can be created with shared data segment, see this article for details).
To install thread specific hook you will need a different type of hook (WH_KEYBOARD_LL is global only!) and non-zero last argument in SetWindowsHookEx.

Winapi: createWindow in plugin

I'm developing a plugin (a dll that is loaded by other app). There's a special function that should return HWND so that app can show a dialog. The problem is that I don't know from where I can get the hInstance (it's not passed as a parameter to the function).
Looks like I'm not understanding something, I'm new to all this stuff, so forgive if the question is silly.
UPD: tried to get hInstance with getModuleHandle:
void* createLoginDialog() {
HINSTANCE hIns = (HINSTANCE) GetModuleHandle(L"comapping");
HWND hWnd = CreateWindow(L"Popup",
L"Enter login",
WS_POPUP,
20,
20,
20,
20,
NULL,
NULL,
hIns,
NULL);
return hWnd;
}
I'm still getting Access Violation.
Several ways to get it:
The first argument passed to your DllMain() entrypoint, cast to HINSTANCE
GetModuleHandle() using your DLL name, cast to HINSTANCE
VirtualQuery(), passing the address of your function. Cast the returned MEMORY_BASIC_INFORMATION.BaseAddress to HINSTANCE. Works on both 32-bit and 64-bit versions of Windows.
According to the documentation of CreateWindow, the hInstance argument is optional. This means that it's valid to pass NULL here. However, as Simon Richter points out in the comments to this answer, the argument may only be NULL the window class is registered globally.
If you're writing a DLL, you may just as well define a DllMain entry point function yourself. This function is called by Windows, passing the handle of your function as the first arugment. You can memorize this handle somewhere to reuse it when creating your window.

When does EnumDisplayMonitor return?

I am using EnumDisplayMonitor to retrieve information about the displays connected to a system. Calling EnumDisplayMonitor requires that a callback function is provided which is then invoked to receive details of each enumerated monitor. My question is when does EnumDisplayMonitor return? Is it immediately or does it block until the callback has been called for each enumerated monitor? I want to process a data structure that will have been altered by the callbacks and I need to know if it's safe to do it immediately after the EnumDisplayMonitor call. If the call doesn't block is there a way to check that the callback has finished being called? This might be a general question about callbacks....
e.g.
BOOL CALLBACK MonitorEnumProc(
__in HMONITOR hMonitor,
__in HDC hdcMonitor,
__in LPRECT lprcMonitor,
__in LPARAM dwData)
{
// Alter something here - e.g. Add lprcMonitor to a list.
}
int main()
{
EnumDisplayMonitor(NULL, NULL, MonitorEnumProc, 0);
// Can I rely on EnumDisplayMonitor to have finished making calls to
// MonitorEnumProc at this point?
}
I've checked the MSDN entry and it does not help in this respect and I would confirm by experiment but I don't have enough monitors to test it reliably.
It returns when it has finished calling your callback functions. So the sequence of events looks like this:
Enter: EnumDisplayMonitor
Callback: MonitorEnumProc
Callback: MonitorEnumProc
Callback: MonitorEnumProc
...
Leave: EnumDisplayMonitor
All the Windows API routines of this ilk behave this way, e.g. EnumProcess, EnumWindows etc.
Code has to run in the context of a thread and if such an enumeration routine were to return immediately and call the callbacks asynchronously, it would have to spawn a thread to do so. You can apply the principle of least surprise here!