title: Detect the unloading of DLLs
body: <p>I have a special requirement, and I believe there is no other way,
  that is: Detect the unloading of DLLs. I googled it and found out
  <a href="https://stackoverflow.com/questions/4242469/detect-when-a-module-dll-is-unloaded">a four-years old SO</a> about this. I have chosen the same
  solution: Hook <code>FreeLibrary</code>.</p>
  
  <p>When code goes into <code>MyFreeLibrary</code>, I will hook the entry point of
  the specified module in the same way (inline-hook). And in
  <code>MyEntryPoint</code>, I will call the original entry point first, then
  check the <code>reason</code> argument - if the value equals to
  <code>DLL_PROCESS_DETACH</code>, it means that the cleanup work of this DLL is
  just done, and it's going to be unloaded from the address space.
  At this point, I have the chance do my job. It works.</p>
  
  <p>So that's it ? Unfortunately, it's not finished. A very important
  thing is overlooked: dependency.</p>
  
  <p>For example, <code>a.dll</code> links against <code>b.dll</code> and <code>c.dll</code>. When you load
  <code>a.dll</code>, <code>b.dll</code> and <code>c.dll</code> will be loaded (be initialized) first. This
  is because <code>b.dll</code> and <code>c.dll</code> are listed in the import table of
  <code>a.dll</code>, they are dependencies of <code>a.dll</code>. Similarly, when you unload
  <code>a.dll</code>, <code>b.dll</code> and <code>c.dll</code> may be also unloaded if their reference
  count decreased to zero. I don't know the detail about how the
  loader finds out the dependencies of a DLL and unload them, The
  <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms683152%28v=vs.85%29.aspx" rel="nofollow noreferrer">MSDN</a> page of <code>FreeLibrary</code> didn't talk about this, I'm glad to
  understand this but I did't find the information.</p>
  
  <p>So the main problem is how to detect the unloading of dependencies
  of a DLL module. I want to have the same chance to do my job.</p>
  
  <p>A possible solution may be the import table, find out the
  dependencies of a DLL from its import table, and find out the
  dependencies of dependencies from their import table and so on,
  find out all the dependencies, hook all the entry points, I don't
  know, It sounds crazy, I need some advice here.</p>