Skip to content

PE Loader and Win32 DLLs

buntatoes edited this page Nov 28, 2026 · 2 revisions

PE Loader and Win32 DLLs

Vodka's libvodka_ntdll.so (vodka/src/ntdll/, also installed as lib/vodka/<arch>-unix/ntdll.so) is a standalone Apache-2.0 Zig + inline-assembly Windows PE64 and hardware CS=0x23 PE32/WoW64 loader and Unix boundary library. It loads Windows .exe and .dll binaries directly on Linux, binds their imports to native Zig PE DLLs and OS-backed Unix thunks, sets up Windows hardware thread state (TEB64/TEB32) and SEH/VEH exception recovery, and executes them at native speed.


Recursive PE64, Hardware CS=0x23 WoW64 & SEH/VEH Runtime

PE64 Execution Flow (pe.zig, virtual.zig, loader.zig, exec.zig)

When executing a Windows PE64 binary (vodka / vodka-pe --run <app.exe>):

  1. Header Validation (pe.zig): Parses DOS (MZ), NT (PE\0\0), COFF file header, Optional Header (PE32+, IMAGE_FILE_MACHINE_AMD64), section table, and data directories (exports, imports, base relocations, exception .pdata, TLS).
  2. Virtual Memory Mapping (virtual.zig): Allocates the image span via VirtualMemory (MEM_RESERVE | MEM_COMMIT), copies PE headers and each section to its VirtualAddress.
  3. Base Relocations: Applies delta relocations (IMAGE_REL_BASED_DIR64, IMAGE_REL_BASED_HIGHLOW) whenever the image is loaded away from its preferred ImageBase.
  4. TEB64 / PEB64 Initialization (teb.zig): Populates Peb64, Teb64, FastPebLock, and RtlUserProcessParameters with compile-time verified NT offsets (NT_TIB64.Self at 0x30, ClientId at 0x40, ThreadLocalStoragePointer at 0x58, PEB at 0x60, LastErrorValue at 0x68, vodka_thread_data at 0x2f0) and installs the user GS segment base via raw syscall(SYS_arch_prctl, ARCH_SET_GS, &teb).
  5. SEH .pdata Registration (seh.zig): Registers PE64 .pdata exception function tables for runtime unwinding (RtlLookupFunctionEntry / RtlVirtualUnwind).
  6. Recursive Import & Forwarder Resolution: Walks the Import Directory (ImportDescriptor), loading referenced DLLs from the executable directory, zig-out/lib/vodka/x86_64-windows, ../x86_64-windows, and VODKADLLPATH, binding IAT slots recursively — including recursive PE Export Directory forwarder resolution (dll.symbol) when an export RVA points inside the export directory range.
  7. PE64 Thread-Local Storage (IMAGE_TLS_DIRECTORY64): Allocates per-module static TLS slots, copies .tls initializers into the TEB64.ThreadLocalStoragePointer (GS:[0x58]) slot array, and initializes each module's _tls_index before invoking DllMain.
  8. Section Page Protections: Applies exact Win32 section protections (PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_READONLY, PAGE_READWRITE) based on section characteristics.
  9. DLL Initialization & Entry Point: Invokes each DLL's DllMain(hinst, DLL_PROCESS_ATTACH, NULL) via callWin64_3, then transfers control to the executable entry point via callWin64_2.

x86_64 Structured & Vectored Exception Handling (seh.zig)

vodka/src/ntdll/seh.zig implements native Windows x64 exception handling on Linux:

  • Decodes PE64 .pdata (RUNTIME_FUNCTION) and .xdata (UNWIND_INFO / UNWIND_CODE) tables for RtlLookupFunctionEntry and RtlVirtualUnwind.
  • Installs Linux sigaction(SA_SIGINFO) signal handlers translating SIGSEGV, SIGBUS, SIGFPE, SIGILL, and SIGTRAP into exact 1232-byte Microsoft x64 CONTEXT and EXCEPTION_RECORD (EXCEPTION_POINTERS) structures (EXCEPTION_ACCESS_VIOLATION, EXCEPTION_ILLEGAL_INSTRUCTION, EXCEPTION_INT_DIVIDE_BY_ZERO, EXCEPTION_BREAKPOINT, etc.).
  • Dispatches registered Vectored Exception Handlers (AddVectoredExceptionHandler / RemoveVectoredExceptionHandler) and supports full EXCEPTION_CONTINUE_EXECUTION register state restoration into Linux ucontext_t.

Hardware CS=0x23 PE32 / WoW64 Execution (wow64.zig)

vodka/src/ntdll/wow64.zig executes real compiled 32-bit i386-windows PE32 binaries natively on x86_64 Linux hardware:

  • Maps PE32 images and 32-bit stacks strictly below 4 GiB (MAP_32BIT), applying HIGHLOW base relocations and parsing 32-bit ImportDescriptor32 IATs.
  • Initializes ABI-exact NtTib32 (Self at %fs:0x18), Teb32 (ClientPid at 0x20, ClientTid at 0x24, PEB at %fs:0x30, LastErrorValue at 0x34, Wow64Transition gate at 0xC0), and Peb32 (ImageBaseAddress at 0x08, Ldr at 0x0C, ProcessParameters at 0x10).
  • Sets flat 32-bit DS/ES (0x2B), enters hardware 32-bit compatibility mode (CS=0x23), and bridges 32-bit stdcall API imports across a dynamic CS=0x23 <-> CS=0x33 call gate into Vodka's 64-bit runtime — live-verified via vodka_wow64_smoke.exe.

Inline-Assembly ABI Bridges (teb.zig)

Linux x86_64 uses the System V AMD64 ABI (rdi, rsi, rdx, rcx, r8, r9), whereas Windows PE64 code uses the Microsoft x64 ABI (rcx, rdx, r8, r9, 32-byte home/shadow space, 16-byte stack alignment).

Vodka bridges both directions without external trampolines:

  • Unix -> Win64: Explicit inline assembly (callWin64_1, callWin64_2, callWin64_3) preserves rbx, aligns rsp to 16 bytes, reserves 32 bytes of shadow space, loads Win64 argument registers, invokes the PE target, and restores rsp.
  • Win64 -> Unix: Native thunk functions use Zig's .{ .x86_64_win = .{} } calling convention on x86_64 so PE64 callers jump straight into Zig code with zero wrapper overhead.
  • Hardware TEB Reads: readCurrentTebSelf() reads %gs:0x30 on x86_64, %fs:0x18 on i386, and tpidr_el0 on aarch64.

Dynamic Loader, Linux Futex Sync & OS-Backed Thunks

Both static IAT resolution (resolveSingleImport) and dynamic LoadLibraryA/LoadLibraryW/GetModuleHandleA/GetModuleHandleW/GetProcAddress follow a strict, deterministic dispatch order:

  1. Native Authority Unix Thunks (bind directly to live Linux/host/daemon bridges):
    • Dynamic loader (LoadLibrary*, GetModuleHandle*, GetProcAddress, FreeLibrary) and seh.zig SEH/VEH APIs
    • Deep Win32 Runtime Thunks (win32_deep_thunks.zig):
      • Linux Futex Win32 Synchronization: Real FUTEX_WAIT_PRIVATE / FUTEX_WAKE_PRIVATE-backed SRWLOCK, CONDITION_VARIABLE, InitOnceExecuteOnce, WaitOnAddress / WakeByAddressSingle / WakeByAddressAll, recursive CRITICAL_SECTION, and Win32 Mutex primitives.
      • Per-Thread TLS & FLS: Full 1088-slot Thread-Local Storage (TlsAlloc/TlsGetValue/TlsSetValue/TlsFree) and Fiber-Local Storage (Fls*).
      • OS-Backed BCrypt (bcrypt.dll): Linux getrandom CSPRNG plus real SHA-256, SHA-512, SHA-1, and MD5 hashing.
      • OS-Backed WinHTTP (winhttp.dll): Live POSIX TCP networking (getaddrinfo/socket/connect/send/recv) paired with dynamic dlopen("libssl.so") TLS for HTTPS requests.
      • UTF-8/UTF-16LE & MinGW/UCRT Runtime: Complete Unicode conversion, file/mapping/system-info APIs, _beginthreadex, stdio, heap, and locale thunks.
    • UCRT/MinGW Startup & NT Native Thunks (crt_win32_thunks.zig): Real UCRT/MinGW initialization and ntdll.dll native syscall compatibility.
    • Live 43-opcode vodkaserver Registry & NT Kernel RPC thunks (reg_thunks, kernel_rpc_thunks)
    • Dynamic Vulkan 1.4 ICD & Wayland WSI swapchain thunks (vk_thunks)
    • Live D3D11-over-Vulkan / DXGI adapter bridge, GDI DIB rasterizer, and extended C11 CRT thunks (dxgi_crt_thunks)
    • WinSock2, WinMM, and XInput/evdev thunks (net_input_thunks)
    • COM, Shell, PSAPI, IP Helper, SetupAPI, and Cert thunks (desktop_thunks)
    • PipeWire/ALSA/WASAPI (IAudioClient/IAudioRenderClient COM vtables), XAudio2, and DirectSound thunks (audio_thunks)
    • Process creation, pipes, and directory enumeration thunks (proc_thunks)
    • Wayland User32/GDI32 GUI bridge & 128-entry Win32 message queue thunks (gui_thunks)
  2. Cross-Compiled Vodka PE Module Exports: Searches loaded and on-disk PE modules in lib/vodka/<arch>-windows/ and VODKADLLPATH, recursively resolving PE Export Directory forwarder strings (dll.symbol), and returns the real PE export address (mod.base + export_rva).
  3. Core OS Fallback Thunks (os_thunks): Provides direct Unix-backed implementations for core file/console/memory/time/environment Win32 APIs when not already satisfied by a PE export.

Complete Catalog of 731 Multi-Architecture PE Modules

All 731 Windows PE modules are managed declaratively in vodka/build/dll_manifest.zig (selectable via -Ddll-set=core|gaming|full, default full) and cross-compiled directly from Zig (link_libc = false) into three Windows architectures (x86_64-windows, i386-windows, aarch64-windows) — 2,193 PE binaries per build:

Manifest Group Module Count Scope & Representative Modules
Core & Gaming Base 41 ntdll, kernelbase, kernel32, advapi32, sechost, msvcrt, ucrtbase, vcruntime140*, msvcp140, version, gdi32, user32, bcrypt, crypt32, ole32, combase, rpcrt4, shell32, shlwapi, psapi, ws2_32, iphlpapi, setupapi, winhttp, vulkan-1, dxgi, d3d11, d3d12, opengl32, d3dcompiler_47, winmm, mmdevapi, dsound, xaudio2_9, dinput8, xinput*
Forwarders, Metadata, TypeLibs & Themes 99 apisetschema, normaliz, usp10, icu, winsqlite3, d3d12core, audioses, ksuser, ksproxy.ax, bthprops.cpl, irprops.cpl, binary MSFT TypeLibs (stdole32.tlb, mshtml.tlb, activeds.tlb), light.msstyles, COM proxies
WoW64, NT Kernel Executive, HAL & Drivers 25 wow64, wow64cpu, wow64win, ntoskrnl.exe, hal.dll, and 20 .sys kernel drivers (fltmgr.sys, mountmgr.sys, ksecdd.sys, ndis.sys, netio.sys, hidparse.sys, hidclass.sys, vodkabus.sys, vodkahid.sys, vodkausb.sys, vodkabth.sys, vodkaxinput.sys, etc.)
Legacy/Versioned CRT, MSVC C++ STL, ConcRT & OpenMP 31 crtdll, msvcrt20, msvcrtd, msvcr70–msvcr120, msvcirt, msvcp60–msvcp120, msvcp140_1 (PMR), msvcp140_2 (C++17 math), msvcp140_atomic_wait, msvcp140_codecvt_ids, msvcm80/90, concrt140, vcomp*
Graphics, DirectX 8–12, D3DX & 2D Imaging 66 vodkad3d, d3d8, d3d9, d3d10, d3d10_1, d3d10core, ddraw, dcomp, dxva2, d3dcompiler_*, d3dx9_*/10_*/11_*, glu32, d2d1, dwrite, windowscodecs, gdiplus, mscms
Windowing, Printing, Audio, Input & Media 113 win32u, imm32, uxtheme, dwmapi, msimg32, comctl32, comdlg32, winspool.drv, xaudio2_*, x3daudio*, xapofx*, dinput, mfplat, mf, mfreadwrite, quartz, wmvcore, wmp, vodkagstreamer
COM/OLE, Shell, Networking, Crypto & WMI 108 oleaut32, oleacc, propsys, coml2, comsvcs, actxprxy, dispex, urlmon, wininet, dnsapi, secur32, schannel, ncrypt, wintrust, wbemprox, wbemdisp, wmiutils
Windows Runtime (WinRT) 50 wintypes, rometadata, threadpoolwinrt, cryptowinrt, coremessaging, bcp47langs, appxdeploymentclient, twinapi.appcore, gameinput, gameux, windows.ui*, windows.web*, windows.system*
XML, Web & Scripting 25 xmllite, msxml, msxml2–msxml6, jscript, vbscript, scrrun, scrobj, msscript, wshom, mshtml, itss, inetcpl, inetcomm
Extended Gaming, Display & Fonts 32 amd_ags_x64, amdxc64, atiadlxx, dxcore, dxdiagn, dx8vb, wing32, dciman32, dmusic32, rtworkq, mfplay, magnification, fntcache, fontsub, t2embed
Enterprise, ODBC, OLE DB & Directory Services 45 odbc32, odbccp32, oledb32, msado15, activeds, adsldp, dsquery, ntdsapi, capi2032, msdrm, wsdapi
System Services, Power, Diagnostics & SNMP 43 apphelp, winbrand, mlang, winnls32, userenv, slc, sppc, powrprof, rstrtmgr, nddeapi, snmpapi, wsnmp32, mgmtapi
16-Bit NE, Win32s/VDM & .vxd Virtual Devices 53 krnl386.exe16, user.exe16, gdi.exe16, system.drv16, shell.dll16, commdlg.dll16, ole2.dll16, mmsystem.dll16, winsock.dll16, w32skrnl, vdmdbg, and all 9 .vxd virtual device drivers (vmm.vxd, vwin32.vxd, ifsmgr.vxd, mmdevldr.vxd, monodebg.vxd, vdhcp.vxd, vnbt.vxd, vnetbios.vxd, vtdapi.vxd)
Total 731 2,193 cross-compiled PE binaries (731 × 3 Windows architectures)

Shared Pure-Zig Core Runtime Engines (vodka/src/dlls/)

Vodka's 731 PE modules share modular, unit-tested core engines compiled directly into the PE targets:

  • Core NT & Security (core/nt_core.zig, core/sec_core.zig, kernel/kernel_drv_core.zig, drivers/drv_util.zig): Slab heap allocator, SRWLOCK/CONDITION_VARIABLE/CRITICAL_SECTION/INIT_ONCE/WaitOnAddress, ThreadPool, inline-asm Fibers, VEH, TLS/FLS, RTL_BITMAP, CRC-32, FILETIME calendar math, NLS/CodePages, inline-asm QPC, SID/ACL/SD/SDDL, LUID/Token privileges, SCM, ETW/EventLog, std.crypto CryptoAPI + Blake3-XOF CSPRNG, and NT kernel driver runtime.
  • CRT, C++ STL & Concurrency (crt/crt_core.zig, crt/crt_compat.zig, cpp/stl_core.zig, concrt/concrt_core.zig, crt_extended.zig): C11/MSVCRT/UCRT runtime, inline-asm setjmp/longjmp, IEEE-754 libm, Win64/SysV variadic vsnprintf/sscanf, MSVC C++ EH/RTTI/FNV-1a type_info, C++17 special math, C++20 atomic wait, ConcRT task scheduler, and OpenMP 2.0/3.0.
  • Graphics, Imaging, Windowing & Media (gfx/gfx_core.zig, gfx/dxbc_compiler.zig, d3dx/d3dx_core.zig, imaging/imaging_core.zig, gdi_raster.zig, user32_wm.zig, win/win_core.zig, xaudio/xaudio_core.zig, audio_input/audio_input_core.zig, media/media_core.zig): Unified GFX engine, DXBC shader compiler, D3DX math/mesh/texture helpers, WIC/GDI+ imaging, GDI DIB rasterizer, User32 window manager, XAudio2/DirectInput, and Media Foundation/DirectShow runtime.
  • COM, Shell, Net, Crypto, WinRT, Web, Enterprise & Compat16 (com/, shell/, net/, crypto/, winrt/, web/, gaming_extra/, enterprise/, sys_services/, compat16/): Shared runtime engines powering the COM, WinRT, enterprise, system-service, and 16-bit compatibility modules across all three Windows architectures.

Clone this wiki locally