How fex-emu/fex works
Project Type & Purpose
• This is FEX, a high-performance x86-on-ARM64 emulator for Linux (with Wine/Proton support).
• It combines compiler-like stages (decode → IR → JIT codegen → execute), interpreter fallback, syscall emulation, and host-API forwarding (OpenGL/Vulkan/X11/etc.).
Top-Level Structure
• CodeEmitter: ARM64 machine-code emitter templates and utilities.
• FEXCore: Core translation engine
– Interface/IR: internal representation & IR passes (validation, optimization, register allocation).
– Interface/Core: CPUBackend abstraction, opcode dispatchers, code cache, fallback interpreter, JIT orchestration.
– Utils: memory allocators, threading, logging, telemetry.
• Source/Tools: CLI tools (FEXServer, FEXInterpreter, FEXRootFSFetcher, FEXConfig GUI), LinuxEmulation (syscall handlers, seccomp emulator, guest context), Windows port.
• ThunkLibs: guest-side stubs and host-side shims for graphics and system libraries.
• External: third-party dependencies (Vixl, SoftFloat, Catch2, Cephes, etc.).
• Data & Scripts: configuration files (JSON), Docker/Nix setups, CI workflows, build toolchain definitions.
• unittests: exhaustive API, emitter, ASM, Linux tests, Thunk tests.
How the Pieces Fit & Interact
• User invokes a CLI tool (e.g. FEXServer or FEXInterpreter) or GUI (FEXConfig).
• Tool loads the target x86 ELF via the loader in Source/Common and creates a FEXCore::Context.
• Frontend reads x86 opcodes via FEXCore opcode tables → emits IR nodes (IREmitter).
• PassManager applies IR passes (validation, redundant-flag elimination, x87 optimization, register allocation).
• JIT (Interface/Core/JIT) compiles IR batches → calls CodeEmitter to emit ARM64 machine code.
• CodeCache stores generated code; CPUBackend dispatches into that code.
• At runtime, near-native ARM64 code executes. On syscalls or traps:
– Control transfers to the LinuxEmulation subsystem in Source/Tools/LinuxEmulation, which translates or emulates Linux syscalls.
• For graphics or library calls marked for forwarding:
– ThunkLibs intercept guest calls (e.g. libGL_guest) → marshal into host calls (e.g. libGL).
• Config subsystem (FEXCore/Interface/Config + Data/AppConfig) supplies per-app tuning via JSON.
Important Patterns & Principles
• Layered architecture: Frontend → IR layer → Backend → OS interface.
• Plugin-style subsystems: LinuxEmulation, ThunkLibs, Windows port separate from core.
• CodeCache & dispatcher: minimizes overhead by caching translated blocks.
• Fallback interpreter: ensures correctness for un-translated or rare paths.
• JSON-driven configuration and automated code generation (Scripts generate IR docs, syscall tables, thunks).