Good way to detect a DLL unload

The PsSetLoadImageNotify callback only tells us when a DLL is loaded, and since DLLs are memory mapped, the FILEOBJECT which we get as part of the same callback is also closed immediately after, so tracking IRP_MJ_CLEANUP doesn’t cut it.

Is there a good way to track image unloads? Is there a backing FILE_OBJECT for the memory mapped sections which can somehow be used to accomplish this task?

No way…

There’s no callback to tell you when a section is close (i.e. CloseHandle on the section).

Mm keeps a reference to the first file object used to create the section so that the data can be cached long after it’s unmapped/closed. If you see an IRP_MJ_CLOSE for the last file object for the stream you definitively know it’s no longer mapped. However, this IRP_MJ_CLOSE may not actually ever arrive (e.g. Mm doesn’t purge sections on shutdown)

@“Scott_Noone_(OSR)” said:
No way…

There’s no callback to tell you when a section is close (i.e. CloseHandle on the section).

Mm keeps a reference to the first file object used to create the section so that the data can be cached long after it’s unmapped/closed. If you see an IRP_MJ_CLOSE for the last file object for the stream you definitively know it’s no longer mapped. However, this IRP_MJ_CLOSE may not actually ever arrive (e.g. Mm doesn’t purge sections on shutdown)

So, if I am reading this right, the Destroy event for the stream context also is not guaranteed to tell me about a DLL unload. I was hoping that the stream context destroy event was my only hope here.

So, if I am reading this right, the Destroy event for the stream context also is not guaranteed to tell me about a DLL unload. I was hoping that the stream context destroy event was my only hope here.

Correct. The DLL has to be unloaded for the the stream context destroy callback to fire but the callback can be delayed indefinitely.

In UM the DllMain function is called with DLL_PROCESS_DETACH shortly before the unload occurs within an address space. This is probably completely unhelpful because it is UM only and leveraging it for a DLL that you did not author requires hacking the entry point, but it is the only notification of DLL unload anywhere that I know of.

tracking or preventing a new image (dll, exe etc.) from being loaded is much more common and surely more useful I think

Well if you are inside the user process that unloads the DLL you can use LdrRegisterDllNotification:

https://docs.microsoft.com/en-us/windows/win32/devnotes/ldrregisterdllnotification

But this is very limited and has a high cost (loading your DLL into random processes is not a good idea in the first place)