JDługosz
JDługosz

Reputation: 5652

LoadLibraryEx ignoring fully-quallified path name?

From my reading of the MSDN documentation, I would think (in the case where a dll of that base name is not already loaded) that passing a fully-qualified absolute file name to LoadLibraryExW would look at that path only.

E.g. (and note that this is the correct CSIDL_SYSTEM path, if that makes a difference)

LoadLibraryExW (L"C:\\Windows\\System32\\foobar.dll", LOAD_LIBRARY_AS_DATAFILE);

should fail if that file does not exist in that location. But I'm getting funny results that make me think it's taking the base name and applying it to the PATH, on Windows 8.1. and finding a file with the same name somewhere else.

Furthermore, if I use LOAD_LIBRARY_AS_DATAFILE it prevents me from finding out just where it actually found it.

What does this function really do in this respect, and does it vary with OS version?

(BTW, I know about LOAD_LIBRARY_SEARCH_SYSTEM32, but that does not exist on all OS versions. I want to run on anything as far back as XP.)

It's especially confusing since I thought that using the absolute path was an effective fix for a previous time I saw it finding improper files via PATH, as a portable alternative to LOAD_LIBRARY_SEARCH_SYSTEM32. So maybe it varies by OS or some other magic changes the behavior.

Upvotes: 1

Views: 423

Answers (2)

JDługosz
JDługosz

Reputation: 5652

I have observed using Process Monitor that a fully-qualified file name used as the argument for LoadLibraryEx will indeed cause only that path to be checked (that is, when it does need to load a file because there's no DLL by that name already loaded). This was observed for a 32-bit process.

In the case of the System32 directory, what was given as an argument as C:\Windows\System32 appears in ProcMon as C:\Windows\SysWOW64, on a 64-bit OS.

This was observed in

  • Windows XP SP3, 32-bit (oddity: if the DLL was not present, QueryOpen is called twice with the same path)
  • Windows 7, 32-bit
  • Windows 10, 64-bit

One caveat is that even if named DLL is loaded from the specified directory with an absolute path, its dependent DLLs are loaded with normal searching of the PATH. This is not an issue when LOAD_LIBRARY_AS_DATAFILE is used.

Upvotes: 2

Adrian McCarthy
Adrian McCarthy

Reputation: 48021

Windows will ignore the path if there's already a DLL of that name loaded.

So if there's a foobar.dll already loaded in the process from some other path, then, even though you specified a full, absolute path to a different foobar.dll, it will just return a handle to the first one and bump the reference count.

Edited: Found the documentation for this behavior:

If a DLL with the same module name is already loaded in memory, the system checks only for redirection and a manifest before resolving to the loaded DLL, no matter which directory it is in. The system does not search for the DLL.

Upvotes: 1

Related Questions