This is the article about the custom FreeLibrary implementation, which has probably been the easiest one. In fact, once stored all the information about all the loaded modules.
In fact, the first thing to do, is checking how many instances have been loaded of the specified modules; I wouldn’t unload from memory a module loaded several times just because a FreeLibrary call has been made: rather I use a counter for each module decremented every time that the FreeLibrary is called for that module and, when this counter reaches 0, the module can be fully removed.
If the counter has reached 0, the flags with which the module has been loaded should be checked: if the module has been loaded with the flags LOAD_LIBRARY_AS_DATAFILE or DONT_RESOLVE_DLL_REFERENCES, then it is not necessary to call the DllMain function for detaching, as the code has not been initialized and the dependencies resolved. Otherwise, the first thing to do is calling the DllMain with the DLL_PROCESS_DETACH flag. Now it is possible to proceed to unload all the dependencies (obviously this step can be skipped if the module has been loaded with the DONT_RESOLVE_DLL_REFERENCES flag).
As all the modules loaded as a dependency of another module are stored in a list inside the library, is pretty simple to recursively unload them: in fact it is done like this indeed, module by module, until the list is over.
Now that the dependencies have been unloaded, it is possible to completely remove the module from memory by calling the UnmapViewOfFile function.
Well, I think that the custom implementation of those APIs is now “complete”. The source code is available on GitHub: for sure it is buggy and lacking of some features, but, for now, it seems to work. Please notify me each bug or propose new features/patch. I really hope to not have been boring in this short series of articles. By now, I don’t know which one will be the next topic, but there surely will be one.
Catch ya soon.