Passing 'this' pointer to MouseProc of SetWindowsHookEx - c++

Generally, whenever we want to wrap a Window/Thread in a C++ object, we do so by passing the this pointer via SetWindowLong/GetWindowLong or SetProp/GetProp for a Window, and as lpParameter for CreateThread/etc.
My question is specific to Hooks. What is the elegant approach to pass the 'this' pointer to SetWindowsHookEx's callback procedures, or in other words How to wrap a hook's callback procedure ?
Since SetWindowsHookEx does not accept any UserData argument, I don't see much options apart from using un-encapsulated i.e. global/static/TLS data.

You are expected to have just one instance of a given hook, so global data is not an issue.
If you are developing a library allowing multiple hook instances that can be dynamically added or removed, do not add multiple hooks at the OS level. Instead, add a library-level hook procedure that walks the list of hook instances. Since you maintain this list, you can track whatever "user data" alongside each entry you want.

The 'most elegant approach' is to use a thunk. It's a small piece of code generated at runtime that holds your this pointer. This is the approach that ATL uses even for regular windows.
See
What is a thunk?
How to generate the code for thunks
C++ WinAPI Wrapper Object using thunks (x32 and x64)

Related

How to hook CopyTextureRegion with Minhook

Im trying to hook the ID3D12GraphicsCommandList::CopyTextureRegion method with MinHook but the problem is that the method is inside ID3D12GraphicsCommandList which makes it hard to hook.
Here is my current approach which unfortunatley is 0
// not working, CopyTextureRegionHook is 0
auto CopyTextureRegionHook = GetProcAddress(GetModuleHandleA("d3d12.dll"), "CopyTextureRegion");
MH_CreateHook(reinterpret_cast<void**>(CopyTextureRegionHook), &HK_CopyTextureRegion, reinterpret_cast<void**>(&oCopyTextureRegion));
MH_EnableHook(CopyTextureRegionHook);
Hooking methods like D3D12CreateDevice, D3D12CoreRegisterLayers.. work because they are not in a interface like ID3D12GraphicsCommandList
How would I properly hook CopyTextureRegion?
Because you're dealing with an interface, you won't be able to hook the function directly in memory since it's dependent on the pointer to the interface. In which case you have to utilize a technique called VMT(Virtual Method Table) hooking. In order to achieve this, you'll need to be able to retrieve the pointer to the interface in memory, then locate the virtual method table index(offset) of the function pointer. Which then you'll have to overwrite with your own function address. Your hooked function will have to comply with the calling convention of the original.

How to call functions in a DLL that is currently load in another process? [duplicate]

I have a DLL that I inject into another process but I want to be able to call the exports on that DLL from my application. I've read elsewhere that you have to the SendMessage API but I have no idea what to do. Is there any example code on how this is done?
While it is not possible to directly call a function in another process, you can do it indirectly pretty easily with a few steps and the Windows API.
Get the addresses of LoadLibrary and GetProcAddress from your own process. kernel32.dll should be loaded at the same address in every process, so you can rely on them being present in the process into which you are injecting
Create a struct that will hold all the arguments you want to pass to your function that will call the functions in the other process (because CreateRemoteThread can only pass one argument to a function, so we'll use it to pass a pointer to the structure) which at least contains member function pointers to hold the addresses of LoadLibrary and GetProcAddress
Allocate enough memory for a struct in the remote process via VirtualAllocEx, then fill it with the correct information with WriteProcessMemory
Write a function, taking a pointer to the struct you wrote, that uses LoadLibrary/GetProcAddress to call the function you want. Remember to use the pointers to those functions in the struct you are passing the function, not the names.
Allocate enough memory in the remote process to hold the function with VirtualAllocEx, making sure to pass VAX the PAGE_EXECUTE_READWRITE flag so that it can hold executable code
Read and write the function's code from your process to the other process via Read/WriteProcessMemory
Call the function in the remote process (which is at the address returned by the VirtualAllocEx) by using CreateRemoteThread.
Make sure that all the data you pass to the function is either stored inside the struct and/or resides in the remote process's address space (get it there with VirtualAllocEx/WriteProcessMemory.
It may look a little involved, but it's not really that complicated. If you need some help with it, feel free to ask in a comment.
You can't directly call functions in another process, in general. There are, however, some workarounds you can use.
First, if you know the address of the export (which isn't the case a lot of the time), and the function you call uses the __stdcall calling convention, takes a pointer-sized integer as an argument, and returns a DWORD, you can use CreateRemoteThread to execute it in a thread in the remote process. This is often used to run LoadLibrary to inject a DLL into a target process, since LoadLibrary is loaded in the same address on all processes on a given computer.
Otherwise, the DLL you inject will need to do some sort of RPC with the process that called it. For example, you could have your injected DLL spawn a thread in its DLL_PROCESS_ATTACH handler, which in turn connects to a named pipe, or connects over COM or something to the master process.
SendMessage would need a window handle (hidden or visible), and a message-pump associated with it, that can handle the custom message. As with UAC/Windows-7, the integrity levels of applications may prevent other applications to send/post messages from other processes having low integrity.
It is better to have another thread that waits for these custom messages. For this, you may use pipes (named or unnamed), sockets, mail-slots, shared memory (along with mutex/event for triggering). The another processes would send the message using same protocol.
But before implementing this custom messaging/protocol/IPC mechanism, I suggest you to first determine the exact need.

What is the typical convention for organization with Win32?

I've been working a lot with Win32 lately, but I'm pretty new to it, and need some advice concerning organization. In C++, although it works syntactically to declare global variables, I was always under the impression that this was sloppy, because the variable can then be modified anywhere, so it becomes much more difficult to track changes to it.
In my Win32 project, I've got several variables which need to be modified in multiple places. For instance, one such variable was in the WndProc function and also in a dialog procedure function. Due to the way it was used, I was able to simply use the actual values in WndProc, and then call the dialog box using DialogBoxParam, and pass the value to the dialog box through the lParam value.
However, there are other values, such as certain bitmaps that I use for drawing or variables that are used in multiple different window message calls, where the value(s) need to be retained throughout multiple instances of the WndProc function or multiple functions. I can control the parameters of the functions I created, but what if I need to pass a variable into the WndProc function so that I can use it regardless of multiple different window messages? What if I need to pass in multiple values?
So far I've just been making everything global, and it works, but it feels sloppy to me...but I know that some variables are generally global as a matter of convention - like the main window and instance variables.
What do you all think?
It might help if you had a specific example in code. But I think you're talking about lifetime--you have a resource (say a bitmap) and you need to reference it many times in response to different Windows messages. You could make it global, yes, but I agree that's sloppy.
So who created the window? Likely your "App" class or something along those lines. Since that class's lifetime is logically longer than the window's, it could hold the resources required by the window.
Or a better approach is to create a "Window" class. Your App instantiates a Window object. The Window object creates the Win32 window and holds the HWND (you've now abstracted that away from the App so it doesn't need to know those gory details), and the Window instance can hold the bitmap resources.
Instead of using global variables you can store window-specific data in a C++ object associated with the relevant window.
To associate a C++ object with a window, use any of a number of existing C++ class frameworks (such as e.g. Microsoft’ WTL or Torjo's Win32GUI), or do it yourself by using SetWindowSubclass API function.
For the Do It Yourself™ solution, I presented a complete C++ example in another SO answer.
That said, for a tiny little program global variables + a dialog is the easiest and presents no problems. So in general, use the Right Tool™ for the job. For larger jobs, use more heavy tooling…

Calling functions in a DLL loaded by another process

I have a DLL that I inject into another process but I want to be able to call the exports on that DLL from my application. I've read elsewhere that you have to the SendMessage API but I have no idea what to do. Is there any example code on how this is done?
While it is not possible to directly call a function in another process, you can do it indirectly pretty easily with a few steps and the Windows API.
Get the addresses of LoadLibrary and GetProcAddress from your own process. kernel32.dll should be loaded at the same address in every process, so you can rely on them being present in the process into which you are injecting
Create a struct that will hold all the arguments you want to pass to your function that will call the functions in the other process (because CreateRemoteThread can only pass one argument to a function, so we'll use it to pass a pointer to the structure) which at least contains member function pointers to hold the addresses of LoadLibrary and GetProcAddress
Allocate enough memory for a struct in the remote process via VirtualAllocEx, then fill it with the correct information with WriteProcessMemory
Write a function, taking a pointer to the struct you wrote, that uses LoadLibrary/GetProcAddress to call the function you want. Remember to use the pointers to those functions in the struct you are passing the function, not the names.
Allocate enough memory in the remote process to hold the function with VirtualAllocEx, making sure to pass VAX the PAGE_EXECUTE_READWRITE flag so that it can hold executable code
Read and write the function's code from your process to the other process via Read/WriteProcessMemory
Call the function in the remote process (which is at the address returned by the VirtualAllocEx) by using CreateRemoteThread.
Make sure that all the data you pass to the function is either stored inside the struct and/or resides in the remote process's address space (get it there with VirtualAllocEx/WriteProcessMemory.
It may look a little involved, but it's not really that complicated. If you need some help with it, feel free to ask in a comment.
You can't directly call functions in another process, in general. There are, however, some workarounds you can use.
First, if you know the address of the export (which isn't the case a lot of the time), and the function you call uses the __stdcall calling convention, takes a pointer-sized integer as an argument, and returns a DWORD, you can use CreateRemoteThread to execute it in a thread in the remote process. This is often used to run LoadLibrary to inject a DLL into a target process, since LoadLibrary is loaded in the same address on all processes on a given computer.
Otherwise, the DLL you inject will need to do some sort of RPC with the process that called it. For example, you could have your injected DLL spawn a thread in its DLL_PROCESS_ATTACH handler, which in turn connects to a named pipe, or connects over COM or something to the master process.
SendMessage would need a window handle (hidden or visible), and a message-pump associated with it, that can handle the custom message. As with UAC/Windows-7, the integrity levels of applications may prevent other applications to send/post messages from other processes having low integrity.
It is better to have another thread that waits for these custom messages. For this, you may use pipes (named or unnamed), sockets, mail-slots, shared memory (along with mutex/event for triggering). The another processes would send the message using same protocol.
But before implementing this custom messaging/protocol/IPC mechanism, I suggest you to first determine the exact need.

How to use IGlobalInterfaceTable to pass an interface pointer?

Without:
MFC
ATL
Question:
What are the steps involved, to use IGlobalInterfaceTable, when passing a particular interface pointer to several threads using CreateThread?
I think this page covers it rather well.
Call RegisterInterfaceInGlobal to put your COM interface in the GIT, pass its cookie to your other threads, which can then call GetInterfaceFromGlobal using that cookie to get the original interface.
Note that each thread has to call CoCreateInstance(CLSID_StdGlobalInterfaceTable... but don't worry, they all get an interface pointer to the same instance of the GIT.