Pavel Yosifovich, co-author of “Windows Internals 7th Edition, Part 1” and author of “Windows Native API Programming”, answers a question that sounds simple: when a program needs a DLL, where does Windows look for it? The import table of an executable lists DLLs by name only, and so do most calls to LoadLibrary. Somebody has to turn that name into a file. This post walks through the search order, then looks at it live with a few tools, including a small spoofing experiment that works for one DLL and fails for another. It is for developers who ship DLLs, and for security researchers who care about DLL hijacking from either side.
Two Ways to Depend on a DLL
Executables have dependencies. If a program calls CreateFile, the documentation says it is implemented in kernel32.dll, so that DLL must be available for the call to work. There are two ways to get such a DLL into the process.
The first is required DLLs. These are listed in the import table of the PE file: “these are my dependencies, and they must be satisfied before I can do anything useful”. The loader, which is part of ntdll.dll, runs before the executable’s entry point and takes care of them. Your main function, whatever it is, is not called until every required DLL has been loaded. And this is recursive, because each DLL can have its own imports, so the loader has to walk those too.
The second is dynamic loading with LoadLibrary, at any time you like. It is more flexible: if the DLL is not found you get a NULL handle back and can do something else, maybe fall back to another option. With a required DLL, there is no plan B. The process simply does not start. The price of the flexibility is more work, since every function has to be located with GetProcAddress and called through a pointer.
What does “loading” mean here? Two things. First, locating the file. Second, calling the DLL’s DllMain with DLL_PROCESS_ATTACH, which has to return TRUE to indicate successful initialization. If it returns FALSE, the DLL is unloaded, and if it was a required DLL, the process terminates.
The Search Order (Simplified)
This is the simplified view. Simplified, because side-by-side assemblies, manifests and stuff like that also play a role, and they are not covered here. Microsoft’s full description is in Dynamic-link library search order. Without those, the order is:
1. Known DLLs. If the name is a known DLL, it is taken from there and the file system is never searched. More on this below, because it is the most interesting part. 2. The executable’s directory. This is the best place for your private DLLs. It also makes the application easy to move: copy all the files to another directory and the dependencies are still found, very early in the search. 3. The System32 directory. Where most Microsoft binaries live, kernel32.dll for instance. 4. The System directory. A relic from 16-bit Windows, still searched for compatibility. On current systems it is pretty much empty. 5. The Windows directory. Typically C:\Windows. 6. The current directory of the process. Every process has one, and the creator can set it with the lpCurrentDirectory parameter of CreateProcess. When you double-click an executable in Explorer, Explorer sets the current directory to the executable’s own directory. That is just how Explorer calls CreateProcess (or ShellExecute, which ends up there). 7. The directories in the PATH environment variable.
If the DLL is not found anywhere, you get the familiar “The code execution cannot proceed because X.dll was not found” message box, and the process shuts down.
Looking at Imports: and those api-ms-win DLLs
Opening regedit.exe in TotalPE shows its import directory: gdi32.dll, user32.dll, msvcrt.dll, ntdll.dll and so on, with the imported functions for each in the bottom pane. There are also a bunch of names that look like DLLs but are a bit weird, such as api-ms-win-core-registry-.... These are API sets.
Why do they exist? Because linking directly to a specific DLL creates a hard dependency on where a function is implemented. CreateFile is documented as living in kernel32.dll, but Microsoft moved the implementation to kernelbase.dll at some point. Since every existing application imports it from kernel32.dll, that dependency is basically impossible to change, so kernel32 now just forwards the call to kernelbase. (If you want to see where CreateFile goes after that, see From CreateFile to Kernel’s NtCreateFile.)
An API set avoids the problem. It is an interface, a named group of functions, and the application says “I need an implementation of this interface, I do not care which DLL provides it”. At runtime the system maps the API set to the actual implementation DLL on that particular Windows version, which could be different in a future (or past) version. Loose coupling instead of a hard dependency. Where the API set schema is stored and how it is parsed is a topic for another time.
Everything in the import table, real DLLs and API sets alike, resolves to required DLLs. What the import table cannot show you is what the process loads later with LoadLibrary, directly or indirectly, for example through COM, which loads the DLLs that implement COM classes on demand. For that, you have to look at a running process.
Watching the Loader Work: Show Loader Snaps
GFlags (Global Flags), part of the Debugging Tools for Windows, can set flags system-wide (registry or kernel) or per image. The per-image part is the useful one here: type an executable name such as regedit.exe, and the flags apply to any executable with that name, no matter which directory it runs from. The flag of interest is Show loader snaps, which makes the loader print what it is doing: locating DLLs, resolving API sets, binding functions, things like that.
I also wrote a tool called GFlagsX, which lists all the executables that already have settings and is, I think, a bit easier to work with. Whichever tool you use, the result is the same registry value: under HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options, there is a key per executable name, and in this case GlobalFlag is set to 2, which is exactly the show loader snaps flag. You can also write it directly, but you need admin rights, since this is under HKEY_LOCAL_MACHINE. That is a good thing: these settings change how processes behave, and a standard user should not be able to set them. (Image File Execution Options shows up in security work for exactly that reason; see DLL Injection with Windows Application Verifier for another use of the same key.)
Now launch regedit under a debugger. Before anything else, at the initial breakpoint, the output window is full of lines from Ldrp* functions, the loader’s private functions. You can see kernel32.dll being loaded and flagged as a known DLL, kernelbase.dll the same, and API set redirections, such as an api-ms-win-core-rtlsupport-... set redirected to ntdll.dll, because that is where those functions are implemented on this system. You can see it binding imported functions by name, and if a function or DLL cannot be found, the error shows up here too.
All of this happens very early. The call stack at that point has only a few loader functions on it. The entry point has not been called, regedit’s main function has not run, and there is no window yet. If you want to learn what the loader does, this output is a great place to start.
A Spoofing Experiment: secur32.dll vs. kernel32.dll
To make things more interesting, take a small application, in this case a logon sessions viewer written for an earlier video. It imports the Visual C++ runtime, kernel32.dll and secur32.dll, which provides LsaEnumerateLogonSessions. Running it under a debugger, the modules window shows kernel32.dll and secur32.dll both loaded from System32. As expected.
The search order says the executable’s directory comes before System32. So copy kernel32.dll from System32 into the application’s directory and run again. Kernel32 is still loaded from System32. The local copy is ignored.
Now do the same with secur32.dll. This time the modules window shows secur32.dll loaded from the application’s directory. That means if I write my own secur32.dll that implements the functions differently, I can spoof this executable into loading my DLL instead of the real one. This is the essence of DLL hijacking (or DLL spoofing, DLL planting, depending on who you ask).
Is that a disaster? Not necessarily. Most applications are installed under Program Files, and only administrators can write there, so you need admin rights to plant a DLL next to them. Applications that live in user-writable directories are a different story. Which is why Microsoft has a whole page on DLL security.
But why did it work for secur32 and not for kernel32?
Known DLLs
Known DLLs are listed in the registry under HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs. Early in the boot, SMSS (the Session Manager, the first user mode process) maps each of them into a section object. When a process loads a DLL whose name is a known DLL, the loader never searches the file system. It uses the existing section object directly.
kernel32.dll is in that list. secur32.dll is not. So secur32 goes through the normal search, where the application’s directory is the first file system location, and kernel32 never gets there. That is the entire difference.
You can see the section objects themselves in the object manager namespace with WinObj: there is a \KnownDlls directory containing a section object per DLL, kernel32.dll among them. That is why known DLLs cannot be spoofed by dropping a copy next to an executable. Many other Microsoft DLLs are not known DLLs, though, and those can be spoofed just like secur32.
(Loading the DLL is one side of the story. If you are interested in what happens to a loaded DLL from the loader’s bookkeeping point of view, see Hiding a DLL from the PEB Loader List.)
When a Required DLL Is Missing
One more experiment. ConfigHook, from the simple hooking samples, has a private DLL called HookDll.dll in its import table, sitting in the same directory. It runs fine. Delete HookDll.dll and run it again, and you get the message box: “The code execution cannot proceed because HookDll.dll was not found. Reinstalling the program may fix this problem.”
Here is a detail most people never notice. That message box does not come from the process that failed to start. Check which process owns that window, and it is csrss.exe, the Windows subsystem process, of which there is one per session. Your process is not running enough to show anything. It might not even depend on user32.dll, so it might not be able to show a message box at all. So CSRSS does it on its behalf.
What This Means Practically
- The import table lists DLL names without paths; the loader resolves them before the entry point runs. A missing required DLL means the process never starts.
LoadLibrarylets you handle a missing DLL gracefully, at the cost ofGetProcAddressfor every function.- Simplified search order: known DLLs, executable directory, System32, System, Windows, current directory, PATH.
- Known DLLs (
HKLM\...\Session Manager\KnownDLLs) are mapped by SMSS at boot and never searched in the file system, so they cannot be spoofed with a local copy. Other DLLs can. - Put private DLLs in the application’s directory, and install applications where standard users cannot write.
- API sets (
api-ms-win-*) are interfaces resolved at runtime to the implementing DLL on that Windows version. - To see what the loader is really doing, set “show loader snaps” (
GlobalFlag= 2 in Image File Execution Options) and run the process under a debugger.
Keep Learning
If you want to go further with DLLs, the loader and what attackers do with them, these TrainSec courses go deeper:
- Windows DLLs, Security and COM in C++: building and consuming DLLs, explicit linking with
LoadLibraryandGetProcAddress,DllMain, and DLL injection - Malware Development Course and Malware Analysis Training: process creation, known DLLs and DLL loading from the attacker’s and the analyst’s side
- WinDbg Course Online: Windows Debugging: the debugger skills used here, from the initial breakpoint to the modules list