tags:

views:

107

answers:

4

As you know, if the call to LoadLibrary specifies a DLL module already mapped into the address space of the calling process, the function simply returns a handle of the DLL and increments the module's reference count.

Somewhere, I need to get the reference count of a dll. How to get the dll's reference count? How to know where the dll was loaded? Thanks.

A: 

This information isn't available via a public API afaik. What's your scenario? Running AppVerifier will catch any mistakes you've made with module (or any other) handles.

Paul Betts
+3  A: 

I googled it, and found this article which claims to provide the answer. Sorry I couldn't be more helpful:

C Johnson
+1 for your perspective on programmatically getting the count
Chubsdad
@C Johnson, did you tried it? This solution depends on undocumented features, which are not guaranteed to work in future versions of Windows.
Kirill V. Lyadvinsky
Actually, they're not even guaranteed to work in _current_ versions of Windows :-)
paxdiablo
+1  A: 

If it is a non programmatic way (thanks to C.Johnson for giving that perspective), WinDBG could be helpful

http://windbg.info/doc/1-common-cmds.html#10_modules

Look at !dlls and it's variants.

!dll - all loaded modules with load count

EDIT 2:

If you want to know from where all the DLL is being loaded from the process, there are two ways:

a. Look at the command

"bu kernel32!LoadLibraryExW ";as /mu ${/v:MyAlias} poi(@esp+4); .if ( $spat( \"${MyAlias}\", \"MYDLL\" ) != 0 ) { kn; } .else { g }" "

in the above URL

b. Run the process under WinDBG. Debug->Even Filter and select "Load Module" and set it to "Enabled" under "Execution". Under "Continue" set it to "Not Handled".

One of these should help you definitely.

Chubsdad
@jack2000: If it is for debugging purpose as you mentioned elsewhere, WinDBG and it's every increasing powerful features should definitely give you a headstart.
Chubsdad
@jack2000: Check if the information under Edit 2 helps
Chubsdad
+1  A: 

I'm not certain you fully understand how LoadLibrary/FreeLibrary is meant to work. You call FreeLibrary when you're finished with it and that decrements the reference count that was incremented when you loaded it. If some other part of your process is still using it, it's probably not your concern.

The reference count may tell you how many times it's been "loaded" but won't help in figuring out who loaded it.

paxdiablo
process explorer can tell who all are using a given DLL.
Chubsdad
@chubsdad, that'll tell you what process is using it but will it tell you where it was loaded from within a process. My understanding is that this is all happening within a single process: `FreeLibrary` is an in-process thing, reference counting does not cross process boundaries, they're for mapping into the local address space only.
paxdiablo
Of course, it's best to know where it was loaded.:)