notify an object when a thread starts - c++

i have an object A which should be notified (A::Notify() method) when some thread starts or dies.
Lets say this thread dynamically loads some DLL file of mine (i can write it).
I believe i should write the dllMain function of this DLL, however i'm not sure how to get a reference to the A object from this function so i can run it's Notify() method.
any ideas?

A DLL is loaded once in every process. Once loaded, its DllMain is automatically called whenever a thread is created in the process. Assuming A is a global variable, you can do the following:
After you first load the DLL, call an exported function that will set a global pointer to A in the DLL
Whenever DllMain is called with the reason being thread attached, call A via the pointer you have in the DLL.
Another option would be to start a message loop in your exe, and pass it's thread ID to the DLL. Then, whenever a thread attaches to the DLL send the message loop a message with the details of the created thread. This is a slightly more complicated solution, but it will save you the need of making the DLL familiar with the A class.

Is it okay to make A::Notify() as static method?
Otherwise, Singleton method might serve the purpose.

So if I understand you write, in your main program you have an instance of class A. When your main program loads certain dlls you want it to call A::Notify for that instance?
As far as I'm aware there is no way to pass an additional argument to LoadLibrary.
If A::Notify can be either static, or A is a singleton, export a "NotifyA" method from the exe, then have the dll call LoadLibrary("yourexe") and you GetProcAddress to get the address of NotifyA which you can then call. (Yes exe files can export methods like dlls!)
A second option is to write your own LoadLibrary, that call a second method after dll main, eg
HMODULE MyLoadLibrary(string dll, A *a)
{
HMODULE module = LoadLibrary(dll.c_str())
void (call*)(A*) = void (*)(A*)GetProcAddress(module, "Init");
call(a);
return module;
}
The dlls Init method can then store the A instance for later.

Related

C++ - Remove Injected DLL [duplicate]

Is it possible for a function that is inside a DLL to unload the DLL? I need to do this so I can make sure the DLL is not in use, then write to the DLL's file.
As I understand it, it CAN be done and is MEANT to be done sometimes (for example in case of dll injection by CreateRemoteThread and other methods). So,
FreeLibraryAndExitThread(hModule, 0)
will do precisely that.
On the other hand, calling
FreeLibrary(hModule)
will not do here - from MSDN: "If they were to call FreeLibrary and ExitThread separately, a race condition would exist. The library could be unloaded before ExitThread is called." As a remark, ExitThread does some bookkeeping besides just returning from the thread function.
All this assumes that Your Dll obtained the hModule itself by calling LoadLibrary from inside the loaded Dll, or rather, by calling from inside the loaded Dll the following function:
GetModuleHandleEx
(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)DllMain,
&hModule
)
This increments the reference count of the Dll so You know that if You free the library later using that handle and if the library is really unloaded then You had the last reference to it.
If You instead skip incrementing the Dll's reference count and obtain the hModule just from the argument to DllMain during DLL_PROCESS_ATTACH then You should not call FreeLibraryAndExitThread since the code that loaded the Dll is still using it and this module handle really isn't Yours to manage.
Use this when the dll has done it job:
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)FreeLibrary, &__ImageBase, 0, NULL);
// terminate if dll run in a separate thread ExitThread(0);
// or just return out the dll
And the __ImageBase is your dll's PE header structure:
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
If your asking if you can safely unload/unmap a DLL loaded in a process from code in the DLL itself, the answer is no - there isn't really a safe way to do this.
Think about it this way: Unloading a DLL is done by decrementing it's reference count using FreeLibrary(). The problem of course is that once the reference count of the DLL hits zero, the module is unmapped. Which means that the code in the DLL that called FreeLibrary() is gone.
Even if you could do this, you'd still need to ensure that there are no other threads executing any exported functions from the DLL.
I don't think it will work. Calling FreeLibrary with a handle from the outside (LoadLibrary would have been called from an area outside the DLL) as the code runs in a memory location that will not be valid anymore.
Even if this is possible, it smells like a bad design. Maybe you want to make some updater or alike. Explain a bit more what is the result you expect. Unloading a DLL from within itself is not the way to go.

When you instantiate a subclass from a DLL, is the vtable correct?

When you have a base class in your main executable and subclasses (say, plugins) defined in DLLs, what happens when you want to get a plugin?
I am looking for an article/answer that'd clarify what happens when you
load a DLL
call a DLL's function that returns a plugin* (it has virtual functions)
use that plugin in your main executable's code
delete, unload
I am thinking about the vtable and other C++ issues. For instance, if you unload the DLL stil having some plugins running... The "code" will be gone?
Since you are talking about plugins, you must be doing something like LoadLibrary. Assuming Windows:
Load a library. You would normally call LoadLibrary followed by GetProcAddress. The DLL is loaded into the process address space and you have the pointer to the function exposed.
Call a DLL's function that returns a plugin* (it has virtual functions). You would cast a the return value from GetProcAddress to the function pointer type, and call it. Everything should work as normal.
Use that plugin in your main executable's code. There is nothing special.
Delete the plugin. I assume you use a function in the DLL to do so, and it should be fine. Directly calling delete can be dangerous, as the DLL may have a separate memory manager (depending on what runtime you use).
Unload the DLL. You call FreeLibrary, and the code is gone. The pointers you previously get from GetProcAddress become invalid.
I am not aware specific vtable issues. If you unload the DLL while the code is still running, I would assume the program will crash at this point, as the code address space becomes invalid.

Calling a function from DLL, in an injected process

Is there a way to call a function, that resides in a dll, (the dll is injected into a process) from that process?
By this I mean if i have myDLL.dll that exports a function, lets say void f(){do sth} and a process myProcess, "myDLL.dll" is injected using CreateRemoteThread(), can I call f() from myProcess so actually myProcess is the "user" that initiated the call to this function ?
I need to do this because I want the function f() not to be dependent by a certain program that can be killed in Task Manager, since employes can find the process and kill it. My manager asked me to do this because he thinks employees are doing other things than work.
Just use the usual, LoadLibrary() and GetProcAddress()
What you want to do probably won't work, and isn't the right approach anyway. The correct solution for preventing users from killing a process can be found here.

What is HMODULE?

I have a small problem. I have loaded DLL into the process (it's not mine) and I have to use function inside it. I have got offset to this function so only what I have to do is to get DLLs address and add to it the offset to get to the function. GetModuleHandle() returns HMODULE variable but actually I don't know what HMODULE is. Is it address of loaded DLL or some kind of other mark?
And if it's not address of place where DLL is loaded, how can I get this address? I hope I make myself clear.
The method that you propose will work fine.
It seems that you have injected a dll into a target process and wish to obtain the address of a function in that dll in the target process from the process that injected the dll.
I assume that you also have the dll loaded in the process that injected the dll into the target process and that you want to create a remote thread in the target process and get it to execute the target function in the target process.
Since the dll that you have injected may not be loaded at the same address in the target process as it is in the injecting process you cannot simply use the address that you would obtain from calling GetProcAddress on the function in the injecting process.
An HMODULE is just the DLL's base address (see this answer for details). So you can take the HMODULE of the dll in your injecting process and subtract it from the address returned by GetProcAddress on your function. You can then add the HMODULE of the injected dll in the target process to this offset to get the address of the target function in the injected dll in the target process. Assuming this function has the correct signature, pass it as the thread function to your call to create the remote thread and you are now running the target function in the target process.
I explain this in more detail in this answer.
Call GetProcAddress. The offset cancels out, as you'd have to both add it (to get to the function) and subtract it (to get the base address), so you might as well not bother.
It is similar to the void* returned by the POSIX dlopen() function (it might even be a typedef - but I don't know that for sure). You pass it to GetProcAddress as an argument. When you are done you also pass it to FreeLibrary to unload the DLL.

How to solve the DLL function call problem

i have couple of query's with respect to DLL,
1)If i load the DLL in run time, i guess DLL will be in separate thread right?
2)If i call a function present in DLL, and that function takes much time to return the value then how can i make my application thread to wait till the DLL's function return value.
How can i solve the second problem
Your assumption is incorrect.
If you load a DLL, and then call one of its functions, the call is made synchronously, just like any other function call.
There is absolutely no reason why the DLL should be loaded in another thread. You may do it, of course, but this is not the default.
1) No. The dll is just code. The code in the dll is called in the context of whatever threads you create. *
2) As a result, your application will wait for the dll's function to complete.
A Dll can create worker threads as a result of your application calling the dll. However, you cannot call directly into a thread. Any call your code makes will always happen synchronously on the current thread.
Are you using qt threads? Otherwise I cannot understand why you would use the "qt" tag.
As for your problems it seems to me that you have to create another thread which will call the function contained in the DLL.
When this thread exits than you can assume you have the function's result.
You can in switch implement DLL_THREAD_ATTACH too.
You must call this function from thread you want to slow down, or get Thread Suspend before function call, and Thread Resume after.