master131 / ExtremeInjector

745 stars 173 forks source link

Unloading managed dll #11

Closed Mik4sa closed 5 years ago

Mik4sa commented 6 years ago

So, you showed us here how to inject a managed dll into a process, which works fine. But is there also a way to unload a managed dll from the injected process? I sadly haven't found one.

master131 commented 6 years ago

I'm not sure that's entirely possible. Extreme Injector loads .NET DLLs like any normal injectable DLL and lets the OS automatically load the .NET CLR which performs all the management of assemblies and creation of the default AppDomain.

Within the context of a normal .NET application you can't unload an assembly unless you unload the entire AppDomain which it resides in (see here) which requires you to have control over the AppDomain your assembly is loaded in.

Mik4sa commented 6 years ago

hmm, too bad. So, my actual problem is that once I injected my dll into the process I wasn’t able to unload it, make some changes to the dll and inject it again into the process.

I could maybe inject a helper dll with loads the actual dll. Then I could atleast unload the actual dll when I have to.

This would ofcourse still leave the helper module in the process, but I guess I won’t come around this

Mik4sa commented 6 years ago

Would it be possible for Extreme Injector to create a app domain per injected managed dll? So we would be able to unload the given assembly later then.

master131 commented 6 years ago

Perhaps, but that would require me to write a C++ helper DLL or stubs to manually load the CLR into the target process which is annoying and tedious work.

You may want to write your own C#/VB helper DLL which receives messages via some messaging protocol (eg. local TCP port, named pipe, etc) from an app which tells it what assembly to load into a new AppDomain. Then the helper DLL can simply unload the new AppDomain when requested.

tapika commented 1 year ago

I've prototyped support of loading managed .dll to ram, after which it's possible also to free it - like completely.

https://github.com/tapika/dllloader

I'm not sure about sideeffects to .net runtime when .dll will go down. Something to play / analyze probably for those who want to do it.