Windows Loader & DLL Injection
Windows Internals for Low-Level Programming · Windows Programming track
8 min read
In this module
How Windows Loads Executables
When you double-click an EXE or call CreateProcess, the Windows loader runs a choreographed sequence of operations to transform a PE file on disk into a running process in memory. Understanding this sequence is what makes DLL injection, process hollowing, and related techniques legible.
The Loading Process
1. CreateProcess called2. Kernel creates process object (EPROCESS), address space3. Map ntdll.dll into the new address space4. Create initial thread (suspended)5. Thread starts at LdrInitializeThunk (in ntdll.dll)6. LdrpInitializeProcess: a. Initialize PEB (Process Environment Block) b. Map the executable image at its preferred base (or ASLR base) c. Process the import table: - For each imported DLL: i. Map the DLL into memory ii. Recursively process ITS imports iii. Call DllMain(DLL_PROCESS_ATTACH) - Resolve function addresses, fill the IAT d. Process TLS (Thread Local Storage) initializers e. Call TLS callbacks f. Transfer control to the entry point (AddressOfEntryPoint)The PEB and TEB
Process Environment Block (PEB)
The PEB is a user-mode structure accessible from every thread. It is found at fs:[0x30] on 32-bit or gs:[0x60] on 64-bit Windows:
typedef struct _PEB { BOOLEAN InheritedAddressSpace; BOOLEAN ReadImageFileExecOptions; BOOLEAN BeingDebugged; // Anti-debug check target! // ... PPEB_LDR_DATA Ldr; // Loaded module list PRTL_USER_PROCESS_PARAMETERS ProcessParameters; // ProcessParameters contains: // CommandLine, CurrentDirectory, Environment, // ImagePathName, WindowTitle, StandardInput/Output/Error PVOID SubSystemData; PVOID ProcessHeap; // Default process heap // ... DWORD NtGlobalFlag; // Debugging flags // ...} PEB;The Loaded Module List
The PEB's Ldr field points to a structure containing three doubly-linked lists of loaded modules:
typedef struct _PEB_LDR_DATA { DWORD Length; BOOLEAN Initialized; PVOID SsHandle; LIST_ENTRY InLoadOrderModuleList; // Order loaded LIST_ENTRY InMemoryOrderModuleList; // Order in memory LIST_ENTRY InInitializationOrderModuleList; // Init order} PEB_LDR_DATA;
// Each entry is an LDR_DATA_TABLE_ENTRY:typedef struct _LDR_DATA_TABLE_ENTRY { LIST_ENTRY InLoadOrderLinks; LIST_ENTRY InMemoryOrderLinks; LIST_ENTRY InInitialisationOrderLinks; PVOID DllBase; // Base address of the DLL PVOID EntryPoint; // DllMain address ULONG SizeOfImage; UNICODE_STRING FullDllName; // Full path UNICODE_STRING BaseDllName; // Just the filename // ...} LDR_DATA_TABLE_ENTRY;Shellcode and malware frequently walk the PEB's module list to find function addresses without calling GetProcAddress (which would require knowing kernel32's address first). The technique: access PEB via TEB, walk InLoadOrderModuleList to find kernel32.dll by name, then parse its export table to find LoadLibraryA and GetProcAddress. This bootstrapping technique is fundamental to shellcode development.
Thread Environment Block (TEB)
Each thread has a TEB accessible via the GS segment register (x64) or FS register (x86):
typedef struct _TEB { NT_TIB NtTib; // Exception list, stack base/limit PVOID EnvironmentPointer; CLIENT_ID ClientId; // ProcessId, ThreadId PVOID ActiveRpcHandle; PVOID ThreadLocalStoragePointer; PPEB ProcessEnvironmentBlock; // Pointer to PEB DWORD LastErrorValue; // GetLastError() reads this // ...} TEB;
// Accessing TEB in assembly (x64):// mov rax, gs:[0x30] ; TEB base// mov rax, gs:[0x60] ; PEB pointerThe Loader Lock
The loader holds a critical section called the loader lock while it maps DLLs and runs their DllMain, both during process initialisation and on every later LoadLibrary or FreeLibrary. All DllMain calls are serialised through this lock. This means:
- DllMain shouldn't call LoadLibrary. The lock is re-entrant, so the calling thread won't deadlock on it outright, but the new DLL can end up running before the DLLs it depends on are initialised, and Microsoft's guidance is to avoid it
- DllMain cannot wait for another thread that needs the loader lock (that one is a real deadlock)
- Complex initialisation in DllMain is dangerous
DLL Injection Techniques
DLL injection forces a target process to load an attacker-chosen DLL. Legitimate users include debuggers, profilers, and accessibility tools. Less legitimate users include malware and game cheats.
Technique 1: CreateRemoteThread + LoadLibrary
The classic injection method:
// 1. Open the target processHANDLE hProcess = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, targetPid);
// 2. Allocate memory in the target for the DLL pathconst char *dllPath = "C:\\inject\\payload.dll";SIZE_T pathLen = strlen(dllPath) + 1;LPVOID remoteMem = VirtualAllocEx(hProcess, NULL, pathLen, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
// 3. Write the DLL path into the target's memoryWriteProcessMemory(hProcess, remoteMem, dllPath, pathLen, NULL);
// 4. Get the address of LoadLibraryA (same in all processes due to ASLR per-boot)LPVOID loadLibAddr = (LPVOID)GetProcAddress( GetModuleHandle("kernel32.dll"), "LoadLibraryA");
// 5. Create a remote thread that calls LoadLibraryA(remoteMem)HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)loadLibAddr, remoteMem, 0, NULL);
// 6. Wait for injection to completeWaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);VirtualFreeEx(hProcess, remoteMem, 0, MEM_RELEASE);CloseHandle(hProcess);The six comments are easier to follow once you see which process each step touches. The injector does all the work through handles; the target only acts at the very end, when its new thread runs:
The trick in step 5 is that LoadLibraryA takes one pointer argument, exactly like a thread start routine, so the kernel can't tell the difference. That's also the step EDR products watch most closely.
Technique 2: SetWindowsHookEx
Install a Windows hook that forces a DLL to be loaded into processes that process the hooked message type:
// The hook DLL exports a hook procedure// Setting a global hook causes Windows to inject the DLL// into every process that processes that message typeHMODULE hMod = LoadLibrary("hook.dll");HOOKPROC hookProc = (HOOKPROC)GetProcAddress(hMod, "HookProc");HHOOK hHook = SetWindowsHookEx(WH_KEYBOARD, hookProc, hMod, 0);// 0 = all threads (global hook)Technique 3: AppInit_DLLs (Legacy)
A registry value that causes specified DLLs to be loaded into every process that loads user32.dll:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\ AppInit_DLLs = "C:\inject\payload.dll" LoadAppInit_DLLs = 1This method is largely dead on modern Windows. Since Windows 8 the loader ignores AppInit_DLLs whenever Secure Boot is on, Windows 7 added a RequireSignedAppInit_DLLs value that only lets signed DLLs load this way, and Microsoft tells developers not to use it.
Process Hollowing
Process hollowing creates a suspended process, unmaps its image, maps a different executable in its place, and resumes it:
The result appears to be a legitimate process (svchost.exe) in task manager but is actually running completely different code.
Security tools detect DLL injection through several methods: monitoring CreateRemoteThread calls, checking for unexpected DLLs in process module lists, watching for WriteProcessMemory to executable regions, monitoring the loader lock for unusual activity, and comparing a process's on-disk image to its in-memory image (detecting hollowing). ETW (Event Tracing for Windows) provides kernel-level visibility into these operations.
The Windows loader and injection techniques are unavoidable territory for security research, malware analysis, and tools that need to interact with other processes. The loader's behaviour governs how ASLR works, how imports get resolved, and how attackers subvert the entire loading process.