I'm using C++ to inject a DLL into a running process. A great source code base for this is here (it's the one I'm using). For a short example, you may use the code from this question. My problem is that after injection, the DLL is immediately unloaded again. I can observe loaded DLLs in x64Dbg for instance when the debugger is attached and it said the following:
Thread 7CC8 created, Entry: <kernel32.LoadLibraryA>
DLL Loaded: 0000000001110000 D:\MyDLL.dll
DLL Unloaded: 0000000001110000 mydll.dll
Thread 7CC8 exit
I debugged the injection and it always happened on CreateRemoteThread() or a similar method of setting up and running the thread.
Why is this happening and how to prevent the process from unloading the DLL? I've seen comments like this one suggesting to use GetModuleHandleEx but I'm not sure where to use it in the code and how. When finding the address of LoadLibrary in the target process or does it need to be called in the injected DLL? How would the method call look like then?
loadLibAddr = GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "LoadLibraryA");
Another suggestion was to repeatedly call LoadLibrary but when exactly? The process already unloaded the DLL after the thread creation so I'm not sure how this could be done.
Reflective injection does not work (e.g. GetReflectiveLoaderOffset() returns 0). I'm also working with entirely 64-bit applications.
I know this is possible since I've seen a persistent injection happen by another application.